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
Code refactoring (#343)
Krzysztof Pajak29c31e8c7c33
diff --git a/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs b/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.csindex 013c949d3..cd55a4632 100644--- a/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs@@ -14,8 +14,8 @@ namespace Grand.Business.Authentication.Events}public async Task Handle(EntityDeleted<Customer> notification, CancellationToken cancellationToken){- var externalrecords = _externalAuthenticationRepository.Table.Where(x => x.CustomerId == notification.Entity.Id).ToList();- foreach (var item in externalrecords)+ var externalRecords = _externalAuthenticationRepository.Table.Where(x => x.CustomerId == notification.Entity.Id).ToList();+ foreach (var item in externalRecords){await _externalAuthenticationRepository.DeleteAsync(item);}diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.csindex 531ee55f0..4e5f20660 100644--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs@@ -10,7 +10,7 @@ using Microsoft.Net.Http.Headers;namespace Grand.Business.Authentication.Services{- public partial class ApiAuthenticationService : IApiAuthenticationService+ public class ApiAuthenticationService : IApiAuthenticationService{private readonly IHttpContextAccessor _httpContextAccessor;private readonly ICustomerService _customerService;@@ -28,9 +28,6 @@ namespace Grand.Business.Authentication.Services_groupService = groupService;}- /// Get authenticated customer- /// </summary>- /// <returns>Customer</returns>public virtual async Task<Customer> GetAuthenticatedCustomer(){//whether there is a cached customer@@ -38,24 +35,24 @@ namespace Grand.Business.Authentication.Servicesreturn _cachedCustomer;Customer customer = null;-+ if (_httpContextAccessor.HttpContext == null) return null;+//try to get authenticated user identitystring authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith(JwtBearerDefaults.AuthenticationScheme))return null;- if (!_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata"))+ if (_httpContextAccessor.HttpContext.Request.Path.Value != null+ && !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata")){customer = await ApiCustomer();- if (customer != null)- {- _cachedCustomer = customer;- return _cachedCustomer;- }- return null;+ if (customer == null) return null;+ _cachedCustomer = customer;+ return _cachedCustomer;}- var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);+ var authenticateResult =+ await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);if (!authenticateResult.Succeeded)return null;@@ -64,43 +61,41 @@ namespace Grand.Business.Authentication.Servicesif (emailClaim != null)customer = await _customerService.GetCustomerByEmail(emailClaim.Value);-//whether the found customer is available- if (customer == null || !customer.Active || customer.Deleted || !await _groupService.IsRegistered(customer))+ if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))return null;//cache authenticated customer_cachedCustomer = customer;return _cachedCustomer;-}private async Task<Customer> ApiCustomer(){Customer customer = null;+ if (_httpContextAccessor.HttpContext == null) return null;var authResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(FrontendAPIConfig.Scheme);if (!authResult.Succeeded){_httpContextAccessor.HttpContext.Response.StatusCode = 400;_httpContextAccessor.HttpContext.Response.ContentType = "text/plain";- await _httpContextAccessor.HttpContext.Response.WriteAsync(authResult.Failure.Message);+ if (authResult.Failure != null)+ await _httpContextAccessor.HttpContext.Response.WriteAsync(authResult.Failure.Message);return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);- };-+ }var email = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;if (email is null){//guestvar id = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;- customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));+ if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));}else{customer = await _customerService.GetCustomerByEmail(email);}-return customer;}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.csindex 58f9934d4..719d1c2f2 100644--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs@@ -16,11 +16,11 @@ namespace Grand.Business.Authentication.Services/// <summary>/// Represents service using cookie middleware for the authentication/// </summary>- public partial class CookieAuthenticationService : IGrandAuthenticationService+ public class CookieAuthenticationService : IGrandAuthenticationService{#region Const- private string CUSTOMER_COOKIE_NAME => $"{_securityConfig.CookiePrefix}Customer";+ private string CustomerCookieName => $"{_securityConfig.CookiePrefix}Customer";#endregion@@ -44,9 +44,9 @@ namespace Grand.Business.Authentication.Services/// <param name="customerSettings">Customer settings</param>/// <param name="customerService">Customer service</param>/// <param name="groupService">Group service</param>- /// <param name="userFieldService">Generic sttribute service</param>+ /// <param name="userFieldService">Generic attribute service</param>/// <param name="httpContextAccessor">HTTP context accessor</param>- /// <param name="SecurityConfig">SecurityConfig</param>+ /// <param name="securityConfig">SecurityConfig</param>public CookieAuthenticationService(CustomerSettings customerSettings,ICustomerService customerService,@@ -88,15 +88,15 @@ namespace Grand.Business.Authentication.Servicesclaims.Add(new Claim(ClaimTypes.Email, customer.Email, ClaimValueTypes.Email, _securityConfig.CookieClaimsIssuer));//add token- var passwordtoken = await customer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.PasswordToken);- if (string.IsNullOrEmpty(passwordtoken))+ var passwordToken = await customer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.PasswordToken);+ if (string.IsNullOrEmpty(passwordToken)){- var passwordguid = Guid.NewGuid().ToString();- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, passwordguid);- claims.Add(new Claim(ClaimTypes.UserData, passwordguid, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));+ var passwordGuid = Guid.NewGuid().ToString();+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, passwordGuid);+ claims.Add(new Claim(ClaimTypes.UserData, passwordGuid, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));}else- claims.Add(new Claim(ClaimTypes.UserData, passwordtoken, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));+ claims.Add(new Claim(ClaimTypes.UserData, passwordToken, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));//create principal for the present scheme of authenticationvar userIdentity = new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme);@@ -110,7 +110,9 @@ namespace Grand.Business.Authentication.Services};//sign in user- await _httpContextAccessor.HttpContext.SignInAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);+ if (_httpContextAccessor.HttpContext != null)+ await _httpContextAccessor.HttpContext.SignInAsync(+ GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);//cache authenticated customer_cachedCustomer = customer;@@ -125,9 +127,14 @@ namespace Grand.Business.Authentication.Services_cachedCustomer = null;//and then sign out customer from the present scheme of authentication- await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme);- //sign out also from other schema- await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme);+ if (_httpContextAccessor.HttpContext != null)+ {+ await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults+ .AuthenticationScheme);+ //sign out also from other schema+ await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults+ .ExternalAuthenticationScheme);+ }}/// <summary>@@ -141,6 +148,7 @@ namespace Grand.Business.Authentication.Servicesreturn _cachedCustomer;//get the authenticated user identity+ if (_httpContextAccessor.HttpContext == null) return _cachedCustomer;var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme);if (!authenticateResult.Succeeded)return null;@@ -165,19 +173,19 @@ namespace Grand.Business.Authentication.Servicesif (customer != null){- 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)+ if (tokenClaim == null || tokenClaim.Value != passwordToken){customer = null;}}}//Check if the found customer is available- if (customer == null || !customer.Active || customer.Deleted || !await _groupService.IsRegistered(customer))+ if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))return null;//Cache the authenticated customer@@ -192,10 +200,7 @@ namespace Grand.Business.Authentication.Services/// <returns>String value of cookie</returns>public virtual Task<string> GetCustomerGuid(){- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)- return Task.FromResult<string>(null);-- return Task.FromResult(_httpContextAccessor.HttpContext.Request.Cookies[CUSTOMER_COOKIE_NAME]);+ return _httpContextAccessor.HttpContext?.Request == null ? Task.FromResult<string>(null) : Task.FromResult(_httpContextAccessor.HttpContext.Request.Cookies[CustomerCookieName]);}/// <summary>@@ -204,11 +209,11 @@ namespace Grand.Business.Authentication.Services/// <param name="customerGuid">Guid of the customer</param>public virtual Task SetCustomerGuid(Guid customerGuid){- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Response == null)+ if (_httpContextAccessor.HttpContext?.Response == null)return Task.CompletedTask;//Delete existing cookie value- _httpContextAccessor.HttpContext.Response.Cookies.Delete(CUSTOMER_COOKIE_NAME);+ _httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);//Get the date date of current cookie expirationvar cookieExpiresDate = DateTime.UtcNow.AddHours(CommonHelper.CookieAuthExpires);@@ -222,7 +227,7 @@ namespace Grand.Business.Authentication.ServicesHttpOnly = true,Expires = cookieExpiresDate};- _httpContextAccessor.HttpContext.Response.Cookies.Append(CUSTOMER_COOKIE_NAME, customerGuid.ToString(), options);+ _httpContextAccessor.HttpContext.Response.Cookies.Append(CustomerCookieName, customerGuid.ToString(), options);return Task.CompletedTask;}diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.csindex b761f041e..7b4acae71 100644--- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs@@ -20,7 +20,7 @@ namespace Grand.Business.Authentication.Services/// <summary>/// Determines the external authentication service implementation/// </summary>- public partial class ExternalAuthenticationService : IExternalAuthenticationService+ public class ExternalAuthenticationService : IExternalAuthenticationService{#region Fields@@ -123,8 +123,7 @@ namespace Grand.Business.Authentication.Services/// <returns>Result of an authentication</returns>protected virtual async Task<IActionResult> RegisterNewUser(ExternalAuthParam parameters, string returnUrl){- var approved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||- _customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation;+ var approved = _customerSettings.UserRegistrationType is UserRegistrationType.Standard or UserRegistrationType.EmailValidation;//create registration requestvar registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,@@ -142,25 +141,21 @@ namespace Grand.Business.Authentication.Services//allow to save other customer values by consuming this eventawait _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters, registrationResult));- //raise vustomer registered event+ //raise customer registered eventawait _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));//associate external account with registered userawait AssociateCustomer(_workContext.CurrentCustomer, parameters);//authenticate- if (approved)- {- await _authenticationService.SignIn(_workContext.CurrentCustomer, false);-- return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });- }-- //registration is succeeded but isn't approved by admin- if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)- return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval });-- return Error(new[] { "Error on registration" });+ if (!approved)+ return _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval+ ? new RedirectToRouteResult("RegisterResult",+ new { resultId = (int)UserRegistrationType.AdminApproval })+ : Error(new[] { "Error on registration" });+ await _authenticationService.SignIn(_workContext.CurrentCustomer, false);++ return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });}/// <summary>@@ -280,7 +275,7 @@ namespace Grand.Business.Authentication.Services#endregion/// <summary>- /// Accociate external account with customer+ /// Associate external account with customer/// </summary>/// <param name="customer">Customer</param>/// <param name="parameters">External authentication parameters</param>@@ -295,7 +290,7 @@ namespace Grand.Business.Authentication.ServicesExternalIdentifier = parameters.Identifier,ExternalDisplayIdentifier = parameters.Name,OAuthAccessToken = parameters.AccessToken,- ProviderSystemName = parameters.ProviderSystemName,+ ProviderSystemName = parameters.ProviderSystemName};await _externalAuthenticationRecordRepository.InsertAsync(externalAuthenticationRecord);@@ -335,7 +330,7 @@ namespace Grand.Business.Authentication.Services/// <summary>/// Delete the external authentication/// </summary>- /// <param name="externalAuthenticationRecord">External authentication</param>+ /// <param name="externalAuthentication">External authentication</param>public virtual async Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication){if (externalAuthentication == null)diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.csindex 6d0419372..320b22f6e 100644--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs@@ -22,9 +22,11 @@ namespace Grand.Business.Authentication.Services/// <summary>/// Valid/// </summary>- /// <param name="customer">Customer</param>+ /// <param name="context">Context</param>public virtual async Task<bool> Valid(TokenValidatedContext context){+ if (context.Principal == null) return await Task.FromResult(false);+_email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;var token = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;if (string.IsNullOrEmpty(token))@@ -32,30 +34,31 @@ namespace Grand.Business.Authentication.Services_errorMessage = "Wrong token, change password on the customer and create token again";return await Task.FromResult(false);}+if (string.IsNullOrEmpty(_email)){_errorMessage = "Email not exists in the context";return await Task.FromResult(false);}+var customer = await _customerService.GetCustomerByEmail(_email);- if (customer == null || !customer.Active || customer.Deleted)+ if (customer is not { Active: true } || customer.Deleted){_errorMessage = "Email not exists/or not active in the customer table";return await Task.FromResult(false);}- var userapi = await _userApiService.GetUserByEmail(_email);- if (userapi == null || !userapi.IsActive)++ var userApi = await _userApiService.GetUserByEmail(_email);+ if (userApi is not { IsActive: true }){_errorMessage = "User api not exists/or not active in the user api table";return await Task.FromResult(false);}- if (userapi.Token != token)- {- _errorMessage = "Wrong token, generate again";- return await Task.FromResult(false);- }- return await Task.FromResult(true);+ if (userApi.Token == token) return await Task.FromResult(true);+ _errorMessage = "Wrong token, generate again";+ return await Task.FromResult(false);+}/// <summary>diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.csindex 41aee734c..99c732774 100644--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs@@ -27,6 +27,7 @@ namespace Grand.Business.Authentication.Servicespublic async Task<bool> Valid(TokenValidatedContext context){+ if (context.Principal == null) return false;var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;var passwordToken = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;var refreshId = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "RefreshId")?.Value;@@ -35,7 +36,7 @@ namespace Grand.Business.Authentication.Services{//guestvar id = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;- customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));+ if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));}else{@@ -54,28 +55,25 @@ namespace Grand.Business.Authentication.Services}var refreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);- if (refreshToken is null || string.IsNullOrEmpty(refreshId) || !refreshId.Equals(refreshToken?.RefreshId))+ if (refreshToken is null || string.IsNullOrEmpty(refreshId) || !refreshId.Equals(refreshToken.RefreshId)){_errorMessage = "Invalid token or cancel by refresh token";return false;}- if (!(await _permissionService.Authorize(StandardPermission.AllowUseApi, customer)))+ if (!await _permissionService.Authorize(StandardPermission.AllowUseApi, customer)){_errorMessage = "You do not have permission to use API operation (Customer group)";return false;}- var customerPasswordtoken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);+ var customerPasswordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);var isGuest = await _groupService.IsGuest(customer);- if (!isGuest && (string.IsNullOrEmpty(passwordToken) || !passwordToken.Equals(customerPasswordtoken)))- {- _errorMessage = "Invalid password token, create new token";- return false;- }--- return true;+ if (isGuest || (!string.IsNullOrEmpty(passwordToken) && passwordToken.Equals(customerPasswordToken)))+ return true;++ _errorMessage = "Invalid password token, create new token";+ return false;}diff --git a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.csindex 26a321e81..1fc225d21 100644--- a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs+++ b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs@@ -24,16 +24,14 @@ namespace Grand.Business.Authentication.Servicespublic string GenerateRefreshToken(){var randomNumber = new byte[32];- using (var rng = RandomNumberGenerator.Create())- {- rng.GetBytes(randomNumber);- return Convert.ToBase64String(randomNumber);- }+ using var rng = RandomNumberGenerator.Create();+ rng.GetBytes(randomNumber);+ return Convert.ToBase64String(randomNumber);}public async Task<RefreshToken> SaveRefreshTokenToCustomer(Customer customer, string refreshToken){- var token = new RefreshToken() {+ var token = new RefreshToken {RefreshId=Guid.NewGuid().ToString(),Token = refreshToken,IsActive = true,@@ -59,10 +57,8 @@ namespace Grand.Business.Authentication.Services};var tokenHandler = new JwtSecurityTokenHandler();- SecurityToken securityToken;- var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);- var jwtSecurityToken = securityToken as JwtSecurityToken;- if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);+ if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))throw new SecurityTokenException("Invalid token");return principal;diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.csindex 4732c9a51..ec292324b 100644--- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs@@ -15,7 +15,7 @@ namespace Grand.Business.Authentication.Servicesprivate readonly IWorkContext _workContext;private readonly IUserFieldService _userFieldService;private readonly IServiceProvider _serviceProvider;- private TwoFactorAuthenticator _twoFactorAuthentication;+ private readonly TwoFactorAuthenticator _twoFactorAuthentication;public TwoFactorAuthenticationService(IWorkContext workContext,@@ -36,14 +36,12 @@ namespace Grand.Business.Authentication.Servicesreturn _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim());case TwoFactorAuthenticationType.EmailVerification:- var customertoken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);- if (customertoken != token.Trim())- return false;- var validuntil = customer.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);- if (validuntil < DateTime.UtcNow)+ var customerToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);+ if (customerToken != token?.Trim())return false;+ var validUntil = customer.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);+ return validUntil >= DateTime.UtcNow;- return true;case TwoFactorAuthenticationType.SMSVerification:var smsVerificationService = _serviceProvider.GetRequiredService<ISMSVerificationService>();return await smsVerificationService.Authenticate(secretKey, token.Trim(), customer);@@ -59,7 +57,7 @@ namespace Grand.Business.Authentication.Servicesswitch (twoFactorAuthenticationType){case TwoFactorAuthenticationType.AppVerification:- var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName, customer.Email, secretKey, false, 3);+ var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName, customer.Email, secretKey, false);model.CustomValues.Add("QrCodeImageUrl", setupInfo.QrCodeSetupImageUrl);model.CustomValues.Add("ManualEntryQrCode", setupInfo.ManualEntryKey);break;@@ -79,7 +77,6 @@ namespace Grand.Business.Authentication.Servicesdefault:break;}-return model;}diff --git a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.csindex d55915c94..dc3c3e28b 100644--- a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs+++ b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs@@ -30,13 +30,13 @@ namespace Grand.Business.Catalog.Commands.Handlersif (request.Product == null)throw new ArgumentNullException(nameof(request.Product));- int approvedRatingSum = 0;- int notApprovedRatingSum = 0;- int approvedTotalReviews = 0;- int notApprovedTotalReviews = 0;+ var approvedRatingSum = 0;+ var notApprovedRatingSum = 0;+ var approvedTotalReviews = 0;+ var notApprovedTotalReviews = 0;var reviews = await _productReviewService.GetAllProductReviews(null, null, null, null, null,- null, request.Product.Id, 0, int.MaxValue);+ null, request.Product.Id);foreach (var pr in reviews){diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.csindex 69860ddfc..21d091974 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs@@ -48,41 +48,48 @@ namespace Grand.Business.Catalog.Events.Handlers{var discount = notification.Entity;- if (discount.DiscountTypeId == DiscountType.AssignedToSkus)+ switch (discount.DiscountTypeId){- //delete on the product- await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);+ case DiscountType.AssignedToSkus:+ //delete on the product+ await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);- }-- if (discount.DiscountTypeId == DiscountType.AssignedToCategories)- {- //delete on the category- await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);- }- if (discount.DiscountTypeId == DiscountType.AssignedToBrands)- {- //delete on the brand- await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);- }- if (discount.DiscountTypeId == DiscountType.AssignedToCollections)- {- //delete on the collection- await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);- }- if (discount.DiscountTypeId == DiscountType.AssignedToVendors)- {- //delete on the vendor- await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ break;+ case DiscountType.AssignedToCategories:+ //delete on the category+ await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);+ break;+ case DiscountType.AssignedToBrands:+ //delete on the brand+ await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);+ break;+ case DiscountType.AssignedToCollections:+ //delete on the collection+ await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);+ break;+ case DiscountType.AssignedToVendors:+ //delete on the vendor+ await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ break;+ case DiscountType.AssignedToOrderTotal:+ break;+ case DiscountType.AssignedToShipping:+ break;+ case DiscountType.AssignedToOrderSubTotal:+ break;+ case DiscountType.AssignedToAllProducts:+ break;+ default:+ break;}//remove coupon codesdiff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.csindex 2d257f84b..98b6ed26c 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs@@ -51,7 +51,7 @@ namespace Grand.Business.Catalog.Events.Handlers//delete cross sales productawait _productRepository.Pull(string.Empty, x => x.CrossSellProduct, notification.Entity.Id);- //delete recomended product+ //delete recommended productawait _productRepository.Pull(string.Empty, x => x.RecommendedProduct, notification.Entity.Id);//delete review@@ -75,9 +75,11 @@ namespace Grand.Business.Catalog.Events.Handlers//insert to deleted productsvar productDeleted = JsonConvert.DeserializeObject<ProductDeleted>(JsonConvert.SerializeObject(notification.Entity));- productDeleted.DeletedOnUtc = DateTime.UtcNow;- await _productDeletedRepository.InsertAsync(productDeleted);-+ if (productDeleted != null)+ {+ productDeleted.DeletedOnUtc = DateTime.UtcNow;+ await _productDeletedRepository.InsertAsync(productDeleted);+ }}}}diff --git a/src/Business/Grand.Business.Catalog/Extensions/MimeTypeExtensions.cs b/src/Business/Grand.Business.Catalog/Extensions/MimeTypeExtensions.csnew file mode 100644index 000000000..4decbd71a--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Extensions/MimeTypeExtensions.cs@@ -0,0 +1,13 @@+using Microsoft.AspNetCore.StaticFiles;++namespace Grand.Business.Catalog.Extensions;++public static class MimeTypeExtensions+{+ public static string GetMimeTypeFromFilePath(string filePath)+ {+ new FileExtensionContentTypeProvider().TryGetContentType(filePath, out var mimeType);+ //set to jpeg in case mime type cannot be found+ return mimeType ?? "image/jpeg";+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.csindex 96d140e4a..f8f04336c 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs@@ -37,13 +37,9 @@ namespace Grand.Business.Catalog.Queries.Handlersvar productIds = query.Take(request.ProductsNumber).ToList();- var products = new List<Product>();var ids = await _productService.GetProductsByIds(productIds.Distinct().ToArray());- foreach (var product in ids)- if (product.Published)- products.Add(product);- return products;+ return ids.Where(product => product.Published).ToList();});}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.csindex 7d0525b66..0f2bed418 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs@@ -21,21 +21,16 @@ namespace Grand.Business.Catalog.Queries.Handlerspublic async Task<double?> Handle(GetPriceByCustomerProductQuery request, CancellationToken cancellationToken){var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, request.CustomerId, request.ProductId);- var productprice = _cacheBase.Get(key, () =>+ var productPrice = _cacheBase.Get(key, () =>{var pp = _customerProductPriceRepository.Table- .Where(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId)- .FirstOrDefault();- if (pp == null)- return (null, false);- else- return (pp, true);+ .FirstOrDefault(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId);+ return pp == null ? (null, false) : (pp, true);});- if (!productprice.Item2)+ if (!productPrice.Item2)return await Task.FromResult(default(double?));- else- return await Task.FromResult(productprice.pp.Price);+ return await Task.FromResult(productPrice.pp.Price);}}}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.csindex 40d1deff4..c352130fb 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Catalog.Queries.Handlerspublic async Task<Product> Handle(GetProductArchByIdQuery request, CancellationToken cancellationToken){- return await _productDeletedRepository.GetByIdAsync(request.Id) as Product;+ return await _productDeletedRepository.GetByIdAsync(request.Id);}}}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.csindex 5e540b0b3..d3a5b91ff 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs@@ -37,13 +37,9 @@ namespace Grand.Business.Catalog.Queries.Handlersvar productIds = query.ToList();- var products = new List<Product>();var ids = await _productService.GetProductsByIds(productIds.Distinct().ToArray());- foreach (var product in ids)- if (product.Published)- products.Add(product);- return products;+ return ids.Where(product => product.Published).ToList();});}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.csindex cc9a1ed16..fb93bbcf5 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs@@ -158,7 +158,7 @@ namespace Grand.Business.Catalog.Queries.Handlers||(p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower()))||- (p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())))+ p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))||(request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())));@@ -205,20 +205,18 @@ namespace Grand.Business.Catalog.Queries.Handlers{var spec = new HashSet<string>();Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();- foreach (string key in request.FilteredSpecs)+ foreach (var key in request.FilteredSpecs){var specification = await _specificationAttributeService.GetSpecificationAttributeByOptionId(key);- if (specification != null)+ if (specification == null) continue;+ spec.Add(specification.Id);+ if (!dictionary.ContainsKey(specification.Id)){- spec.Add(specification.Id);- if (!dictionary.ContainsKey(specification.Id))- {- //add- dictionary.Add(specification.Id, new List<string>());- querySpecification = querySpecification.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == specification.Id && y.AllowFiltering));- }- dictionary[specification.Id].Add(key);+ //add+ dictionary.Add(specification.Id, new List<string>());+ querySpecification = querySpecification.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == specification.Id && y.AllowFiltering));}+ dictionary[specification.Id].Add(key);}foreach (var item in dictionary)@@ -233,113 +231,103 @@ namespace Grand.Business.Catalog.Queries.Handlersquery = query.Where(x => x.ProductSpecificationAttributes.Any(y => request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId)));}- if (request.OrderBy == ProductSortingEnum.Position && request.CategoryIds != null && request.CategoryIds.Any())- {- //category position- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory) :- query.OrderBy(x => x.DisplayOrderCategory);- }- else if (request.OrderBy == ProductSortingEnum.Position && !string.IsNullOrEmpty(request.BrandId))- {- //brand position- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand) :- query.OrderBy(x => x.DisplayOrderBrand);- }- else if (request.OrderBy == ProductSortingEnum.Position && !string.IsNullOrEmpty(request.CollectionId))- {- //collection position- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection) :- query.OrderBy(x => x.DisplayOrderCollection);- }- else if (request.OrderBy == ProductSortingEnum.Position)- {- //otherwise sort by name- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :- query.OrderBy(x => x.Name);- }- else if (request.OrderBy == ProductSortingEnum.NameAsc)- {- //Name: A to Z- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :- query.OrderBy(x => x.Name);- }- else if (request.OrderBy == ProductSortingEnum.NameDesc)- {- //Name: Z to A- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name) :- query.OrderByDescending(x => x.Name);- }- else if (request.OrderBy == ProductSortingEnum.PriceAsc)- {- //Price: Low to High- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.Price) :- query.OrderBy(x => x.Price);- }- else if (request.OrderBy == ProductSortingEnum.PriceDesc)- {- //Price: High to Low- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price) :- query.OrderByDescending(x => x.Price);- }- else if (request.OrderBy == ProductSortingEnum.CreatedOn)- {- //creation date- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc) :- query.OrderBy(x => x.CreatedOnUtc);-- }- else if (request.OrderBy == ProductSortingEnum.OnSale)- {- //on sale- query = query.OrderBy(x => x.OnSale);-- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale) :- query.OrderBy(x => x.OnSale);- }- else if (request.OrderBy == ProductSortingEnum.MostViewed)- {- //most viewed- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed) :- query.OrderByDescending(x => x.Viewed);- }- else if (request.OrderBy == ProductSortingEnum.BestSellers)- {- //best seller- query = query.OrderByDescending(x => x.Sold);-- query = _catalogSettings.SortingByAvailability ?- query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold) :- query.OrderByDescending(x => x.Sold);+ switch (request.OrderBy)+ {+ case ProductSortingEnum.Position when request.CategoryIds != null && request.CategoryIds.Any():+ //category position+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory) :+ query.OrderBy(x => x.DisplayOrderCategory);+ break;+ case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.BrandId):+ //brand position+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand) :+ query.OrderBy(x => x.DisplayOrderBrand);+ break;+ case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.CollectionId):+ //collection position+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection) :+ query.OrderBy(x => x.DisplayOrderCollection);+ break;+ case ProductSortingEnum.Position:+ //otherwise sort by name+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :+ query.OrderBy(x => x.Name);+ break;+ case ProductSortingEnum.NameAsc:+ //Name: A to Z+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :+ query.OrderBy(x => x.Name);+ break;+ case ProductSortingEnum.NameDesc:+ //Name: Z to A+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name) :+ query.OrderByDescending(x => x.Name);+ break;+ case ProductSortingEnum.PriceAsc:+ //Price: Low to High+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Price) :+ query.OrderBy(x => x.Price);+ break;+ case ProductSortingEnum.PriceDesc:+ //Price: High to Low+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price) :+ query.OrderByDescending(x => x.Price);+ break;+ case ProductSortingEnum.CreatedOn:+ //creation date+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc) :+ query.OrderBy(x => x.CreatedOnUtc);+ break;+ case ProductSortingEnum.OnSale:+ //on sale+ query = query.OrderBy(x => x.OnSale);++ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale) :+ query.OrderBy(x => x.OnSale);+ break;+ case ProductSortingEnum.MostViewed:+ //most viewed+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed) :+ query.OrderByDescending(x => x.Viewed);+ break;+ case ProductSortingEnum.BestSellers:+ //best seller+ query = query.OrderByDescending(x => x.Sold);++ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold) :+ query.OrderByDescending(x => x.Sold);+ break;+ default:+ break;}var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);- if (request.LoadFilterableSpecificationAttributeOptionIds && !_catalogSettings.IgnoreFilterableSpecAttributeOption)+ if (!request.LoadFilterableSpecificationAttributeOptionIds ||+ _catalogSettings.IgnoreFilterableSpecAttributeOption)+ return (products, filterableSpecificationAttributeOptionIds);{- IList<string> specyfication = new List<string>();var filterSpecExists = querySpecification.Where(x => x.ProductSpecificationAttributes.Any(x => x.AllowFiltering));var qspec = from p in filterSpecExists- from item in p.ProductSpecificationAttributes- select item;+ from item in p.ProductSpecificationAttributes+ select item;var groupQuerySpec = qspec.Where(x => x.AllowFiltering).GroupBy(x => new { SpecificationAttributeOptionId = x.SpecificationAttributeOptionId }).ToList();- foreach (var item in groupQuerySpec)- {- specyfication.Add(item.Key.SpecificationAttributeOptionId);- }+ IList<string> specyfication = groupQuerySpec.Select(item => item.Key.SpecificationAttributeOptionId).ToList();filterableSpecificationAttributeOptionIds = specyfication.ToList();}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.csindex e44cba994..e3244ca6b 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs@@ -40,13 +40,9 @@ namespace Grand.Business.Catalog.Queries.Handlersvar productIds = query.Take(request.ProductsNumber).ToList();- var products = new List<Product>();var ids = await _productService.GetProductsByIds(productIds.Distinct().ToArray());- foreach (var product in ids)- if (product.Published)- products.Add(product);- return products;+ return ids.Where(product => product.Published).ToList();});}diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.csindex 8e9b604aa..5a3f446ff 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs@@ -16,10 +16,7 @@ namespace Grand.Business.Catalog.Queries.Handlerspublic Task<Vendor> Handle(GetVendorByIdQuery request, CancellationToken cancellationToken){- if (string.IsNullOrWhiteSpace(request.Id))- return Task.FromResult<Vendor>(null);-- return _vendorRepository.GetByIdAsync(request.Id);+ return string.IsNullOrWhiteSpace(request.Id) ? Task.FromResult<Vendor>(null) : _vendorRepository.GetByIdAsync(request.Id);}}}diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.csindex 2440dc122..4a2a4b858 100644--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Brands/// <summary>/// Brand layout service/// </summary>- public partial class BrandLayoutService : IBrandLayoutService+ public class BrandLayoutService : IBrandLayoutService{#region Fields@@ -64,7 +64,7 @@ namespace Grand.Business.Catalog.Services.Brands/// <returns>Brand layout</returns>public virtual Task<BrandLayout> GetBrandLayoutById(string brandLayoutId){- string key = string.Format(CacheKey.BRAND_LAYOUT_BY_ID_KEY, brandLayoutId);+ var key = string.Format(CacheKey.BRAND_LAYOUT_BY_ID_KEY, brandLayoutId);return _cacheBase.GetAsync(key, () => _brandLayoutRepository.GetByIdAsync(brandLayoutId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.csindex d4a3c1b07..e83094fc8 100644--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs@@ -15,7 +15,7 @@ namespace Grand.Business.Catalog.Services.Brands/// <summary>/// Brand service/// </summary>- public partial class BrandService : IBrandService+ public class BrandService : IBrandService{#region Fields@@ -65,10 +65,10 @@ namespace Grand.Business.Catalog.Services.Brandsif (!showHidden)query = query.Where(m => m.Published);- if (!String.IsNullOrWhiteSpace(brandName))+ if (!string.IsNullOrWhiteSpace(brandName))query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(brandName.ToLower()));- if ((!CommonHelper.IgnoreAcl || (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)))+ if (!CommonHelper.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)){if (!showHidden && !CommonHelper.IgnoreAcl){@@ -79,7 +79,7 @@ namespace Grand.Business.Catalog.Services.Brandsselect p;}- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){//Limited to stores rulesquery = from p in query@@ -98,7 +98,7 @@ namespace Grand.Business.Catalog.Services.Brands/// <returns>Brand</returns>public virtual Task<Brand> GetBrandById(string brandId){- string key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId);+ var key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId);return _cacheBase.GetAsync(key, () => _brandRepository.GetByIdAsync(brandId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.csindex 5aa60676a..64d52f042 100644--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Categories/// <summary>/// Category layout service/// </summary>- public partial class CategoryLayoutService : ICategoryLayoutService+ public class CategoryLayoutService : ICategoryLayoutService{#region Fields@@ -64,7 +64,7 @@ namespace Grand.Business.Catalog.Services.Categories/// <returns>Category layout</returns>public virtual Task<CategoryLayout> GetCategoryLayoutById(string categoryLayoutId){- string key = string.Format(CacheKey.CATEGORY_LAYOUT_BY_ID_KEY, categoryLayoutId);+ var key = string.Format(CacheKey.CATEGORY_LAYOUT_BY_ID_KEY, categoryLayoutId);return _cacheBase.GetAsync(key, () => _categoryLayoutRepository.GetByIdAsync(categoryLayoutId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.csindex add3504ae..eab78bad6 100644--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Catalog.Services.Categories/// <summary>/// Category service/// </summary>- public partial class CategoryService : ICategoryService+ public class CategoryService : ICategoryService{#region Fields@@ -37,6 +37,7 @@ namespace Grand.Business.Catalog.Services.Categories/// <param name="cacheBase">Cache manager</param>/// <param name="categoryRepository">Category repository</param>/// <param name="workContext">Work context</param>+ /// <param name="mediator">Mediator</param>/// <param name="aclService">ACL service</param>public CategoryService(ICacheBase cacheBase,IRepository<Category> categoryRepository,@@ -60,6 +61,7 @@ namespace Grand.Business.Catalog.Services.Categories/// </summary>/// <param name="parentId">Parent Id</param>/// <param name="categoryName">Category name</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>@@ -72,13 +74,13 @@ namespace Grand.Business.Catalog.Services.Categoriesif (!showHidden)query = query.Where(c => c.Published);- if (!String.IsNullOrWhiteSpace(categoryName))+ if (!string.IsNullOrWhiteSpace(categoryName))query = query.Where(m => m.Name.ToLowerInvariant().Contains(categoryName.ToLowerInvariant()));if (parentId != null)query = query.Where(m => m.ParentCategoryId == parentId);- if ((!CommonHelper.IgnoreAcl || (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)))+ if (!CommonHelper.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)){if (!showHidden && !CommonHelper.IgnoreAcl){@@ -88,7 +90,7 @@ namespace Grand.Business.Catalog.Services.Categorieswhere !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))select p;}- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){//Limited to stores rulequery = from p in query@@ -115,24 +117,29 @@ namespace Grand.Business.Catalog.Services.Categoriesquery = query.Where(c => c.Published && c.IncludeInMenu);- if ((!CommonHelper.IgnoreAcl || (!String.IsNullOrEmpty(_workContext.CurrentStore.Id) && !CommonHelper.IgnoreStoreLimitations)))+ switch (CommonHelper.IgnoreAcl){- if (!CommonHelper.IgnoreAcl)+ case true when+ string.IsNullOrEmpty(_workContext.CurrentStore.Id) || CommonHelper.IgnoreStoreLimitations:+ return await Task.FromResult(query.ToList());+ case false:{//Limited to customer group (access control list)var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;- }- if (!String.IsNullOrEmpty(_workContext.CurrentStore.Id) && !CommonHelper.IgnoreStoreLimitations)- {- //Limited to stores rule- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)- select p;+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;+ break;}}++ if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id) && !CommonHelper.IgnoreStoreLimitations)+ {+ //Limited to stores rule+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)+ select p;+ }return await Task.FromResult(query.ToList());}@@ -148,7 +155,7 @@ namespace Grand.Business.Catalog.Services.Categories{var storeId = _workContext.CurrentStore.Id;var customer = _workContext.CurrentCustomer;- string key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden, customer.Id, storeId, includeAllLevels);+ var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden, customer.Id, storeId, includeAllLevels);return await _cacheBase.GetAsync(key, async () =>{var query = _categoryRepository.Table.Where(c => c.ParentCategoryId == parentCategoryId);@@ -157,7 +164,7 @@ namespace Grand.Business.Catalog.Services.Categoriesif (!showHidden && (!CommonHelper.IgnoreAcl || !CommonHelper.IgnoreStoreLimitations)){- if (!showHidden && !CommonHelper.IgnoreAcl)+ if (!CommonHelper.IgnoreAcl){//Limited to customer groups rulesvar allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();@@ -175,16 +182,14 @@ namespace Grand.Business.Catalog.Services.Categories}var categories = query.OrderBy(x => x.DisplayOrder).ToList();- if (includeAllLevels)+ if (!includeAllLevels) return categories;+ var childCategories = new List<Category>();+ //add child levels+ foreach (var category in categories){- var childCategories = new List<Category>();- //add child levels- foreach (var category in categories)- {- childCategories.AddRange(await GetAllCategoriesByParentCategoryId(category.Id, showHidden, includeAllLevels));- }- categories.AddRange(childCategories);+ childCategories.AddRange(await GetAllCategoriesByParentCategoryId(category.Id, showHidden, true));}+ categories.AddRange(childCategories);return categories;});}@@ -234,7 +239,6 @@ namespace Grand.Business.Catalog.Services.Categories/// <summary>/// Gets all categories displayed in the search box/// </summary>- /// <param name="showHidden">A value that indicates if it should shows hidden records<</param>/// <returns>Categories</returns>public virtual async Task<IList<Category>> GetAllCategoriesSearchBox(){@@ -253,9 +257,6 @@ namespace Grand.Business.Catalog.Services.Categories/// Get category breadcrumb/// </summary>/// <param name="category">Category</param>- /// <param name="categoryService">Category service</param>- /// <param name="aclService">ACL service</param>- /// <param name="storeLinkService">Store link service</param>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>/// <returns>Category breadcrumb </returns>public virtual async Task<IList<Category>> GetCategoryBreadCrumb(Category category, bool showHidden = false)@@ -323,15 +324,15 @@ namespace Grand.Business.Catalog.Services.Categories/// <returns>Formatted breadcrumb</returns>public virtual async Task<string> GetFormattedBreadCrumb(Category category, string separator = ">>", string languageId = ""){- string result = string.Empty;+ var result = string.Empty;var breadcrumb = await GetCategoryBreadCrumb(category, true);- for (int i = 0; i <= breadcrumb.Count - 1; i++)+ for (var i = 0; i <= breadcrumb.Count - 1; i++){var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);- result = String.IsNullOrEmpty(result)+ result = string.IsNullOrEmpty(result)? categoryName- : string.Format("{0} {1} {2}", result, separator, categoryName);+ : $"{result} {separator} {categoryName}";}return result;@@ -348,15 +349,15 @@ namespace Grand.Business.Catalog.Services.Categoriespublic virtual string GetFormattedBreadCrumb(Category category,IList<Category> allCategories, string separator = ">>", string languageId = ""){- string result = string.Empty;+ var result = string.Empty;var breadcrumb = GetCategoryBreadCrumb(category, allCategories, true);- for (int i = 0; i <= breadcrumb.Count - 1; i++)+ for (var i = 0; i <= breadcrumb.Count - 1; i++){var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);- result = String.IsNullOrEmpty(result)+ result = string.IsNullOrEmpty(result)? categoryName- : string.Format("{0} {1} {2}", result, separator, categoryName);+ : $"{result} {separator} {categoryName}";}return result;@@ -382,7 +383,7 @@ namespace Grand.Business.Catalog.Services.Categories/// <returns>Category</returns>public virtual async Task<Category> GetCategoryById(string categoryId){- string key = string.Format(CacheKey.CATEGORIES_BY_ID_KEY, categoryId);+ var key = string.Format(CacheKey.CATEGORIES_BY_ID_KEY, categoryId);return await _cacheBase.GetAsync(key, () => _categoryRepository.GetByIdAsync(categoryId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.csindex acefb102f..bc7112be2 100644--- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs@@ -43,10 +43,10 @@ namespace Grand.Business.Catalog.Services.Categoriespublic virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCategoryId(string categoryId,int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false){- if (String.IsNullOrEmpty(categoryId))+ if (string.IsNullOrEmpty(categoryId))return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);- string key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);+ var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);return await _cacheBase.GetAsync(key, () =>{var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));@@ -73,7 +73,7 @@ namespace Grand.Business.Catalog.Services.Categories}- var query_productCategories = from prod in query+ var queryProductCategories = from prod in queryfrom pc in prod.ProductCategoriesselect new ProductsCategory{@@ -81,15 +81,15 @@ namespace Grand.Business.Catalog.Services.CategoriesDisplayOrder = pc.DisplayOrder,Id = pc.Id,ProductId = prod.Id,- IsFeaturedProduct = pc.IsFeaturedProduct,+ IsFeaturedProduct = pc.IsFeaturedProduct};- query_productCategories = from pm in query_productCategories+ queryProductCategories = from pm in queryProductCategorieswhere pm.CategoryId == categoryIdorderby pm.DisplayOrderselect pm;- return Task.FromResult(new PagedList<ProductsCategory>(query_productCategories, pageIndex, pageSize));+ return Task.FromResult(new PagedList<ProductsCategory>(queryProductCategories, pageIndex, pageSize));});}diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.csindex 70330b2bd..4e42eb006 100644--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Collections/// <summary>/// Collection layout service/// </summary>- public partial class CollectionLayoutService : ICollectionLayoutService+ public class CollectionLayoutService : ICollectionLayoutService{#region Fields@@ -64,7 +64,7 @@ namespace Grand.Business.Catalog.Services.Collections/// <returns>Collection layout</returns>public virtual Task<CollectionLayout> GetCollectionLayoutById(string collectionLayoutId){- string key = string.Format(CacheKey.COLLECTION_LAYOUT_BY_ID_KEY, collectionLayoutId);+ var key = string.Format(CacheKey.COLLECTION_LAYOUT_BY_ID_KEY, collectionLayoutId);return _cacheBase.GetAsync(key, () => _collectionLayoutRepository.GetByIdAsync(collectionLayoutId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.csindex 8e970e5f6..f00df85c9 100644--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Catalog.Services.Collections/// <summary>/// Collection service/// </summary>- public partial class CollectionService : ICollectionService+ public class CollectionService : ICollectionService{#region Fields@@ -70,10 +70,10 @@ namespace Grand.Business.Catalog.Services.Collectionsif (!showHidden)query = query.Where(m => m.Published);- if (!String.IsNullOrWhiteSpace(collectionName))+ if (!string.IsNullOrWhiteSpace(collectionName))query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(collectionName.ToLower()));- if ((!CommonHelper.IgnoreAcl || (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)))+ if (!CommonHelper.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)){if (!showHidden && !CommonHelper.IgnoreAcl){@@ -84,7 +84,7 @@ namespace Grand.Business.Catalog.Services.Collectionsselect p;}- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){//Limited to stores rulesquery = from p in query@@ -124,7 +124,7 @@ namespace Grand.Business.Catalog.Services.Collections/// <returns>Collection</returns>public virtual Task<Collection> GetCollectionById(string collectionId){- string key = string.Format(CacheKey.COLLECTIONS_BY_ID_KEY, collectionId);+ var key = string.Format(CacheKey.COLLECTIONS_BY_ID_KEY, collectionId);return _cacheBase.GetAsync(key, () => _collectionRepository.GetByIdAsync(collectionId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.csindex 8118b9681..b8c3f6fda 100644--- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs@@ -42,6 +42,7 @@ namespace Grand.Business.Catalog.Services.Collections/// Gets product collection by collection id/// </summary>/// <param name="collectionId">Collection id</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>@@ -49,7 +50,7 @@ namespace Grand.Business.Catalog.Services.Collectionspublic virtual async Task<IPagedList<ProductsCollection>> GetProductCollectionsByCollectionId(string collectionId, string storeId,int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false){- string key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, storeId);+ var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, storeId);return await _cacheBase.GetAsync(key, () =>{var query = _productRepository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == collectionId));@@ -75,7 +76,7 @@ namespace Grand.Business.Catalog.Services.Collections}- var query_ProductCollection = from prod in query+ var queryProductCollection = from prod in queryfrom pm in prod.ProductCollectionsselect new ProductsCollection {Id = pm.Id,@@ -85,12 +86,12 @@ namespace Grand.Business.Catalog.Services.CollectionsCollectionId = pm.CollectionId};- query_ProductCollection = from pm in query_ProductCollection+ queryProductCollection = from pm in queryProductCollectionwhere pm.CollectionId == collectionIdorderby pm.DisplayOrderselect pm;- return Task.FromResult(new PagedList<ProductsCollection>(query_ProductCollection, pageIndex, pageSize));+ return Task.FromResult(new PagedList<ProductsCollection>(queryProductCollection, pageIndex, pageSize));});}diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.csindex 3cac9cd22..be8032331 100644--- a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <summary>/// GEO lookup service/// </summary>- public partial class GeoLookupService : IGeoLookupService+ public class GeoLookupService : IGeoLookupService{#region Fields@@ -34,7 +34,7 @@ namespace Grand.Business.Catalog.Services.Directoryprotected virtual CountryResponse GetInformation(string ipAddress){- if (String.IsNullOrEmpty(ipAddress))+ if (string.IsNullOrEmpty(ipAddress))return null;try@@ -69,10 +69,7 @@ namespace Grand.Business.Catalog.Services.Directorypublic virtual string CountryIsoCode(string ipAddress){var response = GetInformation(ipAddress);- if (response != null && response.Country != null)- return response.Country.IsoCode;-- return "";+ return response is { Country: { } } ? response.Country.IsoCode : "";}/// <summary>@@ -83,10 +80,7 @@ namespace Grand.Business.Catalog.Services.Directorypublic virtual string CountryName(string ipAddress){var response = GetInformation(ipAddress);- if (response != null && response.Country != null)- return response.Country.Name;-- return "";+ return response is { Country: { } } ? response.Country.Name : "";}#endregiondiff --git a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.csindex 6d45234de..a00828924 100644--- a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <summary>/// Measure dimension service/// </summary>- public partial class MeasureService : IMeasureService+ public class MeasureService : IMeasureService{#region Fields@@ -64,7 +64,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure dimension</returns>public virtual Task<MeasureDimension> GetMeasureDimensionById(string measureDimensionId){- string key = string.Format(CacheKey.MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId);+ var key = string.Format(CacheKey.MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId);return _cacheBase.GetAsync(key, () => _measureDimensionRepository.GetByIdAsync(measureDimensionId));}@@ -75,14 +75,11 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure dimension</returns>public virtual async Task<MeasureDimension> GetMeasureDimensionBySystemKeyword(string systemKeyword){- if (String.IsNullOrEmpty(systemKeyword))+ if (string.IsNullOrEmpty(systemKeyword))return null;var measureDimensions = await GetAllMeasureDimensions();- foreach (var measureDimension in measureDimensions)- if (measureDimension.SystemKeyword.ToLowerInvariant() == systemKeyword.ToLowerInvariant())- return measureDimension;- return null;+ return measureDimensions.FirstOrDefault(measureDimension => string.Equals(measureDimension.SystemKeyword, systemKeyword, StringComparison.InvariantCultureIgnoreCase));}/// <summary>@@ -91,7 +88,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure dimensions</returns>public virtual async Task<IList<MeasureDimension>> GetAllMeasureDimensions(){- string key = CacheKey.MEASUREDIMENSIONS_ALL_KEY;+ var key = CacheKey.MEASUREDIMENSIONS_ALL_KEY;return await _cacheBase.GetAsync(key, async () =>{var query = from md in _measureDimensionRepository.Table@@ -169,7 +166,7 @@ namespace Grand.Business.Catalog.Services.Directoryif (targetMeasureDimension == null)throw new ArgumentNullException(nameof(targetMeasureDimension));- double result = value;+ var result = value;if (result != 0 && sourceMeasureDimension.Id != targetMeasureDimension.Id){result = await ConvertToPrimaryMeasureDimension(result, sourceMeasureDimension);@@ -192,15 +189,13 @@ namespace Grand.Business.Catalog.Services.Directoryif (sourceMeasureDimension == null)throw new ArgumentNullException(nameof(sourceMeasureDimension));- double result = value;+ var result = value;var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);- if (result != 0 && sourceMeasureDimension.Id != baseDimensionIn.Id)- {- double exchangeRatio = sourceMeasureDimension.Ratio;- if (exchangeRatio == 0)- throw new GrandException(string.Format("Exchange ratio not set for dimension [{0}]", sourceMeasureDimension.Name));- result = result / exchangeRatio;- }+ 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;return result;}@@ -216,15 +211,13 @@ namespace Grand.Business.Catalog.Services.Directoryif (targetMeasureDimension == null)throw new ArgumentNullException(nameof(targetMeasureDimension));- double result = value;+ var result = value;var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);- if (result != 0 && targetMeasureDimension.Id != baseDimensionIn.Id)- {- double exchangeRatio = targetMeasureDimension.Ratio;- if (exchangeRatio == 0)- throw new GrandException(string.Format("Exchange ratio not set for dimension [{0}]", targetMeasureDimension.Name));- result = result * exchangeRatio;- }+ 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;return result;}@@ -239,7 +232,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure weight</returns>public virtual Task<MeasureWeight> GetMeasureWeightById(string measureWeightId){- string key = string.Format(CacheKey.MEASUREWEIGHTS_BY_ID_KEY, measureWeightId);+ var key = string.Format(CacheKey.MEASUREWEIGHTS_BY_ID_KEY, measureWeightId);return _cacheBase.GetAsync(key, () => _measureWeightRepository.GetByIdAsync(measureWeightId));}@@ -250,14 +243,11 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure weight</returns>public virtual async Task<MeasureWeight> GetMeasureWeightBySystemKeyword(string systemKeyword){- if (String.IsNullOrEmpty(systemKeyword))+ if (string.IsNullOrEmpty(systemKeyword))return null;var measureWeights = await GetAllMeasureWeights();- foreach (var measureWeight in measureWeights)- if (measureWeight.SystemKeyword.ToLowerInvariant() == systemKeyword.ToLowerInvariant())- return measureWeight;- return null;+ return measureWeights.FirstOrDefault(measureWeight => string.Equals(measureWeight.SystemKeyword, systemKeyword, StringComparison.InvariantCultureIgnoreCase));}/// <summary>@@ -266,7 +256,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure weights</returns>public virtual async Task<IList<MeasureWeight>> GetAllMeasureWeights(){- string key = CacheKey.MEASUREWEIGHTS_ALL_KEY;+ var key = CacheKey.MEASUREWEIGHTS_ALL_KEY;return await _cacheBase.GetAsync(key, async () =>{var query = from mw in _measureWeightRepository.Table@@ -344,7 +334,7 @@ namespace Grand.Business.Catalog.Services.Directoryif (targetMeasureWeight == null)throw new ArgumentNullException(nameof(targetMeasureWeight));- double result = value;+ var result = value;if (result != 0 && sourceMeasureWeight.Id != targetMeasureWeight.Id){result = await ConvertToPrimaryMeasureWeight(result, sourceMeasureWeight);@@ -366,15 +356,13 @@ namespace Grand.Business.Catalog.Services.Directoryif (sourceMeasureWeight == null)throw new ArgumentNullException(nameof(sourceMeasureWeight));- double result = value;+ var result = value;var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);- if (result != 0 && sourceMeasureWeight.Id != baseWeightIn.Id)- {- double exchangeRatio = sourceMeasureWeight.Ratio;- if (exchangeRatio == 0)- throw new GrandException(string.Format("Exchange ratio not set for weight [{0}]", sourceMeasureWeight.Name));- result = result / exchangeRatio;- }+ 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;return result;}@@ -390,15 +378,13 @@ namespace Grand.Business.Catalog.Services.Directoryif (targetMeasureWeight == null)throw new ArgumentNullException(nameof(targetMeasureWeight));- double result = value;+ var result = value;var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);- if (result != 0 && targetMeasureWeight.Id != baseWeightIn.Id)- {- double exchangeRatio = targetMeasureWeight.Ratio;- if (exchangeRatio == 0)- throw new GrandException(string.Format("Exchange ratio not set for weight [{0}]", targetMeasureWeight.Name));- result = result * exchangeRatio;- }+ 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;return result;}@@ -414,7 +400,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure dimension</returns>public virtual Task<MeasureUnit> GetMeasureUnitById(string measureUnitId){- string key = string.Format(CacheKey.MEASUREUNITS_BY_ID_KEY, measureUnitId);+ var key = string.Format(CacheKey.MEASUREUNITS_BY_ID_KEY, measureUnitId);return _cacheBase.GetAsync(key, () => _measureUnitRepository.GetByIdAsync(measureUnitId));}@@ -425,7 +411,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Measure unit</returns>public virtual async Task<IList<MeasureUnit>> GetAllMeasureUnits(){- string key = CacheKey.MEASUREUNITS_ALL_KEY;+ var key = CacheKey.MEASUREUNITS_ALL_KEY;return await _cacheBase.GetAsync(key, async () =>{var query = from md in _measureUnitRepository.Tablediff --git a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.csindex 4786a9ab6..3523faeb2 100644--- a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <summary>/// Search term service/// </summary>- public partial class SearchTermService : ISearchTermService+ public class SearchTermService : ISearchTermService{#region Fields@@ -66,7 +66,7 @@ namespace Grand.Business.Catalog.Services.Directory/// <returns>Search term</returns>public virtual async Task<SearchTerm> GetSearchTermByKeyword(string keyword, string storeId){- if (String.IsNullOrEmpty(keyword))+ if (string.IsNullOrEmpty(keyword))return null;var query = from st in _searchTermRepository.Tablediff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.csindex 8e9862e67..26e842a29 100644--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs@@ -20,7 +20,7 @@ namespace Grand.Business.Catalog.Services.Discounts/// <summary>/// Discount service/// </summary>- public partial class DiscountService : IDiscountService+ public class DiscountService : IDiscountService{#region Fields@@ -74,7 +74,7 @@ namespace Grand.Business.Catalog.Services.Discounts/// <returns>Discount</returns>public virtual Task<Discount> GetDiscountById(string discountId){- string key = string.Format(CacheKey.DISCOUNTS_BY_ID_KEY, discountId);+ var key = string.Format(CacheKey.DISCOUNTS_BY_ID_KEY, discountId);return _cacheBase.GetAsync(key, () => _discountRepository.GetByIdAsync(discountId));}@@ -85,7 +85,7 @@ namespace Grand.Business.Catalog.Services.Discountspublic virtual async Task<IList<Discount>> GetAllDiscounts(DiscountType? discountType,string storeId = "", string currencyCode = "", string couponCode = "", string discountName = "", bool showHidden = false){- string key = string.Format(CacheKey.DISCOUNTS_ALL_KEY, showHidden, storeId, currencyCode, couponCode, discountName);+ var key = string.Format(CacheKey.DISCOUNTS_ALL_KEY, showHidden, storeId, currencyCode, couponCode, discountName);var result = await _cacheBase.GetAsync(key, async () =>{var query = from m in _discountRepository.Table@@ -107,9 +107,9 @@ namespace Grand.Business.Catalog.Services.Discounts}if (!string.IsNullOrEmpty(couponCode)){- var _coupon = _discountCouponRepository.Table.FirstOrDefault(x => x.CouponCode == couponCode);- if (_coupon != null)- query = query.Where(d => d.Id == _coupon.DiscountId);+ var coupon = _discountCouponRepository.Table.FirstOrDefault(x => x.CouponCode == couponCode);+ if (coupon != null)+ query = query.Where(d => d.Id == coupon.DiscountId);}if (!string.IsNullOrEmpty(discountName)){@@ -174,9 +174,9 @@ namespace Grand.Business.Catalog.Services.Discountsif (discount == null)throw new ArgumentNullException(nameof(discount));- var usagehistory = await GetAllDiscountUsageHistory(discount.Id);- if (usagehistory.Count > 0)- throw new ArgumentNullException("discount was used and have a history");+ var usageHistory = await GetAllDiscountUsageHistory(discount.Id);+ if (usageHistory.Count > 0)+ throw new ArgumentNullException("Discount was used and have a history");await _discountRepository.DeleteAsync(discount);@@ -189,16 +189,16 @@ namespace Grand.Business.Catalog.Services.Discounts/// <summary>/// Load discount provider by rule system name/// </summary>- /// <param name="rulesystemName">Rule system name</param>+ /// <param name="ruleSystemName">Rule system name</param>/// <returns>Found discount</returns>- public virtual IDiscountProvider LoadDiscountProviderByRuleSystemName(string rulesystemName)+ public virtual IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName){var discountPlugins = LoadAllDiscountProviders();foreach (var discountPlugin in discountPlugins){var rules = discountPlugin.GetRequirementRules();- if (!rules.Any(x => x.SystemName.Equals(rulesystemName, StringComparison.OrdinalIgnoreCase)))+ if (!rules.Any(x => x.SystemName.Equals(ruleSystemName, StringComparison.OrdinalIgnoreCase)))continue;return discountPlugin;}@@ -223,7 +223,7 @@ namespace Grand.Business.Catalog.Services.Discounts/// <returns>Discount</returns>public virtual async Task<Discount> GetDiscountByCouponCode(string couponCode, bool showHidden = false){- if (String.IsNullOrWhiteSpace(couponCode))+ if (string.IsNullOrWhiteSpace(couponCode))return null;var query = _discountCouponRepository.Table.Where(x => x.CouponCode == couponCode).ToList();@@ -241,10 +241,11 @@ namespace Grand.Business.Catalog.Services.Discounts/// </summary>/// <param name="couponCode"></param>/// <param name="discountId"></param>+ /// <param name="used"></param>/// <returns></returns>public virtual async Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used){- if (String.IsNullOrWhiteSpace(couponCode))+ if (string.IsNullOrWhiteSpace(couponCode))return false;var query = _discountCouponRepository.Table.Where(x => x.CouponCode == couponCode@@ -255,10 +256,7 @@ namespace Grand.Business.Catalog.Services.Discountsvar result = await Task.FromResult(query.ToList());- if (result.Any())- return true;- else- return false;+ return result.Any();}/// <summary>@@ -284,7 +282,6 @@ namespace Grand.Business.Catalog.Services.Discounts/// <summary>/// Gets a discount/// </summary>- /// <param name="discountId">Discount identifier</param>/// <returns>Discount</returns>public virtual Task<DiscountCoupon> GetDiscountCodeById(string id){@@ -294,7 +291,7 @@ namespace Grand.Business.Catalog.Services.Discounts/// <summary>/// Get discount code by discount code/// </summary>- /// <param name="code"></param>+ /// <param name="couponCode">Coupon code</param>/// <returns></returns>public virtual async Task<DiscountCoupon> GetDiscountCodeByCode(string couponCode){@@ -324,7 +321,8 @@ namespace Grand.Business.Catalog.Services.Discounts/// <summary>/// Update discount code - set as used or not/// </summary>- /// <param name="coupon"></param>+ /// <param name="couponCode"></param>+ /// <param name="used"></param>public virtual async Task DiscountCouponSetAsUsed(string couponCode, bool used){if (string.IsNullOrEmpty(couponCode))@@ -335,7 +333,7 @@ namespace Grand.Business.Catalog.Services.Discounts{if (used){- coupon.Used = used;+ coupon.Used = true;coupon.Qty++;}else@@ -391,13 +389,12 @@ namespace Grand.Business.Catalog.Services.Discounts/// <returns>Discount validation result</returns>public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency, string couponCodeToValidate){- if (!String.IsNullOrEmpty(couponCodeToValidate))+ if (!string.IsNullOrEmpty(couponCodeToValidate)){- return await ValidateDiscount(discount, customer, currency, new string[] { couponCodeToValidate });+ return await ValidateDiscount(discount, customer, currency, new[] { couponCodeToValidate });}- else- return await ValidateDiscount(discount, customer, currency, new string[0]);+ return await ValidateDiscount(discount, customer, currency, Array.Empty<string>());}/// <summary>@@ -423,7 +420,7 @@ namespace Grand.Business.Catalog.Services.Discountsreturn result;//do not allow use discount in the current store- if (discount.LimitedToStores && !discount.Stores.Any(x => _workContext.CurrentStore.Id == x))+ if (discount.LimitedToStores && discount.Stores.All(x => _workContext.CurrentStore.Id != x)){result.UserError = _translationService.GetResource("ShoppingCart.Discount.CannotBeUsedInStore");return result;@@ -439,27 +436,22 @@ namespace Grand.Business.Catalog.Services.Discounts{if (discount.Reused){- if (await ExistsCodeInDiscount(item, discount.Id, null))- {- result.CouponCode = item;- exists = true;- }+ if (!await ExistsCodeInDiscount(item, discount.Id, null)) continue;+ result.CouponCode = item;+ exists = true;}else{- if (await ExistsCodeInDiscount(item, discount.Id, false))- {- result.CouponCode = item;- exists = true;- }+ if (!await ExistsCodeInDiscount(item, discount.Id, false)) continue;+ result.CouponCode = item;+ exists = true;}}if (!exists)return result;}- if (discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal ||- discount.DiscountTypeId == DiscountType.AssignedToOrderTotal)+ if (discount.DiscountTypeId is DiscountType.AssignedToOrderSubTotal or DiscountType.AssignedToOrderTotal){var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)@@ -539,12 +531,12 @@ namespace Grand.Business.Catalog.Services.DiscountsStore = _workContext.CurrentStore};var singleRequirementRule = discountRequirementPlugin.GetRequirementRules().FirstOrDefault(x => x.SystemName.Equals(rule.DiscountRequirementRuleSystemName, StringComparison.OrdinalIgnoreCase));+ if (singleRequirementRule == null) return result;var ruleResult = await singleRequirementRule.CheckRequirement(ruleRequest);- if (!ruleResult.IsValid)- {- result.UserError = ruleResult.UserError;- return result;- }+ if (ruleResult.IsValid) continue;+ result.UserError = ruleResult.UserError;++ return result;}result.IsValid = true;@@ -567,6 +559,7 @@ namespace Grand.Business.Catalog.Services.Discounts/// <param name="discountId">Discount identifier; use null to load all records</param>/// <param name="customerId">Customer identifier; use null to load all records</param>/// <param name="orderId">Order identifier; null to load all records</param>+ /// <param name="canceled">Canceled</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Discount usage history records</returns>@@ -601,11 +594,10 @@ namespace Grand.Business.Catalog.Services.Discountsawait _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);- //Support for couponcode+ //Support for coupon codeawait DiscountCouponSetAsUsed(discountUsageHistory.CouponCode, true);-+ //clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);-//event notificationawait _mediator.EntityInserted(discountUsageHistory);}@@ -659,11 +651,11 @@ namespace Grand.Business.Catalog.Services.Discountsthrow new ArgumentNullException(nameof(discount));//calculate discount amount- double result = 0;+ double result;if (!discount.CalculateByPlugin){if (discount.UsePercentage)- result = (double)((((float)amount) * ((float)discount.DiscountPercentage)) / 100f);+ result = (float)amount * (float)discount.DiscountPercentage / 100f;else{result = discount.DiscountAmount;@@ -674,7 +666,7 @@ namespace Grand.Business.Catalog.Services.Discountsresult = await GetDiscountAmountProvider(discount, customer, product, amount);}- //validate maximum disocunt amount+ //validate maximum discount amountif (discount.UsePercentage &&discount.MaximumDiscountAmount.HasValue &&result > discount.MaximumDiscountAmount.Value)@@ -694,7 +686,6 @@ namespace Grand.Business.Catalog.Services.Discounts/// <param name="currency">currency</param>/// <param name="product"></param>/// <param name="amount">Amount</param>- /// <param name="discountAmount"></param>/// <returns>Preferred discount</returns>public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(IList<ApplyDiscount> discounts, Customer customer, Currency currency, Product product,@@ -712,17 +703,15 @@ namespace Grand.Business.Catalog.Services.Discountsforeach (var applieddiscount in discounts){var discount = await GetDiscountById(applieddiscount.DiscountId);- double currentDiscountValue = await GetDiscountAmount(discount, customer, currency, product, amount);- if (currentDiscountValue > discountAmount)- {- discountAmount = currentDiscountValue;- appliedDiscount.Clear();- appliedDiscount.Add(applieddiscount);- }+ var currentDiscountValue = await GetDiscountAmount(discount, customer, currency, product, amount);+ if (!(currentDiscountValue > discountAmount)) continue;+ discountAmount = currentDiscountValue;+ appliedDiscount.Clear();+ appliedDiscount.Add(applieddiscount);}//cumulative discountsvar cumulativeDiscounts = discounts.Where(x => x.IsCumulative).ToList();- if (cumulativeDiscounts.Count > 1)+ if (cumulativeDiscounts.Count <= 1) return (appliedDiscount, discountAmount);{double cumulativeDiscountAmount = 0;foreach (var item in cumulativeDiscounts)@@ -730,17 +719,17 @@ namespace Grand.Business.Catalog.Services.Discountsvar discount = await GetDiscountById(item.DiscountId);cumulativeDiscountAmount += await GetDiscountAmount(discount, customer, currency, product, amount);}- if (cumulativeDiscountAmount > discountAmount)- {- discountAmount = cumulativeDiscountAmount;- appliedDiscount.Clear();- appliedDiscount.AddRange(cumulativeDiscounts);- }+ if (!(cumulativeDiscountAmount > discountAmount)) return (appliedDiscount, discountAmount);+ discountAmount = cumulativeDiscountAmount;++ appliedDiscount.Clear();+ appliedDiscount.AddRange(cumulativeDiscounts);}return (appliedDiscount, discountAmount);}+/// <summary>/// Get preferred discount (with maximum discount value)/// </summary>@@ -748,7 +737,6 @@ namespace Grand.Business.Catalog.Services.Discounts/// <param name="customer"></param>/// <param name="currency">currency</param>/// <param name="amount">Amount</param>- /// <param name="discountAmount"></param>/// <returns>Preferred discount</returns>public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(IList<ApplyDiscount> discounts,@@ -763,7 +751,9 @@ namespace Grand.Business.Catalog.Services.Discounts/// Get amount from discount amount provider/// </summary>/// <param name="discount"></param>+ /// <param name="product"></param>/// <param name="amount"></param>+ /// <param name="customer"></param>/// <returns></returns>public virtual async Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product, double amount){diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.csindex 62775c93d..8d3b3155e 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs@@ -1,4 +1,5 @@-using Grand.Business.Catalog.Services.ExportImport.Dto;+using Grand.Business.Catalog.Extensions;+using Grand.Business.Catalog.Services.ExportImport.Dto;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Brands;using Grand.Business.Core.Interfaces.Common.Localization;@@ -9,7 +10,6 @@ using Grand.Domain.Catalog;using Grand.Domain.Media;using Grand.Domain.Seo;using Grand.Infrastructure.Mapper;-using Microsoft.AspNetCore.StaticFiles;namespace Grand.Business.Catalog.Services.ExportImport{@@ -48,7 +48,7 @@ namespace Grand.Business.Catalog.Services.ExportImport}}- protected async Task Import(BrandDto brandDto)+ private async Task Import(BrandDto brandDto){var brand = await _brandService.GetBrandById(brandDto.Id);var isNew = brand == null;@@ -65,22 +65,22 @@ namespace Grand.Business.Catalog.Services.ExportImport}- protected async Task<Brand> UpdateBrandData(BrandDto brandDto, Brand brand)+ private async Task UpdateBrandData(BrandDto brandDto, Brand brand){if (string.IsNullOrEmpty(brand.BrandLayoutId))- brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault().Id;+ brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault()?.Id;else{var layout = await _brandLayoutService.GetBrandLayoutById(brand.BrandLayoutId);if (layout == null)- brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault().Id;+ brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault()?.Id;}if (!string.IsNullOrEmpty(brandDto.Picture)){- var _picture = await LoadPicture(brandDto.Picture, brand.Name, brand.PictureId);- if (_picture != null)- brand.PictureId = _picture.Id;+ var picture = await LoadPicture(brandDto.Picture, brand.Name, brand.PictureId);+ if (picture != null)+ brand.PictureId = picture.Id;}var sename = brand.SeName ?? brand.Name;@@ -89,16 +89,11 @@ namespace Grand.Business.Catalog.Services.ExportImportawait _brandService.UpdateBrand(brand);await _slugService.SaveSlug(brand, sename, "");-- return brand;}- protected virtual bool ValidBrand(Brand brand)+ private bool ValidBrand(Brand brand){- if (string.IsNullOrEmpty(brand.Name))- return false;-- return true;+ return !string.IsNullOrEmpty(brand.Name);}/// <summary>@@ -108,13 +103,13 @@ namespace Grand.Business.Catalog.Services.ExportImport/// <param name="name">The name of the object</param>/// <param name="picId">Image identifier, may be null</param>/// <returns>The image or null if the image has not changed</returns>- protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = ""){if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))return null;- var mimeType = GetMimeTypeFromFilePath(picturePath);- var newPictureBinary = File.ReadAllBytes(picturePath);+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);var pictureAlreadyExists = false;if (!string.IsNullOrEmpty(picId)){@@ -137,13 +132,6 @@ namespace Grand.Business.Catalog.Services.ExportImport_pictureService.GetPictureSeName(name));return newPicture;}- protected virtual string GetMimeTypeFromFilePath(string filePath)- {- new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);- //set to jpeg in case mime type cannot be found- if (mimeType == null)- mimeType = "image/jpeg";- return mimeType;- }+}}diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.csindex b63024b1f..79b23bde4 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs@@ -1,4 +1,5 @@-using Grand.Business.Catalog.Services.ExportImport.Dto;+using Grand.Business.Catalog.Extensions;+using Grand.Business.Catalog.Services.ExportImport.Dto;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Business.Core.Interfaces.Common.Localization;@@ -9,7 +10,6 @@ using Grand.Domain.Catalog;using Grand.Domain.Media;using Grand.Domain.Seo;using Grand.Infrastructure.Mapper;-using Microsoft.AspNetCore.StaticFiles;namespace Grand.Business.Catalog.Services.ExportImport{@@ -48,7 +48,7 @@ namespace Grand.Business.Catalog.Services.ExportImport}}- protected async Task Import(CategoryDto categoryDto)+ private async Task Import(CategoryDto categoryDto){var category = await _categoryService.GetCategoryById(categoryDto.Id);var isNew = category == null;@@ -63,15 +63,15 @@ namespace Grand.Business.Catalog.Services.ExportImportawait UpdateCategoryData(categoryDto, category);}- protected async Task<Category> UpdateCategoryData(CategoryDto categoryDto, Category category)+ private async Task UpdateCategoryData(CategoryDto categoryDto, Category category){if (string.IsNullOrEmpty(category.CategoryLayoutId))- category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault().Id;+ category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault()?.Id;else{var layout = await _categoryLayoutService.GetCategoryLayoutById(category.CategoryLayoutId);if (layout == null)- category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault().Id;+ category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault()?.Id;}if(!string.IsNullOrEmpty(category.ParentCategoryId)){@@ -81,9 +81,9 @@ namespace Grand.Business.Catalog.Services.ExportImport}if (!string.IsNullOrEmpty(categoryDto.Picture)){- var _picture = await LoadPicture(categoryDto.Picture, category.Name, category.PictureId);- if (_picture != null)- category.PictureId = _picture.Id;+ var picture = await LoadPicture(categoryDto.Picture, category.Name, category.PictureId);+ if (picture != null)+ category.PictureId = picture.Id;}var sename = category.SeName ?? category.Name;@@ -91,15 +91,11 @@ namespace Grand.Business.Catalog.Services.ExportImportcategory.SeName = sename;await _categoryService.UpdateCategory(category);await _slugService.SaveSlug(category, sename, "");- return category;}- protected virtual bool ValidCategory(Category category)+ private bool ValidCategory(Category category){- if (string.IsNullOrEmpty(category.Name))- return false;-- return true;+ return !string.IsNullOrEmpty(category.Name);}/// <summary>@@ -109,13 +105,13 @@ namespace Grand.Business.Catalog.Services.ExportImport/// <param name="name">The name of the object</param>/// <param name="picId">Image identifier, may be null</param>/// <returns>The image or null if the image has not changed</returns>- protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = ""){if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))return null;- var mimeType = GetMimeTypeFromFilePath(picturePath);- var newPictureBinary = File.ReadAllBytes(picturePath);+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);var pictureAlreadyExists = false;if (!string.IsNullOrEmpty(picId)){@@ -138,13 +134,5 @@ namespace Grand.Business.Catalog.Services.ExportImport_pictureService.GetPictureSeName(name));return newPicture;}- protected virtual string GetMimeTypeFromFilePath(string filePath)- {- new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);- //set to jpeg in case mime type cannot be found- if (mimeType == null)- mimeType = "image/jpeg";- return mimeType;- }}}diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.csindex 4f1205bee..fdb74289d 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs@@ -1,4 +1,5 @@-using Grand.Business.Catalog.Services.ExportImport.Dto;+using Grand.Business.Catalog.Extensions;+using Grand.Business.Catalog.Services.ExportImport.Dto;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Common.Localization;@@ -9,7 +10,6 @@ using Grand.Domain.Catalog;using Grand.Domain.Media;using Grand.Domain.Seo;using Grand.Infrastructure.Mapper;-using Microsoft.AspNetCore.StaticFiles;namespace Grand.Business.Catalog.Services.ExportImport{@@ -48,7 +48,7 @@ namespace Grand.Business.Catalog.Services.ExportImport}}- protected async Task Import(CollectionDto collectionDto)+ private async Task Import(CollectionDto collectionDto){var collection = await _collectionService.GetCollectionById(collectionDto.Id);var isNew = collection == null;@@ -64,22 +64,22 @@ namespace Grand.Business.Catalog.Services.ExportImportawait UpdateCollectionData(collectionDto, collection);}- protected async Task<Collection> UpdateCollectionData(CollectionDto collectionDto, Collection collection)+ private async Task UpdateCollectionData(CollectionDto collectionDto, Collection collection){if (string.IsNullOrEmpty(collection.CollectionLayoutId))- collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault().Id;+ collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;else{var layout = await _collectionLayoutService.GetCollectionLayoutById(collection.CollectionLayoutId);if (layout == null)- collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault().Id;+ collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;}if (!string.IsNullOrEmpty(collectionDto.Picture)){- var _picture = await LoadPicture(collectionDto.Picture, collection.Name, collection.PictureId);- if (_picture != null)- collection.PictureId = _picture.Id;+ var picture = await LoadPicture(collectionDto.Picture, collection.Name, collection.PictureId);+ if (picture != null)+ collection.PictureId = picture.Id;}var sename = collection.SeName ?? collection.Name;@@ -88,16 +88,11 @@ namespace Grand.Business.Catalog.Services.ExportImportawait _collectionService.UpdateCollection(collection);await _slugService.SaveSlug(collection, sename, "");-- return collection;}- protected virtual bool ValidCollection(Collection collection)+ private bool ValidCollection(Collection collection){- if (string.IsNullOrEmpty(collection.Name))- return false;-- return true;+ return !string.IsNullOrEmpty(collection.Name);}/// <summary>@@ -107,13 +102,13 @@ namespace Grand.Business.Catalog.Services.ExportImport/// <param name="name">The name of the object</param>/// <param name="picId">Image identifier, may be null</param>/// <returns>The image or null if the image has not changed</returns>- protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = ""){if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))return null;- var mimeType = GetMimeTypeFromFilePath(picturePath);- var newPictureBinary = File.ReadAllBytes(picturePath);+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);var pictureAlreadyExists = false;if (!string.IsNullOrEmpty(picId)){@@ -136,13 +131,5 @@ namespace Grand.Business.Catalog.Services.ExportImport_pictureService.GetPictureSeName(name));return newPicture;}- protected virtual string GetMimeTypeFromFilePath(string filePath)- {- new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);- //set to jpeg in case mime type cannot be found- if (mimeType == null)- mimeType = "image/jpeg";- return mimeType;- }}}diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.csindex e884ebeaf..1297aae1c 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs@@ -88,11 +88,11 @@ namespace Grand.Business.Catalog.Services.ExportImport.Dtopublic bool? EnteredPrice { get; set; }public double? MinEnteredPrice { get; set; }public double? MaxEnteredPrice { get; set; }- public bool? BasepriceEnabled { get; set; }- public double? BasepriceAmount { get; set; }- public string BasepriceUnitId { get; set; }- public double? BasepriceBaseAmount { get; set; }- public string BasepriceBaseUnitId { get; set; }+ public bool? BasePriceEnabled { get; set; }+ public double? BasePriceAmount { get; set; }+ public string BasePriceUnitId { get; set; }+ public double? BasePriceBaseAmount { get; set; }+ public string BasePriceBaseUnitId { get; set; }public string UnitId { get; set; }public string CourseId { get; set; }public bool? MarkAsNew { get; set; }diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.csindex 32274e4d9..6f051773d 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs@@ -71,9 +71,9 @@ namespace Grand.Business.Catalog.Services.ExportImport.Mapper.ForMember(x => x.EnteredPrice, opt => opt.Condition(z => z.EnteredPrice.HasValue)).ForMember(x => x.MinEnteredPrice, opt => opt.Condition(z => z.MinEnteredPrice.HasValue)).ForMember(x => x.MaxEnteredPrice, opt => opt.Condition(z => z.MaxEnteredPrice.HasValue))- .ForMember(x => x.BasepriceEnabled, opt => opt.Condition(z => z.BasepriceEnabled.HasValue))- .ForMember(x => x.BasepriceAmount, opt => opt.Condition(z => z.BasepriceAmount.HasValue))- .ForMember(x => x.BasepriceBaseAmount, opt => opt.Condition(z => z.BasepriceBaseAmount.HasValue))+ .ForMember(x => x.BasepriceEnabled, opt => opt.Condition(z => z.BasePriceEnabled.HasValue))+ .ForMember(x => x.BasepriceAmount, opt => opt.Condition(z => z.BasePriceAmount.HasValue))+ .ForMember(x => x.BasepriceBaseAmount, opt => opt.Condition(z => z.BasePriceBaseAmount.HasValue)).ForMember(x => x.MarkAsNew, opt => opt.Condition(z => z.MarkAsNew.HasValue)).ForMember(x => x.MarkAsNewStartDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewStartDateTimeUtc.HasValue)).ForMember(x => x.MarkAsNewEndDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewEndDateTimeUtc.HasValue))@@ -108,8 +108,8 @@ namespace Grand.Business.Catalog.Services.ExportImport.Mapper.ForMember(x => x.Mpn, opt => opt.Condition(z => z.Mpn != null)).ForMember(x => x.Gtin, opt => opt.Condition(z => z.Gtin != null)).ForMember(x => x.AllowedQuantities, opt => opt.Condition(z => z.AllowedQuantities != null))- .ForMember(x => x.BasepriceBaseUnitId, opt => opt.Condition(z => z.BasepriceBaseUnitId != null))- .ForMember(x => x.BasepriceUnitId, opt => opt.Condition(z => z.BasepriceUnitId != null))+ .ForMember(x => x.BasepriceBaseUnitId, opt => opt.Condition(z => z.BasePriceBaseUnitId != null))+ .ForMember(x => x.BasepriceUnitId, opt => opt.Condition(z => z.BasePriceUnitId != null)).ForMember(x => x.CourseId, opt => opt.Condition(z => z.CourseId != null)).ForMember(x => x.DeliveryDateId, opt => opt.Condition(z => z.DeliveryDateId != null)).ForMember(x => x.TaxCategoryId, opt => opt.Condition(z => z.TaxCategoryId != null))diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.csindex 4d10c1e8c..2dde9982e 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs@@ -1,4 +1,5 @@-using Grand.Business.Catalog.Services.ExportImport.Dto;+using Grand.Business.Catalog.Extensions;+using Grand.Business.Catalog.Services.ExportImport.Dto;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Brands;using Grand.Business.Core.Interfaces.Catalog.Categories;@@ -13,10 +14,8 @@ using Grand.Business.Core.Interfaces.ExportImport;using Grand.Business.Core.Interfaces.Storage;using Grand.Business.Core.Utilities.System;using Grand.Domain.Catalog;-using Grand.Domain.Media;using Grand.Domain.Seo;using Grand.Infrastructure.Mapper;-using Microsoft.AspNetCore.StaticFiles;namespace Grand.Business.Catalog.Services.ExportImport{@@ -81,7 +80,7 @@ namespace Grand.Business.Catalog.Services.ExportImport}}- protected async Task Import(ProductDto productDto)+ private async Task Import(ProductDto productDto){var product = await _productService.GetProductById(productDto.Id);product ??= await _productService.GetProductBySku(productDto.Sku);@@ -100,7 +99,7 @@ namespace Grand.Business.Catalog.Services.ExportImport}- protected async Task<Product> UpdateProductData(ProductDto productDto, Product product, bool isNew)+ private async Task UpdateProductData(ProductDto productDto, Product product, bool isNew){await UpdateProductDataLayout(product);await UpdateProductDataDeliveryDate(product);@@ -124,114 +123,95 @@ namespace Grand.Business.Catalog.Services.ExportImport//picturesawait PrepareProductPictures(productDto, product, isNew);-- return product;}- protected async Task<Product> UpdateProductDataLayout(Product product)++ private async Task UpdateProductDataLayout(Product product){if (string.IsNullOrEmpty(product.ProductLayoutId))- product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault().Id;+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;else{var layout = await _productLayoutService.GetProductLayoutById(product.ProductLayoutId);if (layout == null)- product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault().Id;+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;}- return product;}- protected async Task<Product> UpdateProductDataDeliveryDate(Product product)++ private async Task UpdateProductDataDeliveryDate(Product product){- if (!string.IsNullOrEmpty(product.DeliveryDateId))- {- var deliveryDate = await _deliveryDateService.GetDeliveryDateById(product.DeliveryDateId);- if (deliveryDate == null)- product.DeliveryDateId = "";- }- return product;+ if (string.IsNullOrEmpty(product.DeliveryDateId)) return;+ var deliveryDate = await _deliveryDateService.GetDeliveryDateById(product.DeliveryDateId);+ if (deliveryDate == null)+ product.DeliveryDateId = "";}- protected async Task<Product> UpdateProductDataTaxCategory(Product product)++ private async Task UpdateProductDataTaxCategory(Product product){- if (!string.IsNullOrEmpty(product.TaxCategoryId))- {- var taxCategory = await _taxService.GetTaxCategoryById(product.TaxCategoryId);- if (taxCategory == null)- product.TaxCategoryId = "";- }- return product;+ if (string.IsNullOrEmpty(product.TaxCategoryId)) return;+ var taxCategory = await _taxService.GetTaxCategoryById(product.TaxCategoryId);+ if (taxCategory == null)+ product.TaxCategoryId = "";}- protected async Task<Product> UpdateProductDataWarehouse(Product product)++ private async Task UpdateProductDataWarehouse(Product product){- if (!string.IsNullOrEmpty(product.WarehouseId))- {- var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);- if (warehouse == null)- product.WarehouseId = "";- }- return product;+ if (string.IsNullOrEmpty(product.WarehouseId)) return;+ var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);+ if (warehouse == null)+ product.WarehouseId = "";}- protected async Task<Product> UpdateProductDataUnit(Product product)++ private async Task UpdateProductDataUnit(Product product){- if (!string.IsNullOrEmpty(product.UnitId))- {- var unit = await _measureService.GetMeasureUnitById(product.UnitId);- if (unit == null)- product.UnitId = "";- }- return product;+ if (string.IsNullOrEmpty(product.UnitId)) return;+ var unit = await _measureService.GetMeasureUnitById(product.UnitId);+ if (unit == null)+ product.UnitId = "";}- protected async Task<Product> UpdateProductDataBrand(Product product)++ private async Task UpdateProductDataBrand(Product product){- if (!string.IsNullOrEmpty(product.BrandId))- {- var brand = await _brandService.GetBrandById(product.BrandId);- if (brand == null)- product.BrandId = "";- }- return product;+ if (string.IsNullOrEmpty(product.BrandId)) return;+ var brand = await _brandService.GetBrandById(product.BrandId);+ if (brand == null)+ product.BrandId = "";}- protected virtual async Task PrepareProductCategories(Product product, string categoryIds)++ private async Task PrepareProductCategories(Product product, string categoryIds){foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())){- if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)- {- //ensure that category exists- var category = await _categoryService.GetCategoryById(id);- if (category != null)- {- var productCategory = new ProductCategory {- CategoryId = category.Id,- IsFeaturedProduct = false,- DisplayOrder = 1- };- await _productCategoryService.InsertProductCategory(productCategory, product.Id);- }- }+ if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) != null) continue;+ //ensure that category exists+ var category = await _categoryService.GetCategoryById(id);+ if (category == null) continue;+ var productCategory = new ProductCategory {+ CategoryId = category.Id,+ IsFeaturedProduct = false,+ DisplayOrder = 1+ };+ await _productCategoryService.InsertProductCategory(productCategory, product.Id);}}- protected virtual async Task PrepareProductCollections(Product product, string collectionIds)+ private async Task PrepareProductCollections(Product product, string collectionIds){foreach (var id in collectionIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())){- if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) == null)- {- //ensure that collection exists- var collection = await _collectionService.GetCollectionById(id);- if (collection != null)- {- var productCollection = new ProductCollection {- CollectionId = collection.Id,- IsFeaturedProduct = false,- DisplayOrder = 1- };- await _productCollectionService.InsertProductCollection(productCollection, product.Id);- }- }+ if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) != null) continue;+ //ensure that collection exists+ var collection = await _collectionService.GetCollectionById(id);+ if (collection == null) continue;+ var productCollection = new ProductCollection {+ CollectionId = collection.Id,+ IsFeaturedProduct = false,+ DisplayOrder = 1+ };+ await _productCollectionService.InsertProductCollection(productCollection, product.Id);}}- protected virtual async Task PrepareProductPictures(ProductDto productDto, Product product, bool isNew)+ private async Task PrepareProductPictures(ProductDto productDto, Product product, bool isNew){var picture1 = productDto.Picture1;var picture2 = productDto.Picture2;@@ -243,8 +223,8 @@ namespace Grand.Business.Catalog.Services.ExportImportcontinue;if (!picturePath.ToLower().StartsWith(("http".ToLower()))){- var mimeType = GetMimeTypeFromFilePath(picturePath);- var newPictureBinary = File.ReadAllBytes(picturePath);+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);var pictureAlreadyExists = false;if (!isNew){@@ -256,96 +236,40 @@ namespace Grand.Business.Catalog.Services.ExportImportvar existingBinary = await _pictureService.LoadPictureBinary(pp);//picture binary after validation (like in database)var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);- if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))- {- //the same picture content- pictureAlreadyExists = true;- break;- }+ if (!existingBinary.SequenceEqual(validatedPictureBinary) &&+ !existingBinary.SequenceEqual(newPictureBinary)) continue;+ //the same picture content+ pictureAlreadyExists = true;+ break;}}- if (!pictureAlreadyExists)- {- var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false,- Domain.Common.Reference.Product, product.Id);- var productPicture = new ProductPicture {- PictureId = picture.Id,- DisplayOrder = 1,- };- await _productService.InsertProductPicture(productPicture, product.Id);- }+ if (pictureAlreadyExists) continue;+ var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false,+ Domain.Common.Reference.Product, product.Id);+ var productPicture = new ProductPicture {+ PictureId = picture.Id,+ DisplayOrder = 1,+ };+ await _productService.InsertProductPicture(productPicture, product.Id);}else{- byte[] fileBinary = await DownloadUrl.DownloadFile(picturePath);- if (fileBinary != null)- {- var mimeType = GetMimeTypeFromFilePath(picturePath);- var picture = await _pictureService.InsertPicture(fileBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false, Domain.Common.Reference.Product, product.Id);- var productPicture = new ProductPicture {- PictureId = picture.Id,- DisplayOrder = 1,- };- await _productService.InsertProductPicture(productPicture, product.Id);- }- }- }-- }--- protected virtual bool ValidProduct(Product product)- {- if (string.IsNullOrEmpty(product.Name))- return false;-- return true;- }-- /// <summary>- /// Creates or loads the image- /// </summary>- /// <param name="picturePath">The path to the image file</param>- /// <param name="name">The name of the object</param>- /// <param name="picId">Image identifier, may be null</param>- /// <returns>The image or null if the image has not changed</returns>- protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")- {- if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))- return null;-- var mimeType = GetMimeTypeFromFilePath(picturePath);- var newPictureBinary = File.ReadAllBytes(picturePath);- var pictureAlreadyExists = false;- if (!string.IsNullOrEmpty(picId))- {- //compare with existing product pictures- var existingPicture = await _pictureService.GetPictureById(picId);-- var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);- //picture binary after validation (like in database)- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);- if (existingBinary.SequenceEqual(validatedPictureBinary) ||- existingBinary.SequenceEqual(newPictureBinary))- {- pictureAlreadyExists = true;+ var fileBinary = await DownloadUrl.DownloadFile(picturePath);+ if (fileBinary == null) continue;+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);+ var picture = await _pictureService.InsertPicture(fileBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false, Domain.Common.Reference.Product, product.Id);+ var productPicture = new ProductPicture {+ PictureId = picture.Id,+ DisplayOrder = 1,+ };+ await _productService.InsertProductPicture(productPicture, product.Id);}}-- if (pictureAlreadyExists) return null;-- var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,- _pictureService.GetPictureSeName(name));- return newPicture;}- protected virtual string GetMimeTypeFromFilePath(string filePath)+ private bool ValidProduct(Product product){- new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);- //set to jpeg in case mime type cannot be found- if (mimeType == null)- mimeType = "image/jpeg";- return mimeType;+ return !string.IsNullOrEmpty(product.Name);}}}diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.csindex 578325c2d..dd1471a31 100644--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs@@ -129,7 +129,7 @@ namespace Grand.Business.Catalog.Services.ExportImportstring picture1 = null;string picture2 = null;string picture3 = null;- int i = 0;+ var i = 0;foreach (var picture in product.ProductPictures.Take(3)){var pic = await _pictureService.GetPictureById(picture.PictureId);diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.csindex bf99eefe6..d43dad512 100644--- a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <summary>/// Price formatter/// </summary>- public partial class PriceFormatter : IPriceFormatter+ public class PriceFormatter : IPriceFormatter{#region Fields@@ -53,21 +53,21 @@ namespace Grand.Business.Catalog.Services.Pricesif (targetCurrency == null)return amount.ToString("C");- string result = "";- if (!String.IsNullOrEmpty(targetCurrency.CustomFormatting))+ var result = "";+ if (!string.IsNullOrEmpty(targetCurrency.CustomFormatting)){- var cultureInfo = !String.IsNullOrEmpty(targetCurrency.DisplayLocale) ? new CultureInfo(targetCurrency.DisplayLocale) : null;+ var cultureInfo = !string.IsNullOrEmpty(targetCurrency.DisplayLocale) ? new CultureInfo(targetCurrency.DisplayLocale) : null;result = amount.ToString(targetCurrency.CustomFormatting, cultureInfo);}else{- if (!String.IsNullOrEmpty(targetCurrency.DisplayLocale))+ if (!string.IsNullOrEmpty(targetCurrency.DisplayLocale)){result = amount.ToString("C", new CultureInfo(targetCurrency.DisplayLocale));}else{- result = String.Format("{0} ({1})", amount.ToString("N"), targetCurrency.CurrencyCode);+ result = $"{amount:N} ({targetCurrency.CurrencyCode})";return result;}}@@ -97,7 +97,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public virtual string FormatPrice(double price, Currency targetCurrency){- bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return FormatPrice(price, targetCurrency, _workContext.WorkingLanguage, priceIncludesTax);}@@ -109,7 +109,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public virtual string FormatPrice(double price, bool showTax){- bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return FormatPrice(price, _workContext.WorkingCurrency, _workContext.WorkingLanguage, priceIncludesTax, showTax);}@@ -124,7 +124,7 @@ namespace Grand.Business.Catalog.Services.Pricespublic virtual async Task<string> FormatPrice(double price, string currencyCode, bool showTax, Language language){var currency = !string.IsNullOrEmpty(currencyCode) ? await _currencyService.GetCurrencyByCode(currencyCode) : null;- bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return FormatPrice(price, currency, language, priceIncludesTax, showTax);}@@ -166,27 +166,24 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public string FormatPrice(double price, Currency targetCurrency, Language language, bool priceIncludesTax, bool showTax){- string currencyString = GetCurrencyString(price, targetCurrency);- if (showTax)+ var currencyString = GetCurrencyString(price, targetCurrency);+ if (!showTax) return currencyString;+ //show tax suffix+ string formatStr;+ if (priceIncludesTax){- //show tax suffix- string formatStr;- if (priceIncludesTax)- {- formatStr = _translationService.GetResource("Products.InclTaxSuffix", language.Id);- if (String.IsNullOrEmpty(formatStr))- formatStr = "{0} incl tax";- }- else- {- formatStr = _translationService.GetResource("Products.ExclTaxSuffix", language.Id);- if (String.IsNullOrEmpty(formatStr))- formatStr = "{0} excl tax";- }- return string.Format(formatStr, currencyString);+ formatStr = _translationService.GetResource("Products.InclTaxSuffix", language.Id);+ if (string.IsNullOrEmpty(formatStr))+ formatStr = "{0} incl tax";}+ else+ {+ formatStr = _translationService.GetResource("Products.ExclTaxSuffix", language.Id);+ if (string.IsNullOrEmpty(formatStr))+ formatStr = "{0} excl tax";+ }+ return string.Format(formatStr, currencyString);- return currencyString;}@@ -198,7 +195,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public virtual string FormatShippingPrice(double price){- bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return FormatShippingPrice(price, _workContext.WorkingCurrency, _workContext.WorkingLanguage, priceIncludesTax);}@@ -212,7 +209,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public virtual string FormatShippingPrice(double price, Currency targetCurrency, Language language, bool priceIncludesTax){- bool showTax = _taxSettings.ShippingIsTaxable && _taxSettings.DisplayTaxSuffix;+ var showTax = _taxSettings.ShippingIsTaxable && _taxSettings.DisplayTaxSuffix;return FormatShippingPrice(price, targetCurrency, language, priceIncludesTax, showTax);}@@ -259,24 +256,18 @@ namespace Grand.Business.Catalog.Services.Pricesif (product.ProductTypeId != ProductType.Reservation)return price;- if (String.IsNullOrWhiteSpace(price))+ if (string.IsNullOrWhiteSpace(price))return price;- string result;- switch (product.IntervalUnitId)- {- case IntervalUnit.Day:- result = string.Format(_translationService.GetResource("Products.Price.Reservation.Days"), price, product.Interval);- break;- case IntervalUnit.Hour:- result = string.Format(_translationService.GetResource("Products.Price.Reservation.Hour"), price, product.Interval);- break;- case IntervalUnit.Minute:- result = string.Format(_translationService.GetResource("Products.Price.Reservation.Minute"), price, product.Interval);- break;- default:- throw new GrandException("Not supported reservation period");- }+ var result = product.IntervalUnitId switch {+ IntervalUnit.Day => string.Format(_translationService.GetResource("Products.Price.Reservation.Days"),+ price, product.Interval),+ IntervalUnit.Hour => string.Format(_translationService.GetResource("Products.Price.Reservation.Hour"),+ price, product.Interval),+ IntervalUnit.Minute => string.Format(+ _translationService.GetResource("Products.Price.Reservation.Minute"), price, product.Interval),+ _ => throw new GrandException("Not supported reservation period")+ };return result;}@@ -289,7 +280,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <returns>Price</returns>public virtual string FormatPaymentMethodAdditionalFee(double price){- bool priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return FormatPaymentMethodAdditionalFee(price, _workContext.WorkingCurrency,_workContext.WorkingLanguage, priceIncludesTax);}@@ -305,7 +296,7 @@ namespace Grand.Business.Catalog.Services.Pricespublic virtual string FormatPaymentMethodAdditionalFee(double price,Currency targetCurrency, Language language, bool priceIncludesTax){- bool showTax = _taxSettings.PaymentMethodAdditionalFeeIsTaxable && _taxSettings.DisplayTaxSuffix;+ var showTax = _taxSettings.PaymentMethodAdditionalFeeIsTaxable && _taxSettings.DisplayTaxSuffix;return FormatPaymentMethodAdditionalFee(price, targetCurrency, language, priceIncludesTax, showTax);}diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.csindex eb8e0ab95..d3afcd3b8 100644--- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs@@ -16,13 +16,14 @@ using Grand.Domain.Discounts;using Grand.Domain.Orders;using MediatR;using Grand.Business.Core.Interfaces.Catalog.Brands;+using System.Globalization;namespace Grand.Business.Catalog.Services.Prices{/// <summary>/// Pricing service/// </summary>- public partial class PricingService : IPricingService+ public class PricingService : IPricingService{#region Fields@@ -98,24 +99,19 @@ namespace Grand.Business.Catalog.Services.Pricesif (_catalogSettings.IgnoreDiscounts)return allowedDiscounts;- if (product.AppliedDiscounts.Any())+ if (!product.AppliedDiscounts.Any()) return allowedDiscounts;+ foreach (var appliedDiscount in product.AppliedDiscounts){- foreach (var appliedDiscount in product.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount != null)- {- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToSkus)- allowedDiscounts.Add(new ApplyDiscount()- {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }- }+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToSkus)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative+ });}return allowedDiscounts;}@@ -131,8 +127,7 @@ namespace Grand.Business.Catalog.Services.Prices{var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);if (validDiscount.IsValid)- allowedDiscounts.Add(new ApplyDiscount()- {+ allowedDiscounts.Add(new ApplyDiscount {CouponCode = validDiscount.CouponCode,DiscountId = discount.Id,IsCumulative = discount.IsCumulative@@ -158,23 +153,18 @@ namespace Grand.Business.Catalog.Services.Pricesforeach (var productCategory in product.ProductCategories){var category = await _categoryService.GetCategoryById(productCategory.CategoryId);- if (category != null && category.AppliedDiscounts.Any())+ if (category == null || !category.AppliedDiscounts.Any()) continue;+ foreach (var appliedDiscount in category.AppliedDiscounts){- foreach (var appliedDiscount in category.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount != null)- {- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);- if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)- allowedDiscounts.Add(new ApplyDiscount()- {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }- }+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative+ });}}return allowedDiscounts;@@ -192,31 +182,22 @@ namespace Grand.Business.Catalog.Services.Pricesif (_catalogSettings.IgnoreDiscounts)return allowedDiscounts;- if (!string.IsNullOrEmpty(product.BrandId))+ if (string.IsNullOrEmpty(product.BrandId)) return allowedDiscounts;+ var brand = await _brandService.GetBrandById(product.BrandId);+ if (brand == null) return allowedDiscounts;+ if (!brand.AppliedDiscounts.Any()) return allowedDiscounts;+ foreach (var appliedDiscount in brand.AppliedDiscounts){- var brand = await _brandService.GetBrandById(product.BrandId);- if (brand != null)- {- if (brand.AppliedDiscounts.Any())- {- foreach (var appliedDiscount in brand.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount != null)- {- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToBrands)- allowedDiscounts.Add(new ApplyDiscount()- {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative,- });- }- }- }- }+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToBrands)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ });}return allowedDiscounts;}@@ -237,31 +218,26 @@ namespace Grand.Business.Catalog.Services.Pricesforeach (var productCollection in product.ProductCollections){var collection = await _collectionService.GetCollectionById(productCollection.CollectionId);- if (collection != null && collection.AppliedDiscounts.Any())+ if (collection == null || !collection.AppliedDiscounts.Any()) continue;+ foreach (var appliedDiscount in collection.AppliedDiscounts){- foreach (var appliedDiscount in collection.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount != null)- {- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToCollections)- allowedDiscounts.Add(new ApplyDiscount()- {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }- }+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToCollections)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative+ });}}return allowedDiscounts;}/// <summary>- ///+ /// Get allowed discounts applied to vendors/// </summary>/// <param name="product"></param>/// <param name="customer"></param>@@ -273,31 +249,23 @@ namespace Grand.Business.Catalog.Services.Pricesif (_catalogSettings.IgnoreDiscounts)return allowedDiscounts;- if (!string.IsNullOrEmpty(product.VendorId))+ if (string.IsNullOrEmpty(product.VendorId)) return allowedDiscounts;++ var vendor = await _mediator.Send(new GetVendorByIdQuery { Id = product.VendorId });+ if (vendor == null) return allowedDiscounts;+ if (!vendor.AppliedDiscounts.Any()) return allowedDiscounts;+ foreach (var appliedDiscount in vendor.AppliedDiscounts){- var vendor = await _mediator.Send(new GetVendorByIdQuery() { Id = product.VendorId });- if (vendor != null)- {- if (vendor.AppliedDiscounts.Any())- {- foreach (var appliedDiscount in vendor.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount != null)- {- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToVendors)- allowedDiscounts.Add(new ApplyDiscount()- {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative,- });- }- }- }- }+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToVendors)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ });}return allowedDiscounts;}@@ -317,32 +285,32 @@ namespace Grand.Business.Catalog.Services.Prices//discounts applied to productsforeach (var discount in await GetAllowedDiscountsAppliedToProduct(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);//discounts applied to all productsforeach (var discount in await GetAllowedDiscountsAppliedToAllProduct(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);//discounts applied to categoriesforeach (var discount in await GetAllowedDiscountsAppliedToCategories(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);//discounts applied to brandsforeach (var discount in await GetAllowedDiscountsAppliedToBrands(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);//discounts applied to collectionsforeach (var discount in await GetAllowedDiscountsAppliedToCollections(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);//discounts applied to vendorsforeach (var discount in await GetAllowedDiscountsAppliedToVendors(product, customer, currency))- if (!allowedDiscounts.Where(x => x.DiscountId == discount.DiscountId).Any())+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);return allowedDiscounts;@@ -361,28 +329,24 @@ namespace Grand.Business.Catalog.Services.Prices{if (product == null)throw new ArgumentNullException(nameof(product));-- List<ApplyDiscount> appliedDiscounts = null;- double appliedDiscountAmount = 0;-+//we don't apply discounts to products with price entered by a customerif (product.EnteredPrice)- return (appliedDiscountAmount, appliedDiscounts);+ return (0, null);//discounts are disabledif (_catalogSettings.IgnoreDiscounts)- return (appliedDiscountAmount, appliedDiscounts);+ return (0, null);var allowedDiscounts = await GetAllowedDiscounts(product, customer, currency);//no discountsif (!allowedDiscounts.Any())- return (appliedDiscountAmount, appliedDiscounts);+ return (0, null);- var preferredDiscount = (await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency, product, productPriceWithoutDiscount));- appliedDiscounts = preferredDiscount.appliedDiscount;- appliedDiscountAmount = preferredDiscount.discountAmount;- return (appliedDiscountAmount, appliedDiscounts);+ var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency, product, productPriceWithoutDiscount);++ return (preferredDiscount.discountAmount, preferredDiscount.appliedDiscount);}@@ -444,7 +408,7 @@ namespace Grand.Business.Catalog.Services.Pricesvar result = new ProductPrice();//initial price- double price =+ var price =product.ProductPrices.FirstOrDefault(x => x.CurrencyCode == currency.CurrencyCode)?.Price ??await _currencyService.ConvertFromPrimaryStoreCurrency(product.Price, currency);@@ -459,7 +423,7 @@ namespace Grand.Business.Catalog.Services.Prices//customer product priceif (_catalogSettings.CustomerProductPrice){- var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery() { CustomerId = customer.Id, ProductId = product.Id });+ var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery { CustomerId = customer.Id, ProductId = product.Id });if (customerPrice.HasValue && customerPrice.Value < await _currencyService.ConvertToPrimaryStoreCurrency(price, currency))price = await _currencyService.ConvertFromPrimaryStoreCurrency(customerPrice.Value, currency);}@@ -471,24 +435,15 @@ namespace Grand.Business.Catalog.Services.Pricesif (product.ProductTypeId == ProductType.Reservation)if (rentalStartDate.HasValue && rentalEndDate.HasValue){- double d = 0;- if (product.IncBothDate)- {- _ = double.TryParse(((rentalEndDate - rentalStartDate).Value.TotalDays + 1).ToString(), out d);- }- else- {- _ = double.TryParse((rentalEndDate - rentalStartDate).Value.TotalDays.ToString(), out d);- }+ _ = product.IncBothDate ? double.TryParse(((rentalEndDate - rentalStartDate).Value.TotalDays + 1).ToString(CultureInfo.InvariantCulture), out var d) :+ double.TryParse((rentalEndDate - rentalStartDate).Value.TotalDays.ToString(CultureInfo.InvariantCulture), out d);price *= d;}if (includeDiscounts){//discount- var discountamount = await GetDiscountAmount(product, customer, currency, price);- double tmpDiscountAmount = discountamount.discountAmount;- List<ApplyDiscount> tmpAppliedDiscounts = discountamount.appliedDiscounts;+ var (tmpDiscountAmount, tmpAppliedDiscounts) = await GetDiscountAmount(product, customer, currency, price);price -= tmpDiscountAmount;if (tmpAppliedDiscounts != null)@@ -502,25 +457,19 @@ namespace Grand.Business.Catalog.Services.Pricesprice = 0;//rounding- if (_shoppingCartSettings.RoundPrices)- {- result.Price = RoundingHelper.RoundPrice(price, currency);- }- else- result.Price = price;+ result.Price = _shoppingCartSettings.RoundPrices ? RoundingHelper.RoundPrice(price, currency) : price;return result;}var modelprice = await PrepareModel();- if (includeDiscounts)+ if (!includeDiscounts)+ return (modelprice.Price, discountAmount, appliedDiscounts, modelprice.PreferredTierPrice);+ appliedDiscounts = modelprice.AppliedDiscounts.ToList();+ if (appliedDiscounts.Any()){- appliedDiscounts = modelprice.AppliedDiscounts.ToList();- if (appliedDiscounts.Any())- {- discountAmount = modelprice.AppliedDiscountAmount;- }+ discountAmount = modelprice.AppliedDiscountAmount;}return (modelprice.Price, discountAmount, appliedDiscounts, modelprice.PreferredTierPrice);@@ -559,7 +508,7 @@ namespace Grand.Business.Catalog.Services.Prices/// <param name="currency">The currency</param>/// <param name="shoppingCartType">Shopping cart type</param>/// <param name="quantity">Quantity</param>- /// <param name="attributes">Product atrributes</param>+ /// <param name="attributes">Product attributes</param>/// <param name="customerEnteredPrice">Customer entered price</param>/// <param name="rentalStartDate">Rental start date</param>/// <param name="rentalEndDate">Rental end date</param>@@ -629,28 +578,18 @@ namespace Grand.Business.Catalog.Services.Pricesforeach (var item in product.BundleProducts){var p1 = await _productService.GetProductById(item.ProductId);- if (p1 != null)+ var bundledProductsAttributeValues = p1?.ParseProductAttributeValues(attributes);+ if (bundledProductsAttributeValues == null) continue;+ foreach (var attributeValue in bundledProductsAttributeValues){- var bundledProductsAttributeValues = p1.ParseProductAttributeValues(attributes);- if (bundledProductsAttributeValues != null)- {- foreach (var attributeValue in bundledProductsAttributeValues)- {- attributesTotalPrice += (item.Quantity * await GetProductAttributeValuePriceAdjustment(attributeValue));- }- }+ attributesTotalPrice += item.Quantity * await GetProductAttributeValuePriceAdjustment(attributeValue);}}}}-- if (product.EnteredPrice)- {- finalPrice = customerEnteredPrice;- }- else+ if (!product.EnteredPrice){- int qty = 0;+ var qty = 0;if (_shoppingCartSettings.GroupTierPrices){qty = customer.ShoppingCartItems@@ -676,8 +615,7 @@ namespace Grand.Business.Catalog.Services.Prices}}- if (!finalPrice.HasValue)- finalPrice = 0;+ finalPrice ??= 0;//roundingif (_shoppingCartSettings.RoundPrices)@@ -702,20 +640,19 @@ namespace Grand.Business.Catalog.Services.Pricesdouble subTotal;//unit price- var getunitPrice = await GetUnitPrice(shoppingCartItem, product, includeDiscounts);- var unitPrice = getunitPrice.unitprice;- double discountAmount = getunitPrice.discountAmount;- List<ApplyDiscount> appliedDiscounts = getunitPrice.appliedDiscounts;+ var getUnitPrice = await GetUnitPrice(shoppingCartItem, product, includeDiscounts);+ var unitPrice = getUnitPrice.unitprice;+ var discountAmount = getUnitPrice.discountAmount;+ List<ApplyDiscount> appliedDiscounts = getUnitPrice.appliedDiscounts;//discountif (appliedDiscounts.Any()){Discount oneAndOnlyDiscount = null;if (appliedDiscounts.Count == 1)- oneAndOnlyDiscount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault().DiscountId);+ oneAndOnlyDiscount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault()?.DiscountId);- if (oneAndOnlyDiscount != null &&- oneAndOnlyDiscount.MaximumDiscountedQuantity.HasValue &&+ if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: { } } &&shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value){//we cannot apply discount for all shopping cart items@@ -757,7 +694,7 @@ namespace Grand.Business.Catalog.Services.Pricesif (product == null)throw new ArgumentNullException(nameof(product));- double cost = product.ProductCost;+ var cost = product.ProductCost;var attributeValues = product.ParseProductAttributeValues(attributes);foreach (var attributeValue in attributeValues){@@ -784,9 +721,6 @@ namespace Grand.Business.Catalog.Services.Pricesreturn cost;}---/// <summary>/// Get a price adjustment of a product attribute value/// </summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.csindex 3d7eba016..53f24fed4 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Auction service/// </summary>- public partial class AuctionService : IAuctionService+ public class AuctionService : IAuctionService{private readonly IRepository<Bid> _bidRepository;private readonly IRepository<Product> _productRepository;@@ -34,9 +34,9 @@ namespace Grand.Business.Catalog.Services.Products_mediator = mediator;}- public virtual Task<Bid> GetBid(string Id)+ public virtual Task<Bid> GetBid(string id){- return _bidRepository.GetByIdAsync(Id);+ return _bidRepository.GetByIdAsync(id);}public virtual async Task<Bid> GetLatestBid(string productId)@@ -87,11 +87,11 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.EntityDeleted(bid);var productToUpdate = await _productRepository.GetByIdAsync(bid.ProductId);- var _bid = await GetBidsByProductId(bid.ProductId);- var highestBid = _bid.OrderByDescending(x => x.Amount).FirstOrDefault();+ var bids = await GetBidsByProductId(bid.ProductId);+ var highestBid = bids.MaxBy(x => x.Amount);if (productToUpdate != null){- await UpdateHighestBid(productToUpdate, highestBid != null ? highestBid.Amount : 0, highestBid != null ? highestBid.CustomerId : "");+ await UpdateHighestBid(productToUpdate, highestBid?.Amount ?? 0, highestBid != null ? highestBid.CustomerId : "");}}public virtual async Task UpdateHighestBid(Product product, double bid, string highestBidder)@@ -114,11 +114,11 @@ namespace Grand.Business.Catalog.Services.Products!x.AuctionEnded && x.AvailableEndDateTimeUtc < DateTime.UtcNow).ToList());}- public virtual async Task UpdateAuctionEnded(Product product, bool ended, bool enddate = false)+ public virtual async Task UpdateAuctionEnded(Product product, bool ended, bool endDate = false){product.AuctionEnded = ended;product.UpdatedOnUtc = DateTime.UtcNow;- if (enddate)+ if (endDate)product.AvailableEndDateTimeUtc = DateTime.UtcNow;await _productRepository.UpdateAsync(product);@@ -127,8 +127,6 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.EntityUpdated(product);}--/// <summary>/// New bid/// </summary>@@ -140,7 +138,7 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="amount"></param>public virtual async Task NewBid(Customer customer, Product product, Store store, Language language, string warehouseId, double amount){- var latestbid = await GetLatestBid(product.Id);+ var latest = await GetLatestBid(product.Id);await InsertBid(new Bid{Date = DateTime.UtcNow,@@ -151,14 +149,14 @@ namespace Grand.Business.Catalog.Services.ProductsWarehouseId = warehouseId,});- if (latestbid != null)+ if (latest != null){- if (latestbid.CustomerId != customer.Id)+ if (latest.CustomerId != customer.Id){await _mediator.Send(new SendOutBidCustomerCommand(){Product = product,- Bid = latestbid,+ Bid = latest,Language = language});}@@ -170,10 +168,10 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Cancel bid/// </summary>- /// <param name="OrderId">OrderId</param>+ /// <param name="orderId">OrderId</param>public virtual async Task CancelBidByOrder(string orderId){- var bid = _bidRepository.Table.Where(x => x.OrderId == orderId).FirstOrDefault();+ var bid = _bidRepository.Table.FirstOrDefault(x => x.OrderId == orderId);if (bid != null){await _bidRepository.DeleteAsync(bid);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.csindex 90e227d3a..9a12842a7 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Copy Product service/// </summary>- public partial class CopyProductService : ICopyProductService+ public class CopyProductService : ICopyProductService{#region Fields@@ -172,7 +172,7 @@ namespace Grand.Business.Catalog.Services.ProductsproductCopy.ProductCollections.Add(productCollections);}- // product <-> releated products mappings+ // product <-> related products mappingsforeach (var relatedProduct in product.RelatedProducts){productCopy.RelatedProducts.Add(relatedProduct);@@ -228,7 +228,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _productService.InsertProduct(productCopy);//search engine name- string seName = await productCopy.ValidateSeName("", productCopy.Name, true, _seoSettings, _slugService, _languageService);+ var seName = await productCopy.ValidateSeName("", productCopy.Name, true, _seoSettings, _slugService, _languageService);productCopy.SeName = seName;await _productService.UpdateProduct(productCopy);await _slugService.SaveSlug(productCopy, seName, "");diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.csindex ec4600020..8f84351c6 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs@@ -92,7 +92,7 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Customer group products</returns>public virtual async Task<IList<CustomerGroupProduct>> GetCustomerGroupProducts(string customerGroupId){- string key = string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupId);+ var key = string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupId);return await _cacheBase.GetAsync(key, async () =>{return await Task.FromResult(_customerGroupProductRepository@@ -118,7 +118,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Gets customer groups product/// </summary>- /// <param name="Id">id</param>+ /// <param name="id">Ident</param>/// <returns>Customer group product</returns>public virtual async Task<CustomerGroupProduct> GetCustomerGroupProductById(string id){diff --git a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.csindex 2fe32a11a..8e4db6cbd 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs@@ -47,7 +47,7 @@ namespace Grand.Business.Catalog.Services.Products#region Utilities methods- private async Task ManageStockInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)+ private async Task ManageStockInventory(Product product, ShipmentItem shipmentItem){if (product.UseMultipleWarehouses){@@ -74,7 +74,7 @@ namespace Grand.Business.Catalog.Services.Productsawait UpdateStockProduct(product);}}- private async Task ManageStockByAttributesInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)+ private async Task ManageStockByAttributesInventory(Product product, ShipmentItem shipmentItem){var combination = product.FindProductAttributeCombination(shipmentItem.Attributes);if (combination == null)@@ -117,21 +117,19 @@ namespace Grand.Business.Catalog.Services.Productsforeach (var item in product.BundleProducts){var p1 = await _productRepository.GetByIdAsync(item.ProductId);- if (p1 != null && p1.Id != product.Id &&- p1.ManageInventoryMethodId != ManageInventoryMethod.DontManageStock)+ if (p1 == null || p1.Id == product.Id ||+ p1.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;+ var shipmentItem1 = new ShipmentItem() {+ Id = shipmentItem.Id,+ Attributes = shipmentItem.Attributes,+ OrderItemId = shipmentItem.OrderItemId,+ ProductId = shipmentItem.ProductId,+ Quantity = shipmentItem.Quantity * item.Quantity,+ WarehouseId = shipmentItem.WarehouseId+ };+ if (!await CheckExistsInventoryJournal(p1, shipmentItem1)){- var _shipmentItem = new ShipmentItem() {- Id = shipmentItem.Id,- Attributes = shipmentItem.Attributes,- OrderItemId = shipmentItem.OrderItemId,- ProductId = shipmentItem.ProductId,- Quantity = shipmentItem.Quantity * item.Quantity,- WarehouseId = shipmentItem.WarehouseId- };- if (!await CheckExistsInventoryJournal(p1, _shipmentItem))- {- await BookReservedInventory(p1, shipment, _shipmentItem);- }+ await BookReservedInventory(p1, shipment, shipmentItem1);}}}@@ -140,28 +138,22 @@ namespace Grand.Business.Catalog.Services.Productsvar attributeValues = product.ParseProductAttributeValues(shipmentItem.Attributes);foreach (var attributeValue in attributeValues){- if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct)- {- //associated product- var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);- if (associatedProduct != null- && associatedProduct.Id != product.Id- && associatedProduct.ManageInventoryMethodId != ManageInventoryMethod.DontManageStock)- {- if (!await CheckExistsInventoryJournal(associatedProduct, shipmentItem))- {- var _shipmentItem = new ShipmentItem() {- Id = shipmentItem.Id,- Attributes = shipmentItem.Attributes,- OrderItemId = shipmentItem.OrderItemId,- ProductId = shipmentItem.ProductId,- Quantity = shipmentItem.Quantity * attributeValue.Quantity,- WarehouseId = shipmentItem.WarehouseId- };- await BookReservedInventory(associatedProduct, shipment, _shipmentItem);- }- }- }+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;+ //associated product+ var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);+ if (associatedProduct == null+ || associatedProduct.Id == product.Id+ || associatedProduct.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;+ if (await CheckExistsInventoryJournal(associatedProduct, shipmentItem)) continue;+ var item = new ShipmentItem() {+ Id = shipmentItem.Id,+ Attributes = shipmentItem.Attributes,+ OrderItemId = shipmentItem.OrderItemId,+ ProductId = shipmentItem.ProductId,+ Quantity = shipmentItem.Quantity * attributeValue.Quantity,+ WarehouseId = shipmentItem.WarehouseId+ };+ await BookReservedInventory(associatedProduct, shipment, item);}}@@ -277,8 +269,9 @@ namespace Grand.Business.Catalog.Services.Products/// Adjust reserved inventory/// </summary>/// <param name="product">Product</param>- /// <param name="quantityToChange">Quantity to increase or descrease</param>+ /// <param name="quantityToChange">Quantity to increase or decrease</param>/// <param name="attributes">Attributes</param>+ /// <param name="warehouseId">Warehouse ident</param>public virtual async Task AdjustReserved(Product product, int quantityToChange, IList<CustomAttribute> attributes = null, string warehouseId = ""){if (product == null)@@ -348,14 +341,13 @@ namespace Grand.Business.Catalog.Services.Products//qty is increased. product is out of stock (minimum stock quantity is reached again)?if (_catalogSettings.PublishBackProductWhenCancellingOrders){- var totalStock = prevStockQuantity;if (quantityToChange > 0 && product.MinStockQuantity >= prevStockQuantity){switch (product.LowStockActivityId){case LowStockActivity.DisableBuyButton:product.DisableBuyButton = false;- product.LowStock = product.MinStockQuantity <= totalStock;+ product.LowStock = product.MinStockQuantity <= prevStockQuantity;await _productRepository.UpdateField(product.Id, x => x.DisableBuyButton, product.DisableBuyButton);await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);@@ -370,7 +362,7 @@ namespace Grand.Business.Catalog.Services.Productsbreak;case LowStockActivity.Unpublish:product.Published = true;- product.LowStock = product.MinStockQuantity < totalStock;+ product.LowStock = product.MinStockQuantity < prevStockQuantity;await _productRepository.UpdateField(product.Id, x => x.Published, product.Published);await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);@@ -427,7 +419,7 @@ namespace Grand.Business.Catalog.Services.Productsforeach (var item in product.BundleProducts){var p1 = await _productRepository.GetByIdAsync(item.ProductId);- if (p1 != null && (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock || p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes))+ if (p1 is { ManageInventoryMethodId: ManageInventoryMethod.ManageStock or ManageInventoryMethod.ManageStockByAttributes }){await AdjustReserved(p1, quantityToChange * item.Quantity, attributes, warehouseId);}@@ -438,14 +430,12 @@ namespace Grand.Business.Catalog.Services.Productsvar attributeValues = product.ParseProductAttributeValues(attributes);foreach (var attributeValue in attributeValues){- if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct)+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;+ //associated product (bundle)+ var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);+ if (associatedProduct != null){- //associated product (bundle)- var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);- if (associatedProduct != null)- {- await AdjustReserved(associatedProduct, quantityToChange * attributeValue.Quantity, null, warehouseId);- }+ await AdjustReserved(associatedProduct, quantityToChange * attributeValue.Quantity, null, warehouseId);}}@@ -458,6 +448,7 @@ namespace Grand.Business.Catalog.Services.Products/// </summary>/// <param name="product">Product</param>/// <param name="quantity">Quantity, must be negative</param>+ /// <param name="warehouseId"></param>protected virtual async Task ReserveInventory(Product product, int quantity, string warehouseId){if (product == null)@@ -501,6 +492,7 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="product">Product</param>/// <param name="combination">Combination</param>/// <param name="quantity">Quantity, must be negative</param>+ /// <param name="warehouseId">Warehouse ident</param>protected virtual async Task ReserveInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId){if (product == null)@@ -558,6 +550,7 @@ namespace Grand.Business.Catalog.Services.Products/// </summary>/// <param name="product">Product</param>/// <param name="quantity">Quantity, must be positive</param>+ /// <param name="warehouseId">Warehouse ident</param>protected virtual async Task UnblockReservedInventory(Product product, int quantity, string warehouseId){if (product == null)@@ -601,7 +594,9 @@ namespace Grand.Business.Catalog.Services.Products/// Unblocks the given quantity reserved items in the warehouses/// </summary>/// <param name="product">Product</param>+ /// <param name="combination">Combination</param>/// <param name="quantity">Quantity, must be positive</param>+ /// <param name="warehouseId">Warehouse ident</param>protected virtual async Task UnblockReservedInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId){if (product == null)@@ -610,11 +605,9 @@ namespace Grand.Business.Catalog.Services.Productsif (quantity < 0)throw new ArgumentException("Value must be positive.", nameof(quantity));- var qty = quantity;-if (!product.UseMultipleWarehouses){- combination.ReservedQuantity -= qty;+ combination.ReservedQuantity -= quantity;if (combination.ReservedQuantity < 0)combination.ReservedQuantity = 0;@@ -631,7 +624,7 @@ namespace Grand.Business.Catalog.Services.Productsif (pwi == null)return;- pwi.ReservedQuantity -= qty;+ pwi.ReservedQuantity -= quantity;if (pwi.ReservedQuantity < 0)pwi.ReservedQuantity = 0;@@ -668,12 +661,12 @@ namespace Grand.Business.Catalog.Services.Products//standard manage stockif (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock){- await ManageStockInventory(product, shipment, shipmentItem);+ await ManageStockInventory(product, shipmentItem);}//manage stock by attributesif (shipmentItem.Attributes != null && product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes){- await ManageStockByAttributesInventory(product, shipment, shipmentItem);+ await ManageStockByAttributesInventory(product, shipmentItem);}//manage stock by bundle products@@ -695,7 +688,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.EntityUpdated(product);//insert inventory journal- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock || product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)+ if (product.ManageInventoryMethodId is ManageInventoryMethod.ManageStock or ManageInventoryMethod.ManageStockByAttributes)await InsertInventoryJournal(product, shipment, shipmentItem);}@@ -745,7 +738,7 @@ namespace Grand.Business.Catalog.Services.Products//updateawait _productRepository.UpdateField(product.Id, x => x.StockQuantity, product.StockQuantity);await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);- await _productRepository.UpdateField(product.Id, x => x.LowStock, ((product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0));+ await _productRepository.UpdateField(product.Id, x => x.LowStock, (product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0);await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.csindex 5f8698821..3c4b584c5 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Out of stock subscription service/// </summary>- public partial class OutOfStockSubscriptionService : IOutOfStockSubscriptionService+ public class OutOfStockSubscriptionService : IOutOfStockSubscriptionService{#region Fields@@ -26,9 +26,6 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Ctor/// </summary>- /// <param name="outOfStockSubscriptionRepository">Out of stock subscription repository</param>- /// <param name="messageProviderService">Message provider service</param>- /// <param name="IMediator">Mediator</param>public OutOfStockSubscriptionService(IRepository<OutOfStockSubscription> outOfStockSubscriptionRepository,IMediator mediator){@@ -54,14 +51,13 @@ namespace Grand.Business.Catalog.Services.Products{var query = from p in _outOfStockSubscriptionRepository.Tableselect p;-//customer- query = query.Where(biss => biss.CustomerId == customerId);+ query = query.Where(x => x.CustomerId == customerId);//store- if (!String.IsNullOrEmpty(storeId))- query = query.Where(biss => biss.StoreId == storeId);+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(x => x.StoreId == storeId);- query = query.OrderByDescending(biss => biss.CreatedOnUtc);+ query = query.OrderByDescending(x => x.CreatedOnUtc);return await PagedList<OutOfStockSubscription>.Create(query, pageIndex, pageSize);}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.csindex 89fff2f8f..f362a4f96 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product attribute formatter/// </summary>- public partial class ProductAttributeFormatter : IProductAttributeFormatter+ public class ProductAttributeFormatter : IProductAttributeFormatter{private readonly IWorkContext _workContext;private readonly IProductAttributeService _productAttributeService;@@ -61,15 +61,16 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="product">Product</param>/// <param name="customAttributes">Attributes</param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>/// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>/// <param name="renderGiftVoucherAttributes">A value indicating whether to render gift voucher attributes</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>+ /// <param name="showInAdmin">Show in admin</param>/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes,- Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true,+ Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true,bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true,bool allowHyperlinks = true, bool showInAdmin = false){@@ -79,12 +80,7 @@ namespace Grand.Business.Catalog.Services.Productsif (customAttributes == null || !customAttributes.Any())return result.ToString();- var langId = string.Empty;-- if (_workContext.WorkingLanguage != null)- langId = _workContext.WorkingLanguage.Id;- else- langId = customer?.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);+ var langId = _workContext.WorkingLanguage != null ? _workContext.WorkingLanguage.Id : customer?.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);if (string.IsNullOrEmpty(langId))langId = "";@@ -92,78 +88,72 @@ namespace Grand.Business.Catalog.Services.Products//attributesif (renderProductAttributes){- result = await PrepareFormattedAttribute(product, customAttributes, langId, serapator, htmlEncode,+ result = await PrepareFormattedAttribute(product, customAttributes, langId, separator, htmlEncode,renderPrices, allowHyperlinks, showInAdmin);if (product.ProductTypeId == ProductType.BundledProduct){- int i = 0;+ var i = 0;foreach (var bundle in product.BundleProducts){var p1 = await _productService.GetProductById(bundle.ProductId);- if (p1 != null)- {- if (i > 0)- result.Append(serapator);+ if (p1 == null) continue;+ if (i > 0)+ result.Append(separator);- result.Append($"<a href=\"{p1.GetSeName(langId)}\"> {p1.GetTranslation(x => x.Name, langId)} </a>");- var formattedAttribute = await PrepareFormattedAttribute(p1, customAttributes, langId, serapator, htmlEncode,+ result.Append($"<a href=\"{p1.GetSeName(langId)}\"> {p1.GetTranslation(x => x.Name, langId)} </a>");+ var formattedAttribute = await PrepareFormattedAttribute(p1, customAttributes, langId, separator, htmlEncode,renderPrices, allowHyperlinks, showInAdmin);- if (formattedAttribute.Length > 0)- {- result.Append(serapator);- result.Append(formattedAttribute);- }- i++;+ if (formattedAttribute.Length > 0)+ {+ result.Append(separator);+ result.Append(formattedAttribute);}+ i++;}}}//gift vouchers- if (renderGiftVoucherAttributes)- {- if (product.IsGiftVoucher)- {- GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);+ if (!renderGiftVoucherAttributes) return result.ToString();+ if (!product.IsGiftVoucher) return result.ToString();+ GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);- //sender- var giftVoucherFrom = product.GiftVoucherTypeId == GiftVoucherType.Virtual ?- string.Format(_translationService.GetResource("GiftVoucherAttribute.From.Virtual"), giftVoucherSenderName, giftVoucherSenderEmail) :- string.Format(_translationService.GetResource("GiftVoucherAttribute.From.Physical"), giftVoucherSenderName);- //recipient- var giftVoucherFor = product.GiftVoucherTypeId == GiftVoucherType.Virtual ?- string.Format(_translationService.GetResource("GiftVoucherAttribute.For.Virtual"), giftVoucherRecipientName, giftVoucherRecipientEmail) :- string.Format(_translationService.GetResource("GiftVoucherAttribute.For.Physical"), giftVoucherRecipientName);+ //sender+ var giftVoucherFrom = product.GiftVoucherTypeId == GiftVoucherType.Virtual ?+ string.Format(_translationService.GetResource("GiftVoucherAttribute.From.Virtual"), giftVoucherSenderName, giftVoucherSenderEmail) :+ string.Format(_translationService.GetResource("GiftVoucherAttribute.From.Physical"), giftVoucherSenderName);+ //recipient+ var giftVoucherFor = product.GiftVoucherTypeId == GiftVoucherType.Virtual ?+ string.Format(_translationService.GetResource("GiftVoucherAttribute.For.Virtual"), giftVoucherRecipientName, giftVoucherRecipientEmail) :+ string.Format(_translationService.GetResource("GiftVoucherAttribute.For.Physical"), giftVoucherRecipientName);- //encode (if required)- if (htmlEncode)- {- giftVoucherFrom = WebUtility.HtmlEncode(giftVoucherFrom);- giftVoucherFor = WebUtility.HtmlEncode(giftVoucherFor);- }+ //encode (if required)+ if (htmlEncode)+ {+ giftVoucherFrom = WebUtility.HtmlEncode(giftVoucherFrom);+ giftVoucherFor = WebUtility.HtmlEncode(giftVoucherFor);+ }- if (!String.IsNullOrEmpty(result.ToString()))- {- result.Append(serapator);- }- result.Append(giftVoucherFrom);- result.Append(serapator);- result.Append(giftVoucherFor);- }+ if (!string.IsNullOrEmpty(result.ToString()))+ {+ result.Append(separator);}+ result.Append(giftVoucherFrom);+ result.Append(separator);+ result.Append(giftVoucherFor);return result.ToString();}private async Task<StringBuilder> PrepareFormattedAttribute(Product product, IList<CustomAttribute> customAttributes, string langId,- string serapator, bool htmlEncode, bool renderPrices,+ string separator, bool htmlEncode, bool renderPrices,bool allowHyperlinks, bool showInAdmin){var result = new StringBuilder();var attributes = product.ParseProductAttributeMappings(customAttributes);- for (int i = 0; i < attributes.Count; i++)+ for (var i = 0; i < attributes.Count; i++){var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);if (productAttribute == null)@@ -171,73 +161,87 @@ namespace Grand.Business.Catalog.Services.Productsvar attribute = attributes[i];var valuesStr = ProductExtensions.ParseValues(customAttributes, attribute.Id);- for (int j = 0; j < valuesStr.Count; j++)+ for (var j = 0; j < valuesStr.Count; j++){- string valueStr = valuesStr[j];- string formattedAttribute = string.Empty;+ var valueStr = valuesStr[j];+ var formattedAttribute = string.Empty;if (!attribute.ShouldHaveValues()){- //no values- if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)+ switch (attribute.AttributeControlTypeId){- //multiline textbox- var attributeName = productAttribute.GetTranslation(a => a.Name, langId);- //encode (if required)- if (htmlEncode)- attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));- //we never encode multiline textbox input- }- else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)- {- //file upload- if (Guid.TryParse(valueStr, out var downloadGuid))+ //no values+ case AttributeControlType.MultilineTextbox:{- var attributeText = string.Empty;+ //multiline textvar attributeName = productAttribute.GetTranslation(a => a.Name, langId);- if (allowHyperlinks)+ //encode (if required)+ if (htmlEncode)+ attributeName = WebUtility.HtmlEncode(attributeName);+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input+ break;+ }+ case AttributeControlType.FileUpload:+ {+ //file upload+ if (Guid.TryParse(valueStr, out var downloadGuid)){- var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentHost.Url.TrimEnd('/'), downloadGuid);- attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, attribute.GetTranslation(a => a.TextPrompt, langId));+ var attributeText = string.Empty;+ var attributeName = productAttribute.GetTranslation(a => a.Name, langId);+ if (allowHyperlinks)+ {+ var downloadLink =+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";+ attributeText =+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, langId)}</a>";+ }+ formattedAttribute = $"{attributeName}: {attributeText}";}- formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);++ break;+ }+ default:+ {+ //other attributes (text box, datepicker)+ formattedAttribute =+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: {valueStr}";+ //encode (if required)+ if (htmlEncode)+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);+ break;}- }- else- {- //other attributes (textbox, datepicker)- formattedAttribute = string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), valueStr);- //encode (if required)- if (htmlEncode)- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}}else{//attributes with values- if (product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault() != null)+ if (product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id) != null){- var attributeValue = product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();+ var attributeValue = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id).ProductAttributeValues.FirstOrDefault(x => x.Id == valueStr);if (attributeValue != null){- formattedAttribute = string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), attributeValue.GetTranslation(a => a.Name, langId));+ formattedAttribute =+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: {attributeValue.GetTranslation(a => a.Name, langId)}";if (renderPrices){- double attributeValuePriceAdjustment = await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);- var prices = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);- double priceAdjustmentBase = prices.productprice;- double taxRate = prices.taxRate;- if (priceAdjustmentBase > 0)+ var attributeValuePriceAdjustment = await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);+ var (priceAdjustmentBase, _) = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);+ switch (priceAdjustmentBase){- string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase, false);- formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);- }- else if (priceAdjustmentBase < 0)- {- string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase, false);- formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr);+ case > 0:+ {+ var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase, false);+ formattedAttribute += $" [+{priceAdjustmentStr}]";+ break;+ }+ case < 0:+ {+ var priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase, false);+ formattedAttribute += $" [-{priceAdjustmentStr}]";+ break;+ }}}@@ -245,7 +249,8 @@ namespace Grand.Business.Catalog.Services.Productselse{if (showInAdmin)- formattedAttribute += string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), "");+ formattedAttribute +=+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: ";}//encode (if required)@@ -254,12 +259,10 @@ namespace Grand.Business.Catalog.Services.Products}}- if (!string.IsNullOrEmpty(formattedAttribute))- {- if (i != 0 || j != 0)- result.Append(serapator);- result.Append(formattedAttribute);- }+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}}return result;diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.csindex b87f9aa1b..45eb4f051 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product attribute service/// </summary>- public partial class ProductAttributeService : IProductAttributeService+ public class ProductAttributeService : IProductAttributeService{#region Fields@@ -31,7 +31,7 @@ namespace Grand.Business.Catalog.Services.Products/// </summary>/// <param name="cacheBase">Cache manager</param>/// <param name="productAttributeRepository">Product attribute repository</param>- /// <param name="productAttributeCombinationRepository">Product attribute combination repository</param>+ /// <param name="productRepository">Product repository</param>/// <param name="mediator">Mediator</param>public ProductAttributeService(ICacheBase cacheBase,IRepository<ProductAttribute> productAttributeRepository,@@ -58,7 +58,7 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Product attributes</returns>public virtual async Task<IPagedList<ProductAttribute>> GetAllProductAttributes(int pageIndex = 0, int pageSize = int.MaxValue){- string key = string.Format(CacheKey.PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize);+ var key = string.Format(CacheKey.PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize);return await _cacheBase.GetAsync(key, () =>{var query = from pa in _productAttributeRepository.Table@@ -75,7 +75,7 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Product attribute </returns>public virtual Task<ProductAttribute> GetProductAttributeById(string productAttributeId){- string key = string.Format(CacheKey.PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId);+ var key = string.Format(CacheKey.PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId);return _cacheBase.GetAsync(key, () => _productAttributeRepository.GetByIdAsync(productAttributeId));}@@ -227,15 +227,12 @@ namespace Grand.Business.Catalog.Services.Productsvar p = await _productRepository.GetByIdAsync(productId);if (p != null){- var pavs = p.ProductAttributeMappings.Where(x => x.Id == productAttributeMappingId).FirstOrDefault();- if (pavs != null)+ var pavs = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);+ var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);+ if (pav != null){- var pav = pavs.ProductAttributeValues.Where(x => x.Id == productAttributeValue.Id).FirstOrDefault();- if (pav != null)- {- pavs.ProductAttributeValues.Remove(pav);- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);- }+ pavs.ProductAttributeValues.Remove(pav);+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);}}@@ -288,31 +285,25 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(productAttributeValue));var p = await _productRepository.GetByIdAsync(productId);- if (p != null)+ var pavs = p?.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);+ var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);+ if (pav != null){- var pavs = p.ProductAttributeMappings.Where(x => x.Id == productAttributeMappingId).FirstOrDefault();- if (pavs != null)- {- var pav = pavs.ProductAttributeValues.Where(x => x.Id == productAttributeValue.Id).FirstOrDefault();- if (pav != null)- {- pav.AttributeValueTypeId = productAttributeValue.AttributeValueTypeId;- pav.AssociatedProductId = productAttributeValue.AssociatedProductId;- pav.Name = productAttributeValue.Name;- pav.ColorSquaresRgb = productAttributeValue.ColorSquaresRgb;- pav.ImageSquaresPictureId = productAttributeValue.ImageSquaresPictureId;- pav.PriceAdjustment = productAttributeValue.PriceAdjustment;- pav.WeightAdjustment = productAttributeValue.WeightAdjustment;- pav.Cost = productAttributeValue.Cost;- pav.Quantity = productAttributeValue.Quantity;- pav.IsPreSelected = productAttributeValue.IsPreSelected;- pav.DisplayOrder = productAttributeValue.DisplayOrder;- pav.PictureId = productAttributeValue.PictureId;- pav.Locales = productAttributeValue.Locales;-- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);- }- }+ pav.AttributeValueTypeId = productAttributeValue.AttributeValueTypeId;+ pav.AssociatedProductId = productAttributeValue.AssociatedProductId;+ pav.Name = productAttributeValue.Name;+ pav.ColorSquaresRgb = productAttributeValue.ColorSquaresRgb;+ pav.ImageSquaresPictureId = productAttributeValue.ImageSquaresPictureId;+ pav.PriceAdjustment = productAttributeValue.PriceAdjustment;+ pav.WeightAdjustment = productAttributeValue.WeightAdjustment;+ pav.Cost = productAttributeValue.Cost;+ pav.Quantity = productAttributeValue.Quantity;+ pav.IsPreSelected = productAttributeValue.IsPreSelected;+ pav.DisplayOrder = productAttributeValue.DisplayOrder;+ pav.PictureId = productAttributeValue.PictureId;+ pav.Locales = productAttributeValue.Locales;++ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);}//cachediff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.csindex 071b735c7..4f513fdda 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs@@ -18,18 +18,18 @@ namespace Grand.Business.Catalog.Services.Productspublic virtual async Task<Course> GetCourseByProductId(string productId){- return await Task.FromResult(_courseRepository.Table.Where(p => p.ProductId == productId).FirstOrDefault());+ return await Task.FromResult(_courseRepository.Table.FirstOrDefault(p => p.ProductId == productId));}public virtual async Task<Product> GetProductByCourseId(string courseId){- return await Task.FromResult(_productRepository.Table.Where(p => p.CourseId == courseId).FirstOrDefault());+ return await Task.FromResult(_productRepository.Table.FirstOrDefault(p => p.CourseId == courseId));}public virtual async Task UpdateCourseOnProduct(string productId, string courseId){if (string.IsNullOrEmpty(productId))- throw new ArgumentNullException("productId");+ throw new ArgumentNullException(nameof(productId));await _productRepository.UpdateField(productId, x => x.CourseId, courseId);await _productRepository.UpdateField(productId, x => x.UpdatedOnUtc, DateTime.UtcNow);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.csindex 18316734a..bfa202ffe 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product layout service/// </summary>- public partial class ProductLayoutService : IProductLayoutService+ public class ProductLayoutService : IProductLayoutService{#region Fields@@ -65,7 +65,7 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Product layout</returns>public virtual Task<ProductLayout> GetProductLayoutById(string productLayoutId){- string key = string.Format(CacheKey.PRODUCT_LAYOUT_BY_ID_KEY, productLayoutId);+ var key = string.Format(CacheKey.PRODUCT_LAYOUT_BY_ID_KEY, productLayoutId);return _cacheBase.GetAsync(key, () => _productLayoutRepository.GetByIdAsync(productLayoutId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.csindex 276d5206a..7e4e7e889 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product reservation service/// </summary>- public partial class ProductReservationService : IProductReservationService+ public class ProductReservationService : IProductReservationService{private readonly IRepository<ProductReservation> _productReservationRepository;private readonly IRepository<CustomerReservationsHelper> _customerReservationsHelperRepository;@@ -26,11 +26,15 @@ namespace Grand.Business.Catalog.Services.Products_mediator = mediator;}-+/// <summary>/// Gets product reservations for product Id/// </summary>/// <param name="productId">Product Id</param>+ /// <param name="showVacant">Show vacant</param>+ /// <param name="date">Date</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>/// <returns>Product reservations</returns>public virtual async Task<IPagedList<ProductReservation>> GetProductReservationsByProductId(string productId, bool? showVacant, DateTime? date,int pageIndex = 0, int pageSize = int.MaxValue)@@ -39,14 +43,7 @@ namespace Grand.Business.Catalog.Services.Productsif (showVacant.HasValue){- if (showVacant.Value)- {- query = query.Where(x => (x.OrderId == "" || x.OrderId == null));- }- else- {- query = query.Where(x => (x.OrderId != "" && x.OrderId != null));- }+ query = showVacant.Value ? query.Where(x => x.OrderId == "" || x.OrderId == null) : query.Where(x => x.OrderId != "" && x.OrderId != null);}if (date.HasValue)@@ -109,11 +106,11 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Gets product reservation for specified Id/// </summary>- /// <param name="Id">Product Id</param>+ /// <param name="id">Product ident</param>/// <returns>Product reservation</returns>- public virtual Task<ProductReservation> GetProductReservation(string Id)+ public virtual Task<ProductReservation> GetProductReservation(string id){- return _productReservationRepository.GetByIdAsync(Id);+ return _productReservationRepository.GetByIdAsync(id);}/// <summary>@@ -163,17 +160,18 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Gets customer reservations helper by id/// </summary>- /// <param name="Id"></param>+ /// <param name="id"></param>/// <returns>CustomerReservationsHelper</returns>- public virtual Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string Id)+ public virtual Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string id){- return _customerReservationsHelperRepository.GetByIdAsync(Id);+ return _customerReservationsHelperRepository.GetByIdAsync(id);}/// <summary>/// Gets customer reservations helpers/// </summary>- /// <returns>List<CustomerReservationsHelper></returns>+ /// <returns>List<CustomerReservationsHelper />+ /// </returns>public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelpers(string customerId){return await Task.FromResult(_customerReservationsHelperRepository.Table.Where(x => x.CustomerId == customerId).ToList());@@ -182,8 +180,9 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Gets customer reservations helper by Shopping Cart Item id/// </summary>- /// <param name="Id"></param>- /// <returns>List<CustomerReservationsHelper></returns>+ /// <param name="sciId">sci ident</param>+ /// <returns>IList<CustomerReservationsHelper />+ /// </returns>public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelperBySciId(string sciId){return await Task.FromResult(_customerReservationsHelperRepository.Table.Where(x => x.ShoppingCartItemId == sciId).ToList());diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.csindex 402b719cd..e2233308e 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs@@ -38,6 +38,10 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="fromUtc">Item creation from; null to load all records</param>/// <param name="toUtc">Item item creation to; null to load all records</param>/// <param name="message">Search title or review text; null to load all records</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="productId">Product ident</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>/// <returns>Reviews</returns>public virtual async Task<IPagedList<ProductReview>> GetAllProductReviews(string customerId, bool? approved,DateTime? fromUtc = null, DateTime? toUtc = null,@@ -48,17 +52,17 @@ namespace Grand.Business.Catalog.Services.Productsif (approved.HasValue)query = query.Where(c => c.IsApproved == approved.Value);- if (!String.IsNullOrEmpty(customerId))+ if (!string.IsNullOrEmpty(customerId))query = query.Where(c => c.CustomerId == customerId);if (fromUtc.HasValue)query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);if (toUtc.HasValue)query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);- if (!String.IsNullOrEmpty(message))+ if (!string.IsNullOrEmpty(message))query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId))query = query.Where(c => c.StoreId == storeId || c.StoreId == "");- if (!String.IsNullOrEmpty(productId))+ if (!string.IsNullOrEmpty(productId))query = query.Where(c => c.ProductId == productId);query = query.OrderByDescending(c => c.CreatedOnUtc);@@ -80,26 +84,26 @@ namespace Grand.Business.Catalog.Services.Products//event notificationawait _mediator.EntityInserted(productReview);}- public virtual async Task UpdateProductReview(ProductReview productreview)+ public virtual async Task UpdateProductReview(ProductReview productReview){- if (productreview == null)- throw new ArgumentNullException(nameof(productreview));+ if (productReview == null)+ throw new ArgumentNullException(nameof(productReview));var update = UpdateBuilder<ProductReview>.Create()- .Set(x => x.Title, productreview.Title)- .Set(x => x.ReviewText, productreview.ReviewText)- .Set(x => x.ReplyText, productreview.ReplyText)- .Set(x => x.Signature, productreview.Signature)+ .Set(x => x.Title, productReview.Title)+ .Set(x => x.ReviewText, productReview.ReviewText)+ .Set(x => x.ReplyText, productReview.ReplyText)+ .Set(x => x.Signature, productReview.Signature).Set(x => x.UpdatedOnUtc, DateTime.UtcNow)- .Set(x => x.IsApproved, productreview.IsApproved)- .Set(x => x.HelpfulNoTotal, productreview.HelpfulNoTotal)- .Set(x => x.HelpfulYesTotal, productreview.HelpfulYesTotal)- .Set(x => x.ProductReviewHelpfulnessEntries, productreview.ProductReviewHelpfulnessEntries);+ .Set(x => x.IsApproved, productReview.IsApproved)+ .Set(x => x.HelpfulNoTotal, productReview.HelpfulNoTotal)+ .Set(x => x.HelpfulYesTotal, productReview.HelpfulYesTotal)+ .Set(x => x.ProductReviewHelpfulnessEntries, productReview.ProductReviewHelpfulnessEntries);- await _productReviewRepository.UpdateOneAsync(x => x.Id == productreview.Id, update);+ await _productReviewRepository.UpdateOneAsync(x => x.Id == productReview.Id, update);//event notification- await _mediator.EntityUpdated(productreview);+ await _mediator.EntityUpdated(productReview);}/// <summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.csindex 891956e48..646fff2c4 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs@@ -19,7 +19,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product service/// </summary>- public partial class ProductService : IProductService+ public class ProductService : IProductService{#region Fields@@ -87,21 +87,18 @@ namespace Grand.Business.Catalog.Services.Products/// Gets product/// </summary>/// <param name="productId">Product identifier</param>- /// <param name="fromDB">get data from db (not from cache)</param>+ /// <param name="fromDb">get data from db (not from cache)</param>/// <returns>Product</returns>- public virtual async Task<Product> GetProductById(string productId, bool fromDB = false)+ public virtual async Task<Product> GetProductById(string productId, bool fromDb = false){if (string.IsNullOrEmpty(productId))return null;- if (fromDB)+ if (fromDb)return await _productRepository.GetByIdAsync(productId);var key = string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId);- return await _cacheBase.GetAsync(key, () =>- {- return _productRepository.GetByIdAsync(productId);- });+ return await _cacheBase.GetAsync(key, () => _productRepository.GetByIdAsync(productId));}/// <summary>@@ -111,20 +108,16 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Product</returns>public virtual async Task<Product> GetProductByIdIncludeArch(string productId){- if (String.IsNullOrEmpty(productId))+ if (string.IsNullOrEmpty(productId))return null;- var product = await GetProductById(productId);- if (product == null)- product = await _mediator.Send(new GetProductArchByIdQuery() { Id = productId });-+ var product = await GetProductById(productId) ?? await _mediator.Send(new GetProductArchByIdQuery() { Id = productId });return product;}--/// <summary>/// Get products by identifiers/// </summary>/// <param name="productIds">Product identifiers</param>+ /// <param name="showHidden">Show hidden</param>/// <returns>Products</returns>public virtual async Task<IList<Product>> GetProductsByIds(string[] productIds, bool showHidden = false){@@ -132,10 +125,10 @@ namespace Grand.Business.Catalog.Services.Productsreturn new List<Product>();var products = new List<Product>();- foreach (string id in productIds)+ foreach (var id in productIds){var product = await GetProductById(id);- if (product != null && (showHidden || (_aclService.Authorize(product, _workContext.CurrentCustomer) && _aclService.Authorize(product, _workContext.CurrentStore.Id) && (product.IsAvailable()))))+ if (product != null && (showHidden || (_aclService.Authorize(product, _workContext.CurrentCustomer) && _aclService.Authorize(product, _workContext.CurrentStore.Id) && product.IsAvailable())))products.Add(product);}return products;@@ -145,6 +138,8 @@ namespace Grand.Business.Catalog.Services.Products/// Gets products by discount/// </summary>/// <param name="discountId">Product identifiers</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>/// <returns>Products</returns>public virtual async Task<IPagedList<Product>> GetProductsByDiscount(string discountId, int pageIndex = 0, int pageSize = int.MaxValue){@@ -252,7 +247,7 @@ namespace Grand.Business.Catalog.Services.Products.Set(x => x.MetaTitle, product.MetaTitle).Set(x => x.MinEnteredPrice, product.MinEnteredPrice).Set(x => x.MinStockQuantity, product.MinStockQuantity)- .Set(x => x.LowStock, ((product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0))+ .Set(x => x.LowStock, (product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0).Set(x => x.Name, product.Name).Set(x => x.NotApprovedRatingSum, product.NotApprovedRatingSum).Set(x => x.NotApprovedTotalReviews, product.NotApprovedTotalReviews)@@ -315,12 +310,16 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.Publish(new UpdateProductOnCartEvent(product));}- //raise event- if (!oldProduct.Published && product.Published)- await _mediator.Publish(new ProductPublishEvent(product));-- if (oldProduct.Published && !product.Published)- await _mediator.Publish(new ProductUnPublishEvent(product));+ switch (oldProduct.Published)+ {+ //raise event+ case false when product.Published:+ await _mediator.Publish(new ProductPublishEvent(product));+ break;+ case true when !product.Published:+ await _mediator.Publish(new ProductUnPublishEvent(product));+ break;+ }//cacheawait _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));@@ -341,7 +340,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(product));//update field- await _productRepository.UpdateField<T>(product.Id, expression, value);+ await _productRepository.UpdateField(product.Id, expression, value);//cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);@@ -366,7 +365,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(product));//inc field- await _productRepository.IncField<T>(product.Id, expression, value);+ await _productRepository.IncField(product.Id, expression, value);}/// <summary>@@ -388,8 +387,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.EntityDeleted(product);}-- public virtual async Task UnpublishProduct(Product product)+ public virtual async Task UnPublishProduct(Product product){var update = UpdateBuilder<Product>.Create().Set(x => x.Published, false)@@ -456,7 +454,6 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Search products/// </summary>- /// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param>/// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>@@ -468,6 +465,7 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="warehouseId">Warehouse identifier; "" to load all records</param>/// <param name="productType">Product type; "" to load all records</param>/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>+ /// <param name="showOnHomePage">Show on home page</param>/// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and collections). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>/// <param name="priceMin">Minimum price; null to load all records</param>/// <param name="priceMax">Maximum price; null to load all records</param>@@ -486,6 +484,7 @@ namespace Grand.Business.Catalog.Services.Products/// true - load only "Published" products/// false - load only "Unpublished" products/// </param>+ /// <param name="markedAsNewOnly">Marked as new</param>/// <returns>Products</returns>public virtual async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)> SearchProducts(bool loadFilterableSpecificationAttributeOptionIds = false,@@ -517,7 +516,7 @@ namespace Grand.Business.Catalog.Services.Productsbool? overridePublished = null){- var model = await _mediator.Send(new GetSearchProductsQuery() {+ var model = await _mediator.Send(new GetSearchProductsQuery {Customer = _workContext.CurrentCustomer,LoadFilterableSpecificationAttributeOptionIds = loadFilterableSpecificationAttributeOptionIds,PageIndex = pageIndex,@@ -558,7 +557,7 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Products</returns>- public virtual async Task<IPagedList<Product>> GetProductsByProductAtributeId(string productAttributeId,+ public virtual async Task<IPagedList<Product>> GetProductsByProductAttributeId(string productAttributeId,int pageIndex = 0, int pageSize = int.MaxValue){var query = from p in _productRepository.Table@@ -575,6 +574,7 @@ namespace Grand.Business.Catalog.Services.Products/// <param name="parentGroupedProductId">Parent product identifier (used with grouped products)</param>/// <param name="storeId">Store identifier; "" to load all records</param>/// <param name="vendorId">Vendor identifier; "" to load all records</param>+ /// <param name="showHidden">Show hidden</param>/// <returns>Products</returns>public virtual async Task<IList<Product>> GetAssociatedProducts(string parentGroupedProductId,string storeId = "", string vendorId = "", bool showHidden = false)@@ -631,7 +631,7 @@ namespace Grand.Business.Catalog.Services.Productsreturn null;sku = sku.Trim();- return await Task.FromResult(_productRepository.Table.Where(x => x.Sku == sku).FirstOrDefault());+ return await Task.FromResult(_productRepository.Table.FirstOrDefault(x => x.Sku == sku));}public virtual async Task UpdateAssociatedProduct(Product product)@@ -888,37 +888,33 @@ namespace Grand.Business.Catalog.Services.Productsvar cartProductIds = new List<string>();foreach (var sci in cart){- string prodId = sci.ProductId;- if (!cartProductIds.Contains(prodId))- cartProductIds.Add(prodId);+ if (!cartProductIds.Contains(sci.ProductId))+ cartProductIds.Add(sci.ProductId);}foreach (var sci in cart){var product = await GetProductById(sci.ProductId);- if (product == null || !product.Published)+ if (product is not { Published: true })continue;var crossSells = product.CrossSellProduct;foreach (var crossSell in crossSells){//validate that this product is not added to result yet- //validate that this product is not in the cart- if (result.Find(p => p.Id == crossSell) == null &&- !cartProductIds.Contains(crossSell))- {- var productToAdd = await GetProductById(crossSell);- //validate product- if (productToAdd == null || !productToAdd.Published- || !_aclService.Authorize(productToAdd, _workContext.CurrentCustomer) || !_aclService.Authorize(productToAdd, _workContext.CurrentStore.Id)- || !productToAdd.IsAvailable())- continue;-- //add a product to result- result.Add(productToAdd);- if (result.Count >= numberOfProducts)- return result;- }+ if (result.Find(p => p.Id == crossSell) != null ||+ cartProductIds.Contains(crossSell)) continue;+ var productToAdd = await GetProductById(crossSell);+ //validate product+ if (productToAdd is not { Published: true }+ || !_aclService.Authorize(productToAdd, _workContext.CurrentCustomer) || !_aclService.Authorize(productToAdd, _workContext.CurrentStore.Id)+ || !productToAdd.IsAvailable())+ continue;++ //add a product to result+ result.Add(productToAdd);+ if (result.Count >= numberOfProducts)+ return result;}}return result;@@ -931,7 +927,8 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Inserts a recommended product/// </summary>- /// <param name="recommendedProduct">Recommended product</param>+ /// <param name="productId">Product ident</param>+ /// <param name="recommendedProductId">Recommended product</param>public virtual async Task InsertRecommendedProduct(string productId, string recommendedProductId){if (productId == null)@@ -950,7 +947,8 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Deletes a recommended product/// </summary>- /// <param name="recommendedProduct">Recommended identifier</param>+ /// <param name="productId">Product ident</param>+ /// <param name="recommendedProductId">Recommended identifier</param>public virtual async Task DeleteRecommendedProduct(string productId, string recommendedProductId){if (productId == null)@@ -1051,7 +1049,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Updates the product price/// </summary>- /// <param name="tierPrice">Tier price</param>+ /// <param name="productPrice">Tier price</param>public virtual async Task UpdateProductPrice(ProductPrice productPrice){if (productPrice == null)@@ -1146,7 +1144,7 @@ namespace Grand.Business.Catalog.Services.Products#region Product warehouse inventory/// <summary>- /// Insert product warehouse inwentory+ /// Insert product warehouse inventory/// </summary>/// <param name="pwi"></param>/// <param name="productId"></param>diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.csindex 8c33c0ffe..fa0714a50 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Product tag service/// </summary>- public partial class ProductTagService : IProductTagService+ public class ProductTagService : IProductTagService{#region Fields@@ -28,6 +28,7 @@ namespace Grand.Business.Catalog.Services.Products/// Ctor/// </summary>/// <param name="productTagRepository">Product tag repository</param>+ /// <param name="productRepository">Product repository</param>/// <param name="cacheBase">Cache manager</param>/// <param name="mediator">Mediator</param>public ProductTagService(IRepository<ProductTag> productTagRepository,@@ -43,17 +44,7 @@ namespace Grand.Business.Catalog.Services.Products}#endregion-- #region Nested classes-- private class ProductTagWithCount- {- public int ProductTagId { get; set; }- public int ProductCount { get; set; }- }-- #endregion-+#region Utilities/// <summary>@@ -63,15 +54,13 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Dictionary of "product tag ID : product count"</returns>private async Task<Dictionary<string, int>> GetProductCount(string storeId){- string key = string.Format(CacheKey.PRODUCTTAG_COUNT_KEY, storeId);+ var key = string.Format(CacheKey.PRODUCTTAG_COUNT_KEY, storeId);return await _cacheBase.GetAsync(key, async () =>{var query = from pt in _productTagRepository.Tableselect pt;- var dictionary = new Dictionary<string, int>();- foreach (var item in query.ToList())- dictionary.Add(item.Id, item.Count);+ var dictionary = query.ToList().ToDictionary(item => item.Id, item => item.Count);return await Task.FromResult(dictionary);});}@@ -87,10 +76,7 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Product tags</returns>public virtual async Task<IList<ProductTag>> GetAllProductTags(){- return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_ALL_KEY, async () =>- {- return await Task.FromResult(_productTagRepository.Table.ToList());- });+ return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_ALL_KEY, async () => await Task.FromResult(_productTagRepository.Table.ToList()));}/// <summary>@@ -118,9 +104,9 @@ namespace Grand.Business.Catalog.Services.Products}/// <summary>- /// Gets product tag by sename+ /// Gets product tag by se-name/// </summary>- /// <param name="sename">Product tag sename</param>+ /// <param name="sename">Product tag se-name</param>/// <returns>Product tag</returns>public virtual Task<ProductTag> GetProductTagBySeName(string sename){@@ -157,12 +143,12 @@ namespace Grand.Business.Catalog.Services.Productsif (productTag == null)throw new ArgumentNullException(nameof(productTag));- var previouse = await GetProductTagById(productTag.Id);+ var previous = await GetProductTagById(productTag.Id);await _productTagRepository.UpdateAsync(productTag);//update on products- await _productRepository.UpdateToSet(x => x.ProductTags, previouse.Name, productTag.Name);+ await _productRepository.UpdateToSet(x => x.ProductTags, previous.Name, productTag.Name);//cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);@@ -251,10 +237,7 @@ namespace Grand.Business.Catalog.Services.Productspublic virtual async Task<int> GetProductCount(string productTagId, string storeId){var dictionary = await GetProductCount(storeId);- if (dictionary.ContainsKey(productTagId))- return dictionary[productTagId];-- return 0;+ return dictionary.ContainsKey(productTagId) ? dictionary[productTagId] : 0;}#endregiondiff --git a/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs b/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.csindex 4398a04c4..e11662d4c 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Recently viewed products service/// </summary>- public partial class RecentlyViewedProductsService : IRecentlyViewedProductsService+ public class RecentlyViewedProductsService : IRecentlyViewedProductsService{#region Fields@@ -55,14 +55,16 @@ namespace Grand.Business.Catalog.Services.Productsreturn query.ToList();}+/// <summary>/// Gets a "recently viewed products" identifier list/// </summary>+ /// <param name="customerId">Customer ident</param>/// <param name="number">Number of products to load</param>/// <returns>"recently viewed products" list</returns>protected async Task<IList<string>> GetRecentlyViewedProductsIds(string customerId, int number){- string key = string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_KEY, customerId, number);+ var key = string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_KEY, customerId, number);return await _cacheBase.GetAsync(key, async () =>{var query = from p in _recentlyViewedProducts.Table@@ -77,25 +79,22 @@ namespace Grand.Business.Catalog.Services.Products#region Methods-/// <summary>/// Gets a "recently viewed products" list/// </summary>+ /// <param name="customerId">Customer ident</param>/// <param name="number">Number of products to load</param>/// <returns>"recently viewed products" list</returns>public virtual async Task<IList<Product>> GetRecentlyViewedProducts(string customerId, int number){- var products = new List<Product>();var productIds = await GetRecentlyViewedProductsIds(customerId, number);- foreach (var product in await _productService.GetProductsByIds(productIds.ToArray()))- if (product.Published)- products.Add(product);- return products;+ return (await _productService.GetProductsByIds(productIds.ToArray())).Where(product => product.Published).ToList();}/// <summary>/// Adds a product to a recently viewed products list/// </summary>+ /// <param name="customerId">Customer ident</param>/// <param name="productId">Product identifier</param>public virtual async Task AddProductToRecentlyViewedList(string customerId, string productId){@@ -113,7 +112,7 @@ namespace Grand.Business.Catalog.Services.ProductsrecentlyViewedProduct.CreatedOnUtc = DateTime.UtcNow;await _recentlyViewedProducts.UpdateAsync(recentlyViewedProduct);}- int maxProducts = _catalogSettings.RecentlyViewedProductsNumber;+ var maxProducts = _catalogSettings.RecentlyViewedProductsNumber;if (maxProducts <= 0)maxProducts = 10;diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.csindex a499f1047..c9703d072 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Catalog.Services.Products/// <summary>/// Specification attribute service/// </summary>- public partial class SpecificationAttributeService : ISpecificationAttributeService+ public class SpecificationAttributeService : ISpecificationAttributeService{#region Fields@@ -52,14 +52,14 @@ namespace Grand.Business.Catalog.Services.Products/// <returns>Specification attribute</returns>public virtual async Task<SpecificationAttribute> GetSpecificationAttributeById(string specificationAttributeId){- string key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId);+ var key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId);return await _cacheBase.GetAsync(key, () => _specificationAttributeRepository.GetByIdAsync(specificationAttributeId));}/// <summary>- /// Gets a specification attribute by sename+ /// Gets a specification attribute by se-name/// </summary>- /// <param name="sename">Sename</param>+ /// <param name="sename">Se-name</param>/// <returns>Specification attribute</returns>public virtual async Task<SpecificationAttribute> GetSpecificationAttributeBySeName(string sename){@@ -70,8 +70,8 @@ namespace Grand.Business.Catalog.Services.Productsvar key = string.Format(CacheKey.SPECIFICATION_BY_SENAME, sename);return await _cacheBase.GetAsync(key, async () =>- await Task.FromResult(_specificationAttributeRepository.Table.Where(x => x.SeName == sename)- .FirstOrDefault()));+ await Task.FromResult(_specificationAttributeRepository.Table+ .FirstOrDefault(x => x.SeName == sename)));}@@ -161,7 +161,7 @@ namespace Grand.Business.Catalog.Services.Productsif (string.IsNullOrEmpty(specificationAttributeOptionId))return await Task.FromResult<SpecificationAttribute>(null);- string key = string.Format(CacheKey.SPECIFICATION_BY_OPTIONID_KEY, specificationAttributeOptionId);+ var key = string.Format(CacheKey.SPECIFICATION_BY_OPTIONID_KEY, specificationAttributeOptionId);return await _cacheBase.GetAsync(key, async () =>{var query = from p in _specificationAttributeRepository.Table@@ -184,7 +184,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id);var specificationAttribute = await GetSpecificationAttributeByOptionId(specificationAttributeOption.Id);- var sao = specificationAttribute.SpecificationAttributeOptions.Where(x => x.Id == specificationAttributeOption.Id).FirstOrDefault();+ var sao = specificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == specificationAttributeOption.Id);if (sao == null)throw new ArgumentException("No specification attribute option found with the specified id");diff --git a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.csindex 8e75520c0..bb4573f80 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs@@ -29,36 +29,25 @@ namespace Grand.Business.Catalog.Services.Products{if (total){- if (useReservedQuantity)- return product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity);- else- return product.ProductWarehouseInventory.Sum(x => x.StockQuantity);+ return useReservedQuantity ? product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) : product.ProductWarehouseInventory.Sum(x => x.StockQuantity);}- else++ var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);+ if (pwi == null) return 0;+ var result = pwi.StockQuantity;+ if (useReservedQuantity){- var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);- if (pwi != null)- {- var result = pwi.StockQuantity;- if (useReservedQuantity)- {- result -= pwi.ReservedQuantity;- }- return result;- }- return 0;+ result -= pwi.ReservedQuantity;}+ return result;}if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);- else- {- if (product.WarehouseId == warehouseId)- return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);- else- return 0;- }-++ if (product.WarehouseId == warehouseId)+ return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);++ return 0;}public virtual int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination,@@ -78,28 +67,22 @@ namespace Grand.Business.Catalog.Services.Productsif (product.UseMultipleWarehouses){var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);- if (pwi != null)+ if (pwi == null) return 0;+ var result = pwi.StockQuantity;+ if (useReservedQuantity){- var result = pwi.StockQuantity;- if (useReservedQuantity)- {- result -= pwi.ReservedQuantity;- }- return result;+ result -= pwi.ReservedQuantity;}- return 0;+ return result;}if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);- else- {- if (product.WarehouseId == warehouseId)- return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);- else- return 0;- }-++ if (product.WarehouseId == warehouseId)+ return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);++ return 0;}public virtual string FormatStockMessage(Product product, string warehouseId, IList<CustomAttribute> attributes)@@ -107,7 +90,7 @@ namespace Grand.Business.Catalog.Services.Productsif (product == null)throw new ArgumentNullException(nameof(product));- string stockMessage = string.Empty;+ var stockMessage = string.Empty;switch (product.ManageInventoryMethodId){diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.csindex af4313ab2..9737d84cd 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <summary>/// Tax category service/// </summary>- public partial class TaxCategoryService : ITaxCategoryService+ public class TaxCategoryService : ITaxCategoryService{#region Fields@@ -48,7 +48,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Tax categories</returns>public virtual async Task<IList<TaxCategory>> GetAllTaxCategories(){- string key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY);+ var key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY);return await _cacheBase.GetAsync(key, async () =>{var query = from tc in _taxCategoryRepository.Table@@ -65,7 +65,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Tax category</returns>public virtual Task<TaxCategory> GetTaxCategoryById(string taxCategoryId){- string key = string.Format(CacheKey.TAXCATEGORIES_BY_ID_KEY, taxCategoryId);+ var key = string.Format(CacheKey.TAXCATEGORIES_BY_ID_KEY, taxCategoryId);return _cacheBase.GetAsync(key, () => _taxCategoryRepository.GetByIdAsync(taxCategoryId));}diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.csindex a6b734488..71a6c28c9 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs@@ -18,7 +18,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <summary>/// Tax service/// </summary>- public partial class TaxService : ITaxService+ public class TaxService : ITaxService{#region Fields@@ -80,8 +80,7 @@ namespace Grand.Business.Catalog.Services.Tax//get country from billing addressif (_addressSettings.CountryEnabled && customer.BillingAddress != null){- var _country = await _countryService.GetCountryById(customer.BillingAddress.CountryId);- country = _country;+ country = await _countryService.GetCountryById(customer.BillingAddress.CountryId);}//get country specified during registration?if (country == null && _customerSettings.CountryEnabled)@@ -99,20 +98,12 @@ namespace Grand.Business.Catalog.Services.Tax}//we cannot detect country- if (country == null)+ if (country is not { SubjectToVat: true })return false;-- //outside EU- if (!country.SubjectToVat)- return false;-+//company (business) or consumer?var customerVatStatus = (VatNumberStatus)customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId);- if (customerVatStatus == VatNumberStatus.Valid)- return false;-- //consumer- return true;+ return customerVatStatus != VatNumberStatus.Valid;}/// <summary>@@ -121,6 +112,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="product">Product</param>/// <param name="taxCategoryId">Tax category identifier</param>/// <param name="customer">Customer</param>+ /// <param name="price">Price</param>/// <returns>Package for tax calculation</returns>protected virtual async Task<TaxRequest> CreateCalculateTaxRequest(Product product,string taxCategoryId, Customer customer, double price)@@ -128,10 +120,11 @@ namespace Grand.Business.Catalog.Services.Taxif (customer == null)throw new ArgumentNullException(nameof(customer));- var calculateTaxRequest = new TaxRequest();- calculateTaxRequest.Customer = customer;- calculateTaxRequest.Product = product;- calculateTaxRequest.Price = price;+ var calculateTaxRequest = new TaxRequest {+ Customer = customer,+ Product = product,+ Price = price+ };if (!string.IsNullOrEmpty(taxCategoryId)){@@ -146,7 +139,7 @@ namespace Grand.Business.Catalog.Services.Taxif (_taxSettings.EuVatEnabled){//telecommunications, broadcasting and electronic services?- if (product != null && product.IsTele)+ if (product is { IsTele: true }){//Europe Union consumer?if (await IsEuConsumer(customer))@@ -214,18 +207,16 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="taxCategoryId">Tax category identifier</param>/// <param name="customer">Customer</param>/// <param name="price">Price (taxable value)</param>- /// <param name="taxRate">Calculated tax rate</param>- /// <param name="isTaxable">A value indicating whether a request is taxable</param>protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId,Customer customer, double price){double taxRate = 0;- bool isTaxable = true;+ var isTaxable = true;//active tax providervar activeTaxProvider = LoadActiveTaxProvider();if (activeTaxProvider == null)- return (taxRate, isTaxable);+ return (taxRate, true);//tax requestvar calculateTaxRequest = await CreateCalculateTaxRequest(product, taxCategoryId, customer, price);@@ -258,7 +249,7 @@ namespace Grand.Business.Catalog.Services.Tax{foreach (var error in calculateTaxResult.Errors){- _ = _logger.Error(string.Format("{0} - {1}", activeTaxProvider.FriendlyName, error), null, customer);+ _ = _logger.Error($"{activeTaxProvider.FriendlyName} - {error}", null, customer);}}return (taxRate, isTaxable);@@ -275,9 +266,8 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Active tax provider</returns>public virtual ITaxProvider LoadActiveTaxProvider(){- var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName);- if (taxProvider == null)- taxProvider = LoadAllTaxProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id).FirstOrDefault();+ var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName) ??+ LoadAllTaxProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id).FirstOrDefault();return taxProvider;}@@ -313,7 +303,6 @@ namespace Grand.Business.Catalog.Services.Tax/// </summary>/// <param name="product">Product</param>/// <param name="price">Price</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price){@@ -327,12 +316,11 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="product">Product</param>/// <param name="price">Price</param>/// <param name="customer">Customer</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,Customer customer){- bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetProductPrice(product, price, includingTax, customer);}@@ -343,14 +331,12 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,bool includingTax, Customer customer){- bool priceIncludesTax = _taxSettings.PricesIncludeTax;- string taxCategoryId = "";- return await GetProductPrice(product, taxCategoryId, price, includingTax,+ var priceIncludesTax = _taxSettings.PricesIncludeTax;+ return await GetProductPrice(product, string.Empty, price, includingTax,customer, priceIncludesTax);}@@ -363,7 +349,6 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>/// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, string taxCategoryId,double price, bool includingTax, Customer customer,@@ -428,7 +413,7 @@ namespace Grand.Business.Catalog.Services.TaxProduct product,Customer customer,double unitPrice,- double unitPricewithoutDisc,+ double unitPriceWithoutDisc,int quantity,double subTotal,double discountAmount,@@ -439,7 +424,7 @@ namespace Grand.Business.Catalog.Services.Taxvar productPrice = new TaxProductPrice{- taxRate = taxrates.taxRate,+ TaxRate = taxrates.taxRate,Quantity = quantity};@@ -447,8 +432,8 @@ namespace Grand.Business.Catalog.Services.Tax{if (taxrates.isTaxable){- productPrice.UnitPriceWihoutDiscInclTax = unitPricewithoutDisc;- productPrice.UnitPriceWihoutDiscExclTax = CalculatePrice(unitPricewithoutDisc, taxrates.taxRate, false);+ productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;+ productPrice.UnitPriceWithoutDiscExclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);productPrice.UnitPriceInclTax = unitPrice;productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);@@ -456,13 +441,13 @@ namespace Grand.Business.Catalog.Services.TaxproductPrice.SubTotalInclTax = subTotal;productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);- productPrice.discountAmountInclTax = discountAmount;- productPrice.discountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);+ productPrice.DiscountAmountInclTax = discountAmount;+ productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);}else{- productPrice.UnitPriceWihoutDiscInclTax = CalculatePrice(unitPricewithoutDisc, taxrates.taxRate, false);- productPrice.UnitPriceWihoutDiscExclTax = CalculatePrice(unitPricewithoutDisc, taxrates.taxRate, false);+ productPrice.UnitPriceWithoutDiscInclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);+ productPrice.UnitPriceWithoutDiscExclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);@@ -470,16 +455,16 @@ namespace Grand.Business.Catalog.Services.TaxproductPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, false);productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);- productPrice.discountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);- productPrice.discountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);+ productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);+ productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);}}else{if (taxrates.isTaxable){- productPrice.UnitPriceWihoutDiscInclTax = CalculatePrice(unitPricewithoutDisc, taxrates.taxRate, true);- productPrice.UnitPriceWihoutDiscExclTax = unitPricewithoutDisc;+ productPrice.UnitPriceWithoutDiscInclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, true);+ productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, true);productPrice.UnitPriceExclTax = unitPrice;@@ -487,13 +472,13 @@ namespace Grand.Business.Catalog.Services.TaxproductPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, true);productPrice.SubTotalExclTax = subTotal;- productPrice.discountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, true);- productPrice.discountAmountExclTax = discountAmount;+ productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, true);+ productPrice.DiscountAmountExclTax = discountAmount;}else{- productPrice.UnitPriceWihoutDiscInclTax = unitPricewithoutDisc;- productPrice.UnitPriceWihoutDiscExclTax = unitPricewithoutDisc;+ productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;+ productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;productPrice.UnitPriceInclTax = unitPrice;productPrice.UnitPriceExclTax = unitPrice;@@ -501,8 +486,8 @@ namespace Grand.Business.Catalog.Services.TaxproductPrice.SubTotalInclTax = subTotal;productPrice.SubTotalExclTax = subTotal;- productPrice.discountAmountInclTax = discountAmount;- productPrice.discountAmountExclTax = discountAmount;+ productPrice.DiscountAmountInclTax = discountAmount;+ productPrice.DiscountAmountExclTax = discountAmount;}}@@ -522,7 +507,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Price</returns>public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer){- bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetShippingPrice(price, includingTax, customer);}@@ -532,7 +517,6 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax, Customer customer){@@ -541,8 +525,8 @@ namespace Grand.Business.Catalog.Services.Taxreturn (price, 0);}- string taxCategoryId = _taxSettings.ShippingTaxCategoryId;- bool priceIncludesTax = _taxSettings.ShippingPriceIncludesTax;+ var taxCategoryId = _taxSettings.ShippingTaxCategoryId;+ var priceIncludesTax = _taxSettings.ShippingPriceIncludesTax;var prices = await GetProductPrice(null, taxCategoryId, price, includingTax, customer,priceIncludesTax);return (prices.productprice, prices.taxRate);@@ -556,7 +540,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Price</returns>public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, Customer customer){- bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetPaymentMethodAdditionalFee(price, includingTax, customer);}@@ -566,7 +550,6 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, bool includingTax, Customer customer){@@ -574,8 +557,8 @@ namespace Grand.Business.Catalog.Services.Tax{return (price, 0);}- string taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxCategoryId;- bool priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax;+ var taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxCategoryId;+ var priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax;var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,priceIncludesTax);return (prices.productprice, prices.taxRate);@@ -602,7 +585,7 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>Price</returns>public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, Customer customer){- bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetCheckoutAttributePrice(ca, cav, includingTax, customer);}@@ -613,7 +596,6 @@ namespace Grand.Business.Catalog.Services.Tax/// <param name="cav">Checkout attribute value</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, bool includingTax, Customer customer){@@ -623,14 +605,14 @@ namespace Grand.Business.Catalog.Services.Taxif (cav == null)throw new ArgumentNullException(nameof(cav));- double price = cav.PriceAdjustment;+ var price = cav.PriceAdjustment;if (ca.IsTaxExempt){return (price, 0);}- bool priceIncludesTax = _taxSettings.PricesIncludeTax;- string taxClassId = ca.TaxCategoryId;+ var priceIncludesTax = _taxSettings.PricesIncludeTax;+ var taxClassId = ca.TaxCategoryId;var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,priceIncludesTax);@@ -647,27 +629,15 @@ namespace Grand.Business.Catalog.Services.Tax/// <returns>A value indicating whether a product is tax exempt</returns>public virtual async Task<bool> IsTaxExempt(Product product, Customer customer){- if (customer != null)- {- if (customer.IsTaxExempt)- return true;-- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());- if (customerGroups.Any(cr => cr.TaxExempt))- return true;- }-- if (product == null)- {- return false;- }+ if (customer == null) return product is { IsTaxExempt: true };+ if (customer.IsTaxExempt)+ return true;- if (product.IsTaxExempt)- {+ var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());+ if (customerGroups.Any(cr => cr.TaxExempt))return true;- }- return false;+ return product is { IsTaxExempt: true };}/// <summary>@@ -681,7 +651,7 @@ namespace Grand.Business.Catalog.Services.Taxif (!_taxSettings.EuVatEnabled)return false;- if (address == null || String.IsNullOrEmpty(address.CountryId) || customer == null)+ if (address == null || string.IsNullOrEmpty(address.CountryId) || customer == null)return false;var country = await _countryService.GetCountryById(address.CountryId);diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.csindex ab53f5046..b371f77b7 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs@@ -18,15 +18,13 @@ namespace Grand.Business.Catalog.Services.Tax/// Gets VAT Number status/// </summary>/// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param>- /// <param name="name">Name (if received)</param>- /// <param name="address">Address (if received)</param>/// <returns>VAT Number status</returns>public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus(string fullVatNumber){- string name = string.Empty;- string address = string.Empty;+ var name = string.Empty;+ var address = string.Empty;- if (String.IsNullOrWhiteSpace(fullVatNumber))+ if (string.IsNullOrWhiteSpace(fullVatNumber))return (VatNumberStatus.Empty, name, address, null);fullVatNumber = fullVatNumber.Trim();@@ -49,13 +47,11 @@ namespace Grand.Business.Catalog.Services.Tax/// </summary>/// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>/// <param name="vatNumber">VAT number</param>- /// <param name="name">Name (if received)</param>- /// <param name="address">Address (if received)</param>/// <returns>VAT Number status</returns>public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus(string twoLetterIsoCode, string vatNumber){- string name = string.Empty;- string address = string.Empty;+ var name = string.Empty;+ var address = string.Empty;if (string.IsNullOrEmpty(twoLetterIsoCode))return (VatNumberStatus.Empty, name, address, null);@@ -77,35 +73,27 @@ namespace Grand.Business.Catalog.Services.Tax/// </summary>/// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>/// <param name="vatNumber">VAT number</param>- /// <param name="name">Company name</param>- /// <param name="address">Address</param>- /// <param name="exception">Exception</param>/// <returns>VAT number status</returns>public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)>DoVatCheck(string twoLetterIsoCode, string vatNumber){- var name = string.Empty;- var address = string.Empty;-- if (vatNumber == null)- vatNumber = string.Empty;+ vatNumber ??= string.Empty;vatNumber = vatNumber.Trim().Replace(" ", "");- if (twoLetterIsoCode == null)- twoLetterIsoCode = string.Empty;- if (!String.IsNullOrEmpty(twoLetterIsoCode))+ twoLetterIsoCode ??= string.Empty;+ if (!string.IsNullOrEmpty(twoLetterIsoCode))//The service returns INVALID_INPUT for country codes that are not uppercase.twoLetterIsoCode = twoLetterIsoCode.ToUpper();try{- var result = await CheckVatRequest(new VatRequest() {+ var result = await CheckVatRequest(new VatRequest {CountryCode = twoLetterIsoCode,VatNumber = vatNumber});var valid = result.Valid;- name = result.Name;- address = result.Address;+ var name = result.Name;+ var address = result.Address;return (valid ? VatNumberStatus.Valid : VatNumberStatus.Invalid, name, address, null);}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.csindex 32bcaf426..048f9966e 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs@@ -43,9 +43,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (!string.IsNullOrEmpty(gc.RecipientEmail) &&!string.IsNullOrEmpty(gc.SenderEmail)){- var customerLang = await _languageService.GetLanguageById(request.Order.CustomerLanguageId);- if (customerLang == null)- customerLang = (await _languageService.GetAllLanguages()).FirstOrDefault();+ var customerLang = await _languageService.GetLanguageById(request.Order.CustomerLanguageId) ??+ (await _languageService.GetAllLanguages()).FirstOrDefault();if (customerLang == null)throw new Exception("No languages could be loaded");_ = await _messageProviderService.SendGiftVoucherMessage(gc, request.Order, customerLang.Id);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.csindex afaba8a79..19eff12f2 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs@@ -22,7 +22,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar reserved = await _productReservationService.GetCustomerReservationsHelpers(request.Customer.Id);foreach (var item in reserved){- var match = reservations.Where(x => x.Id == item.ReservationId).FirstOrDefault();+ var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);if (match != null){reservations.Remove(match);@@ -34,34 +34,29 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar grouped = reservations.GroupBy(x => x.Resource);foreach (var group in grouped){- bool groupCanBeBooked = true;+ var groupCanBeBooked = true;if (request.Product.IncBothDate && request.Product.IntervalUnitId == IntervalUnit.Day){for (DateTime iterator = request.RentalStartDate.Value; iterator <= request.RentalEndDate.Value; iterator += new TimeSpan(24, 0, 0)){- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}}else{for (DateTime iterator = request.RentalStartDate.Value; iterator < request.RentalEndDate.Value; iterator += new TimeSpan(24, 0, 0)){- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}}- if (groupCanBeBooked)- {- groupToBook = group;- break;- }++ if (!groupCanBeBooked) continue;+ groupToBook = group;+ break;}if (groupToBook != null)@@ -91,7 +86,6 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}}-if (!string.IsNullOrEmpty(request.ReservationId)){await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.csindex 36064e8c6..39e2f6140 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs@@ -33,9 +33,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId).ToList();- var warnings = new List<string>();-- if (product.RequireOtherProducts)+ if (!product.RequireOtherProducts) return true;{var requiredProducts = new List<Product>();foreach (var id in product.ParseRequiredProductIds())@@ -48,38 +46,25 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersforeach (var rp in requiredProducts){//ensure that product is in the cart- bool alreadyInTheCart = false;- foreach (var sci in cart)- {- if (sci.ProductId == rp.Id)- {- alreadyInTheCart = true;- break;- }- }+ var alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id);//not in the cart- if (!alreadyInTheCart)- {-- if (product.AutoAddRequiredProducts)- {- var addToCart = await _shoppingCartService.AddToCart(customer: customer,- productId: rp.Id,- shoppingCartType: shoppingCartType,- storeId: storeId,- automaticallyAddRequiredProductsIfEnabled: false,- validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false });+ if (alreadyInTheCart) continue;+ if (!product.AutoAddRequiredProducts) continue;+ var addToCart = await _shoppingCartService.AddToCart(customer: customer,+ productId: rp.Id,+ shoppingCartType: shoppingCartType,+ storeId: storeId,+ automaticallyAddRequiredProductsIfEnabled: false,+ validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false });- if (rp.RequireOtherProducts && addToCart.warnings.Count == 0)- {- await Handle(new AddRequiredProductsCommand {- Customer = customer,- ShoppingCartType = shoppingCartType,- StoreId = storeId,- Product = rp- }, cancellationToken);- }- }+ if (rp.RequireOtherProducts && addToCart.warnings.Count == 0)+ {+ await Handle(new AddRequiredProductsCommand {+ Customer = customer,+ ShoppingCartType = shoppingCartType,+ StoreId = storeId,+ Product = rp+ }, cancellationToken);}}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.csindex 797f21943..14d78850b 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs@@ -40,7 +40,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar customer = await _customerService.GetCustomerById(request.Order.CustomerId);var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);var amount = await _currencyService.ConvertToPrimaryStoreCurrency(request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);- var points = await _mediator.Send(new CalculateLoyaltyPointsCommand() { Customer = customer, Amount = amount });+ var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount }, cancellationToken);if (points <= 0)return false;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.csindex 061cb16b1..af5911e6f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs@@ -60,13 +60,13 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersthrow new Exception("Cannot do cancel for order with shipments");//Cancel order- await _mediator.Send(new SetOrderStatusCommand()+ await _mediator.Send(new SetOrderStatusCommand{Order = request.Order,Os = OrderStatusSystem.Cancelled,NotifyCustomer = request.NotifyCustomer,NotifyStoreOwner = request.NotifyStoreOwner- });+ }, cancellationToken);//add a noteawait _orderService.InsertOrderNote(new OrderNote@@ -74,12 +74,12 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = "Order has been cancelled",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});- //return (add) back redeemded loyalty points- await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand() { Order = request.Order });+ //return (add) back redeemed loyalty points+ await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order }, cancellationToken);//Adjust inventoryforeach (var orderItem in request.Order.OrderItems)@@ -105,12 +105,12 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _discountService.CancelDiscount(request.Order.Id);//cancel payments- var payment = await _paymentTransactionService.GetByOrdeGuid(request.Order.OrderGuid);+ var payment = await _paymentTransactionService.GetOrderByGuid(request.Order.OrderGuid);if (payment != null)await _paymentService.CancelPayment(payment);//event notification- await _mediator.Publish(new OrderCancelledEvent(request.Order));+ await _mediator.Publish(new OrderCancelledEvent(request.Order), cancellationToken);return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.csindex 238037bca..9f5b54917 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs@@ -56,7 +56,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = $"Order item has been canceled - {product.Name} - Qty: {request.OrderItem.OpenQty}",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});await _inventoryManageService.AdjustReserved(product, request.OrderItem.OpenQty, request.OrderItem.Attributes, request.OrderItem.WarehouseId);@@ -69,11 +69,11 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped){var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- if (!request.Order.HasItemsToAddToShipment() && !shipments.Where(x => x.ShippedDateUtc == null).Any())+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.ShippedDateUtc != null)){request.Order.ShippingStatusId = ShippingStatus.Shipped;}- if (!request.Order.HasItemsToAddToShipment() && !shipments.Where(x => x.DeliveryDateUtc == null).Any())+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null)){request.Order.ShippingStatusId = ShippingStatus.Delivered;}@@ -82,7 +82,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(request.Order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = request.Order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);return (false, "");}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.csindex a387b54f2..464732fc5 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs@@ -40,7 +40,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(command.PaymentTransaction));- var canCapture = await _mediator.Send(new CanCaptureQuery() { PaymentTransaction = paymentTransaction });+ var canCapture = await _mediator.Send(new CanCaptureQuery { PaymentTransaction = paymentTransaction }, cancellationToken);if (!canCapture)throw new GrandException("Cannot do capture for order.");@@ -69,31 +69,30 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersorder.PaymentStatusId = PaymentStatus.Paid;order.PaidDateUtc = DateTime.UtcNow;await _orderService.UpdateOrder(order);- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);if (order.PaymentStatusId == PaymentStatus.Paid){- await _mediator.Send(new ProcessOrderPaidCommand() { Order = order });+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);}}}}catch (Exception exc){- if (result == null)- result = new CapturePaymentResult();- result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc));+ result ??= new CapturePaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");}//process errors- string error = "";- for (int i = 0; i < result.Errors.Count; i++)+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++){- error += string.Format("Error {0}: {1}", i, result.Errors[i]);+ error += $"Error {i}: {result.Errors[i]}";if (i != result.Errors.Count - 1)error += ". ";}- if (!String.IsNullOrEmpty(error))+ if (!string.IsNullOrEmpty(error)){//log itawait _logger.InsertLog(LogLevel.Error, $"Error capturing order code # {paymentTransaction.OrderCode}. Error: {error}", $"Error capturing order code # {paymentTransaction.OrderCode}. Error: {error}");diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.csindex fc0d1b705..040578a21 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs@@ -37,10 +37,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (request.Order.OrderStatusId == (int)OrderStatusSystem.Pending){- if (request.Order.PaymentStatusId == PaymentStatus.Authorized ||- request.Order.PaymentStatusId == PaymentStatus.Paid ||- request.Order.PaymentStatusId == PaymentStatus.PartiallyPaid- )+ if (request.Order.PaymentStatusId is PaymentStatus.Authorized or PaymentStatus.Paid or PaymentStatus.PartiallyPaid){await _mediator.Send(new SetOrderStatusCommand{@@ -48,12 +45,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersOs = OrderStatusSystem.Processing,NotifyCustomer = false,NotifyStoreOwner = false- });+ }, cancellationToken);}- if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped ||- request.Order.ShippingStatusId == ShippingStatus.Shipped ||- request.Order.ShippingStatusId == ShippingStatus.Delivered)+ if (request.Order.ShippingStatusId is ShippingStatus.PartiallyShipped or ShippingStatus.Shipped or ShippingStatus.Delivered){await _mediator.Send(new SetOrderStatusCommand{@@ -61,43 +56,37 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersOs = OrderStatusSystem.Processing,NotifyCustomer = false,NotifyStoreOwner = false- });+ }, cancellationToken);}}- if (request.Order.OrderStatusId != (int)OrderStatusSystem.Cancelled &&- request.Order.OrderStatusId != (int)OrderStatusSystem.Complete)+ if (request.Order.OrderStatusId is (int)OrderStatusSystem.Cancelled or (int)OrderStatusSystem.Complete) return true;+ if (request.Order.PaymentStatusId != PaymentStatus.Paid) return true;+ bool completed;+ if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired){- if (request.Order.PaymentStatusId == PaymentStatus.Paid)+ completed = true;+ }+ else+ {+ if (_orderSettings.CompleteOrderWhenDelivered){- bool completed;- if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired)- {- completed = true;- }- else- {- if (_orderSettings.CompleteOrderWhenDelivered)- {- completed = request.Order.ShippingStatusId == ShippingStatus.Delivered;- }- else- {- completed = request.Order.ShippingStatusId == ShippingStatus.Shipped ||- request.Order.ShippingStatusId == ShippingStatus.Delivered;- }- }- if (completed)- {- await _mediator.Send(new SetOrderStatusCommand- {- Order = request.Order,- Os = OrderStatusSystem.Complete,- NotifyCustomer = true,- NotifyStoreOwner = false- });- }+ completed = request.Order.ShippingStatusId == ShippingStatus.Delivered;}+ else+ {+ completed = request.Order.ShippingStatusId is ShippingStatus.Shipped or ShippingStatus.Delivered;+ }+ }+ if (completed)+ {+ await _mediator.Send(new SetOrderStatusCommand+ {+ Order = request.Order,+ Os = OrderStatusSystem.Complete,+ NotifyCustomer = true,+ NotifyStoreOwner = false+ }, cancellationToken);}return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.csindex a10aa094e..93343327a 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs@@ -55,11 +55,11 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//check whether the order wasn't cancelled beforeif (request.Order.OrderStatusId != (int)OrderStatusSystem.Cancelled){- //return (add) back redeemded loyalty points- await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand() { Order = request.Order });+ //return (add) back redeemed loyalty points+ await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order }, cancellationToken);//reduce (cancel) back loyalty points (previously awarded for this order)- await _mediator.Send(new ReduceLoyaltyPointsCommand() { Order = request.Order });+ await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);//Adjust inventoryforeach (var orderItem in request.Order.OrderItems)@@ -78,7 +78,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//deactivate gift vouchersif (_orderSettings.DeactivateGiftVouchersAfterDeletingOrder)- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand() { Order = request.Order, Activate = false });+ await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false }, cancellationToken);request.Order.Deleted = true;//now delete an order@@ -90,14 +90,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//add a noteawait _orderService.InsertOrderNote(new OrderNote{- Note = $"Order has been deleted",+ Note = "Order has been deleted",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});//event notification- await _mediator.Publish(new OrderDeletedEvent(request.Order));+ await _mediator.Publish(new OrderDeletedEvent(request.Order), cancellationToken);return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.csindex 79ed9330c..40e23d1fe 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs@@ -58,10 +58,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn (true, "You can't cancel gift voucher, please delete it.");}- var shipments = (await _shipmentService.GetShipmentsByOrder(request.Order.Id));+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);foreach (var shipment in shipments){- if (shipment.ShipmentItems.Where(x => x.OrderItemId == request.OrderItem.Id).Any())+ if (shipment.ShipmentItems.Any(x => x.OrderItemId == request.OrderItem.Id)){return (true, $"This order item is in associated with shipment {shipment.ShipmentNumber}. Please delete it first.");}@@ -78,7 +78,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = $"Order item has been deleted - {product.Name}",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});await _inventoryManageService.AdjustReserved(product, request.OrderItem.Quantity, request.OrderItem.Attributes, request.OrderItem.WarehouseId);@@ -90,12 +90,12 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersrequest.Order.OrderSubtotalExclTax -= request.OrderItem.PriceExclTax;request.Order.OrderSubtotalInclTax -= request.OrderItem.PriceInclTax;- request.Order.OrderTax -= (request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax);+ request.Order.OrderTax -= request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;request.Order.OrderTotal -= request.OrderItem.PriceInclTax;if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped){- if (!request.Order.HasItemsToAddToShipment() && !shipments.Where(x => x.DeliveryDateUtc == null).Any())+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null)){request.Order.ShippingStatusId = ShippingStatus.Delivered;}@@ -106,7 +106,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(request.Order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = request.Order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);return (false, "");}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.csindex 42c5247f8..281194a6e 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs@@ -38,7 +38,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersrequest.Order.OrderItems.Add(request.OrderItem);request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax;request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax;- request.Order.OrderTax += (request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax);+ request.Order.OrderTax += request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;request.Order.OrderTotal += request.OrderItem.PriceInclTax;if (request.Order.ShippingStatusId == ShippingStatus.Delivered@@ -62,7 +62,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _inventoryManageService.AdjustReserved(request.Product, -request.OrderItem.Quantity, request.OrderItem.Attributes, request.OrderItem.WarehouseId);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = request.Order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);//add a noteawait _orderService.InsertOrderNote(new OrderNote@@ -70,34 +70,32 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = "A new order item has been added",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});//gift vouchers- if (request.Product.IsGiftVoucher)+ if (!request.Product.IsGiftVoucher) return true;+ for (var i = 0; i < request.OrderItem.Quantity; i++){- for (int i = 0; i < request.OrderItem.Quantity; i++)+ var gc = new GiftVoucher{- var gc = new GiftVoucher- {- GiftVoucherTypeId = request.Product.GiftVoucherTypeId,- PurchasedWithOrderItem = request.OrderItem,- Amount = request.OrderItem.UnitPriceExclTax,- CurrencyCode = request.Order.CustomerCurrencyCode,- IsGiftVoucherActivated = false,- Code = _giftVoucherService.GenerateGiftVoucherCode(),+ GiftVoucherTypeId = request.Product.GiftVoucherTypeId,+ PurchasedWithOrderItem = request.OrderItem,+ Amount = request.OrderItem.UnitPriceExclTax,+ CurrencyCode = request.Order.CustomerCurrencyCode,+ IsGiftVoucherActivated = false,+ Code = _giftVoucherService.GenerateGiftVoucherCode(),- //TODO- //RecipientName = recipientName,- //RecipientEmail = recipientEmail,- //SenderName = senderName,- //SenderEmail = senderEmail,- //Message = giftVoucherMessage,- IsRecipientNotified = false,- CreatedOnUtc = DateTime.UtcNow- };- await _giftVoucherService.InsertGiftVoucher(gc);- }+ //TODO+ //RecipientName = recipientName,+ //RecipientEmail = recipientEmail,+ //SenderName = senderName,+ //SenderEmail = senderEmail,+ //Message = giftVoucherMessage,+ IsRecipientNotified = false,+ CreatedOnUtc = DateTime.UtcNow+ };+ await _giftVoucherService.InsertGiftVoucher(gc);}return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.csindex d4eff6458..e3b1abb09 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs@@ -40,10 +40,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(order);//event notification- await _mediator.Publish(new PaymentTransactionMarkAsAuthorizedEvent(paymentTransaction));+ await _mediator.Publish(new PaymentTransactionMarkAsAuthorizedEvent(paymentTransaction), cancellationToken);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.csindex 83ef00b3f..4d5f956b6 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs@@ -31,7 +31,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- var canMarkOrderAsPaid = await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery() { PaymentTransaction = paymentTransaction });+ var canMarkOrderAsPaid = await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }, cancellationToken);if (!canMarkOrderAsPaid)throw new GrandException("You can't mark this Payment Transaction as paid");@@ -54,14 +54,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = "Order has been marked as paid",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = order.Id,+ OrderId = order.Id});- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);if (order.PaymentStatusId == PaymentStatus.Paid){- await _mediator.Send(new ProcessOrderPaidCommand() { Order = order });+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);}return true;}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.csindex 98ce3667b..a2f077e8f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs@@ -21,14 +21,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn null;var max = count > 0 ? _orderRepository.Table.Max(x => x.OrderNumber) : 0;- if (request.OrderNumber.HasValue)- {- if (request.OrderNumber.Value > max)- {- await _orderRepository.InsertAsync(new Order() { OrderNumber = request.OrderNumber.Value, Deleted = true, CreatedOnUtc = DateTime.UtcNow });- max = request.OrderNumber.Value;- }- }+ if (!request.OrderNumber.HasValue) return max;+ if (request.OrderNumber.Value <= max) return max;+ await _orderRepository.InsertAsync(new Order() { OrderNumber = request.OrderNumber.Value, Deleted = true, CreatedOnUtc = DateTime.UtcNow });+ max = request.OrderNumber.Value;return max;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.csindex 19abf22d1..3d4a6faba 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs@@ -44,7 +44,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (request.Order == null)throw new ArgumentNullException(nameof(request.Order));- int prevOrderStatus = request.Order.OrderStatusId;+ var prevOrderStatus = request.Order.OrderStatusId;if (prevOrderStatus == (int)request.Os)return false;@@ -54,7 +54,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//order notes, notificationsawait _orderService.InsertOrderNote(new OrderNote {- Note = string.Format("Order status has been changed to {0}", request.Os.ToString()),+ Note = $"Order status has been changed to {request.Os.ToString()}",DisplayToCustomer = false,OrderId = request.Order.Id,CreatedOnUtc = DateTime.UtcNow@@ -104,7 +104,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersNote = "\"Order cancelled\" by customer.",DisplayToCustomer = true,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});}//notification for vendor@@ -114,46 +114,42 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//loyalty pointsif (_loyaltyPointsSettings.PointsForPurchases_Awarded == request.Order.OrderStatusId){- await _mediator.Send(new AwardLoyaltyPointsCommand() { Order = request.Order });+ await _mediator.Send(new AwardLoyaltyPointsCommand { Order = request.Order }, cancellationToken);}if (_loyaltyPointsSettings.ReduceLoyaltyPointsAfterCancelOrder && request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled){- await _mediator.Send(new ReduceLoyaltyPointsCommand() { Order = request.Order });+ await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);}//gift vouchers activationif (_orderSettings.GiftVouchers_Activated_OrderStatusId > 0 &&- _orderSettings.GiftVouchers_Activated_OrderStatusId == (int)request.Order.OrderStatusId)+ _orderSettings.GiftVouchers_Activated_OrderStatusId == request.Order.OrderStatusId){- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand() { Order = request.Order, Activate = true });+ await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = true }, cancellationToken);}//gift vouchers deactivationif (_orderSettings.DeactivateGiftVouchersAfterCancelOrder &&request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled){- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand() { Order = request.Order, Activate = false });+ await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false }, cancellationToken);}return true;}- private async Task<bool> VendorNotification(Order order)+ private async Task VendorNotification(Order order){//notification for vendorforeach (var orderItem in order.OrderItems){- if (!string.IsNullOrEmpty(orderItem.VendorId))+ if (string.IsNullOrEmpty(orderItem.VendorId)) continue;+ var vendor = await _vendorService.GetVendorById(orderItem.VendorId);+ if (vendor is { Deleted: false, Active: true }){- var vendor = await _vendorService.GetVendorById(orderItem.VendorId);- if (vendor != null && !vendor.Deleted && vendor.Active)- {- await _messageProviderService.SendOrderCancelledVendorMessage(order, vendor, order.CustomerLanguageId);- }+ await _messageProviderService.SendOrderCancelledVendorMessage(order, vendor, order.CustomerLanguageId);}}-- return true;}}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.csindex 301b5d060..da85c5cd1 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs@@ -33,7 +33,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar amountToPaid = command.AmountToPaid;- var canPartiallyPaidOffline = await _mediator.Send(new CanPartiallyPaidOfflineQuery() { PaymentTransaction = paymentTransaction, AmountToPaid = amountToPaid });+ var canPartiallyPaidOffline = await _mediator.Send(new CanPartiallyPaidOfflineQuery { PaymentTransaction = paymentTransaction, AmountToPaid = amountToPaid }, cancellationToken);if (!canPartiallyPaidOffline)throw new GrandException("You can't partially paid (offline) this transaction");@@ -51,11 +51,11 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);if (order.PaymentStatusId == PaymentStatus.Paid){- await _mediator.Send(new ProcessOrderPaidCommand() { Order = order });+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);}return true;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.csindex 24e7b7017..5f57783c7 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs@@ -49,7 +49,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar amountToRefund = command.AmountToRefund;- var canPartiallyRefund = await _mediator.Send(new CanPartiallyRefundQuery() { AmountToRefund = amountToRefund, PaymentTransaction = paymentTransaction });+ var canPartiallyRefund = await _mediator.Send(new CanPartiallyRefundQuery { AmountToRefund = amountToRefund, PaymentTransaction = paymentTransaction }, cancellationToken);if (!canPartiallyRefund)throw new GrandException("Cannot do partial refund for order.");@@ -77,14 +77,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//total amount refundedif (paymentTransaction.TransactionStatus == Domain.Payments.TransactionStatus.Refunded){- double totalAmountRefunded = order.RefundedAmount + amountToRefund;+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;order.RefundedAmount = totalAmountRefunded;order.PaymentStatusId = order.RefundedAmount == order.OrderTotal ? Domain.Payments.PaymentStatus.Refunded : Domain.Payments.PaymentStatus.PartiallyRefunded;await _orderService.UpdateOrder(order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);//notificationsawait _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);@@ -93,30 +93,27 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}//raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund));+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);}}catch (Exception exc){- if (result == null)- result = new RefundPaymentResult();- result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc.ToString()));+ result ??= new RefundPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");}//process errors- string error = "";- for (int i = 0; i < result.Errors.Count; i++)+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++){- error += string.Format("Error {0}: {1}", i, result.Errors[i]);+ error += $"Error {i}: {result.Errors[i]}";if (i != result.Errors.Count - 1)error += ". ";}- if (!String.IsNullOrEmpty(error))- {- string logError = string.Format("Error refunding order #{0}. Error: {1}", paymentTransaction.OrderCode, error);- await _logger.InsertLog(LogLevel.Error, logError, logError);- }+ if (string.IsNullOrEmpty(error)) return result.Errors;+ var logError = $"Error refunding order #{paymentTransaction.OrderCode}. Error: {error}";+ await _logger.InsertLog(LogLevel.Error, logError, logError);return result.Errors;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.csindex 91bde6622..4f17920b7 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs@@ -42,7 +42,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar amountToRefund = command.AmountToRefund;- var canPartiallyRefundOffline = await _mediator.Send(new CanPartiallyRefundOfflineQuery() { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund });+ var canPartiallyRefundOffline = await _mediator.Send(new CanPartiallyRefundOfflineQuery { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund }, cancellationToken);if (!canPartiallyRefundOffline)throw new GrandException("You can't partially refund (offline) this order");@@ -55,7 +55,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersthrow new ArgumentNullException(nameof(order));//total amount refunded- double totalAmountRefunded = order.RefundedAmount + amountToRefund;+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;//update order infoorder.RefundedAmount = totalAmountRefunded;@@ -64,7 +64,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);//notifications_ = await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);@@ -72,7 +72,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders_ = await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);//raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund));+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);return true;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.csindex a6bb66782..fa1a5d9ef 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs@@ -187,17 +187,17 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders#region Events & notes- _ = Task.Run(() => SendNotification(_serviceScopeFactory, result.PlacedOrder, _workContext.CurrentCustomer, _workContext.OriginalCustomerIfImpersonated));+ _ = Task.Run(() => SendNotification(_serviceScopeFactory, result.PlacedOrder, _workContext.CurrentCustomer, _workContext.OriginalCustomerIfImpersonated), cancellationToken);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = result.PlacedOrder });+ await _mediator.Send(new CheckOrderStatusCommand { Order = result.PlacedOrder }, cancellationToken);//raise event- await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder));+ await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder), cancellationToken);if (result.PlacedOrder.PaymentStatusId == PaymentStatus.Paid){- await _mediator.Send(new ProcessOrderPaidCommand() { Order = result.PlacedOrder });+ await _mediator.Send(new ProcessOrderPaidCommand { Order = result.PlacedOrder }, cancellationToken);}#endregion@@ -217,19 +217,18 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders#region Process errors- string error = "";- for (int i = 0; i < result.Errors.Count; i++)+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++){- error += string.Format("Error {0}: {1}", i + 1, result.Errors[i]);+ error += $"Error {i + 1}: {result.Errors[i]}";if (i != result.Errors.Count - 1)error += ". ";}- if (!string.IsNullOrEmpty(error))- {- //log it- string logError = string.Format("Error while placing order. {0}", error);- _ = _logger.Error(logError);- }++ if (string.IsNullOrEmpty(error)) return result;+ //log it+ var logError = $"Error while placing order. {error}";+ _ = _logger.Error(logError);#endregion@@ -237,13 +236,13 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}protected virtual async Task<(ProcessPaymentResult paymentResult, PaymentTransaction paymentTransaction)>- PrepareProcessPayment(PlaceOrderContainter details)+ PrepareProcessPayment(PlaceOrderContainer details){//payment transactionvar paymentTransaction = await PreparePaymentTransaction(details);//process payment- ProcessPaymentResult processPaymentResult = null;+ ProcessPaymentResult processPaymentResult;//skip payment workflow if order total equals zerovar skipPaymentWorkflow = details.OrderTotal == 0;if (!skipPaymentWorkflow)@@ -262,9 +261,9 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orderselse{//payment is not required- if (processPaymentResult == null)- processPaymentResult = new ProcessPaymentResult();- processPaymentResult.NewPaymentTransactionStatus = TransactionStatus.Paid;+ processPaymentResult = new ProcessPaymentResult {+ NewPaymentTransactionStatus = TransactionStatus.Paid+ };}if (processPaymentResult == null)@@ -273,10 +272,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn (processPaymentResult, paymentTransaction);}- protected async Task<PaymentTransaction> PreparePaymentTransaction(PlaceOrderContainter details)+ private async Task<PaymentTransaction> PreparePaymentTransaction(PlaceOrderContainer details){var update = false;- var paymentTransaction = new PaymentTransaction() { CreatedOnUtc = DateTime.UtcNow };+ PaymentTransaction paymentTransaction = new PaymentTransaction { CreatedOnUtc = DateTime.UtcNow };var paymentTransactionId = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentTransaction, _workContext.CurrentStore.Id);if (!string.IsNullOrEmpty(paymentTransactionId)){@@ -286,6 +285,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersupdate = true;paymentTransaction.UpdatedOnUtc = DateTime.UtcNow;}+ else+ paymentTransaction = new PaymentTransaction { CreatedOnUtc = DateTime.UtcNow };}paymentTransaction.TransactionStatus = TransactionStatus.Pending;@@ -309,7 +310,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn paymentTransaction;}- protected async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction, Order order, ProcessPaymentResult processPaymentResult)+ private async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction, Order order, ProcessPaymentResult processPaymentResult){paymentTransaction.TransactionAmount = order.OrderTotal;paymentTransaction.PaidAmount = order.PaidAmount;@@ -318,25 +319,21 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrderspaymentTransaction.Errors.Clear();await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);}- private async Task<double?> PrepareCommissionRate(Product product, PlaceOrderContainter details)+ private async Task<double?> PrepareCommissionRate(Product product, PlaceOrderContainer details){var commissionRate = default(double?);if (!string.IsNullOrEmpty(product.VendorId)){var vendor = await _vendorService.GetVendorById(product.VendorId);- if (vendor != null && vendor.Commission.HasValue)+ if (vendor is { Commission: { } })commissionRate = vendor.Commission.Value;}- if (!commissionRate.HasValue)- {- if (!string.IsNullOrEmpty(details.Customer.SeId))- {- var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(details.Customer.SeId);- if (salesEmployee != null && salesEmployee.Active && salesEmployee.Commission.HasValue)- commissionRate = salesEmployee.Commission.Value;- }- }+ if (commissionRate.HasValue) return commissionRate;+ if (string.IsNullOrEmpty(details.Customer.SeId)) return null;+ var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(details.Customer.SeId);+ if (salesEmployee is { Active: true, Commission: { } })+ commissionRate = salesEmployee.Commission.Value;return commissionRate;}@@ -373,7 +370,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders{//bundled productvar associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);- if (associatedProduct != null && associatedProduct.IsShipEnabled)+ if (associatedProduct is { IsShipEnabled: true }){attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;}@@ -388,9 +385,9 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn weight;}- protected virtual async Task<PlaceOrderContainter> PreparePlaceOrderDetails()+ protected virtual async Task<PlaceOrderContainer> PreparePlaceOrderDetails(){- var details = new PlaceOrderContainter {+ var details = new PlaceOrderContainer {//customerCustomer = _workContext.CurrentCustomer};@@ -412,13 +409,13 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (!string.IsNullOrEmpty(details.Customer.AffiliateId)){var affiliate = await _affiliateService.GetAffiliateById(details.Customer.AffiliateId);- if (affiliate != null && affiliate.Active)+ if (affiliate is { Active: true })details.AffiliateId = affiliate.Id;}//customer currencyvar currencyTmp = await _currencyService.GetCurrencyById(details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, _workContext.CurrentStore.Id));- var customerCurrency = (currencyTmp != null && currencyTmp.Published) ? currencyTmp : _workContext.WorkingCurrency;+ var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : _workContext.WorkingCurrency;details.Currency = customerCurrency;var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();details.CurrencyRate = Math.Round(customerCurrency.Rate / primaryStoreCurrency.Rate, 6);@@ -427,16 +424,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//customer languagedetails.Language = await _languageService.GetLanguageById(details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, _workContext.CurrentStore.Id));- if (details.Language == null || !details.Language.Published)+ if (details.Language is not { Published: true })details.Language = _workContext.WorkingLanguage;details.BillingAddress = details.Customer.BillingAddress;if (!string.IsNullOrEmpty(details.BillingAddress.CountryId)){var country = await _countryService.GetCountryById(details.BillingAddress.CountryId);- if (country != null)- if (!country.AllowsBilling)- throw new GrandException(string.Format("Country '{0}' is not allowed for billing", country.Name));+ if (country is { AllowsBilling: false }) throw new GrandException($"Country '{country.Name}' is not allowed for billing");}//checkout attributes@@ -445,7 +440,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//load and validate customer shopping cartdetails.Cart = details.Customer.ShoppingCartItems- .Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart || sci.ShoppingCartTypeId == ShoppingCartType.Auctions)+ .Where(sci => sci.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions).LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id).ToList();@@ -457,10 +452,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (warnings.Any()){var warningsSb = new StringBuilder();- foreach (string warning in warnings)+ foreach (var warning in warnings){warningsSb.Append(warning);- warningsSb.Append(";");+ warningsSb.Append(';');}throw new GrandException(warningsSb.ToString());}@@ -473,31 +468,30 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (sciWarnings.Any()){var warningsSb = new StringBuilder();- foreach (string warning in sciWarnings)+ foreach (var warning in sciWarnings){warningsSb.Append(warning);- warningsSb.Append(";");+ warningsSb.Append(';');}throw new GrandException(warningsSb.ToString());}- if (product.IsRecurring)- {- details.IsRecurring = true;- details.RecurringCycleLength = product.RecurringCycleLength;- details.RecurringCyclePeriodId = product.RecurringCyclePeriodId;- details.RecurringTotalCycles = product.RecurringTotalCycles;- }++ if (!product.IsRecurring) continue;+ details.IsRecurring = true;+ details.RecurringCycleLength = product.RecurringCycleLength;+ details.RecurringCyclePeriodId = product.RecurringCyclePeriodId;+ details.RecurringTotalCycles = product.RecurringTotalCycles;}//min totals validation- bool minOrderSubtotalAmountOk = await _mediator.Send(new ValidateMinShoppingCartSubtotalAmountCommand() { Customer = _workContext.CurrentCustomer, Cart = details.Cart });+ var minOrderSubtotalAmountOk = await _mediator.Send(new ValidateMinShoppingCartSubtotalAmountCommand() { Customer = _workContext.CurrentCustomer, Cart = details.Cart });if (!minOrderSubtotalAmountOk){- double minOrderSubtotalAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);+ var minOrderSubtotalAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);throw new GrandException(string.Format(_translationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, false)));}- bool minmaxOrderTotalAmountOk = await _mediator.Send(new ValidateShoppingCartTotalAmountCommand() { Customer = details.Customer, Cart = details.Cart });+ var minmaxOrderTotalAmountOk = await _mediator.Send(new ValidateShoppingCartTotalAmountCommand() { Customer = details.Customer, Cart = details.Cart });if (!minmaxOrderTotalAmountOk){throw new GrandException(_translationService.GetResource("Checkout.MinMaxOrderTotalAmount"));@@ -512,30 +506,26 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//sub total//sub total (incl tax)var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true);- double orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;+ var orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;List<ApplyDiscount> orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts;- double subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;- double subTotalWithDiscountBase = shoppingCartSubTotal.subTotalWithDiscount;+ var subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;details.OrderSubTotalInclTax = subTotalWithoutDiscountBase;details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount;- foreach (var disc in orderSubTotalAppliedDiscounts)- if (!details.AppliedDiscounts.Where(x => x.DiscountId == disc.DiscountId).Any())- details.AppliedDiscounts.Add(disc);+ foreach (var disc in orderSubTotalAppliedDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ details.AppliedDiscounts.Add(disc);//sub total (excl tax)shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false);orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;- orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts;subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;- subTotalWithDiscountBase = shoppingCartSubTotal.subTotalWithDiscount;details.OrderSubTotalExclTax = subTotalWithoutDiscountBase;details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount;//shipping info- bool shoppingCartRequiresShipping = shoppingCartRequiresShipping = details.Cart.RequiresShipping();+ var shoppingCartRequiresShipping = details.Cart.RequiresShipping();if (shoppingCartRequiresShipping){@@ -543,7 +533,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (_shippingSettings.AllowPickUpInStore && pickupPoint != null){details.PickUpInStore = true;- details.PickupPoint = await _mediator.Send(new GetPickupPointById() { Id = pickupPoint });+ details.PickupPoint = await _mediator.Send(new GetPickupPointById { Id = pickupPoint });}else{@@ -555,12 +545,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//clone shipping addressdetails.ShippingAddress = details.Customer.ShippingAddress;- if (!String.IsNullOrEmpty(details.ShippingAddress.CountryId))+ if (!string.IsNullOrEmpty(details.ShippingAddress.CountryId)){var country = await _countryService.GetCountryById(details.ShippingAddress.CountryId);- if (country != null)- if (!country.AllowsShipping)- throw new GrandException(string.Format("Country '{0}' is not allowed for shipping", country.Name));+ if (country is { AllowsShipping: false }) throw new GrandException($"Country '{country.Name}' is not allowed for shipping");}}var shippingOption = details.Customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption, _workContext.CurrentStore.Id);@@ -576,104 +564,86 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//shipping total- var shoppingCartShippingTotal = await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true);- double tax = shoppingCartShippingTotal.taxRate;- List<ApplyDiscount> shippingTotalDiscounts = shoppingCartShippingTotal.appliedDiscounts;- var orderShippingTotalInclTax = shoppingCartShippingTotal.shoppingCartShippingTotal;+ var (orderShippingTotalInclTax, _, shippingTotalDiscounts) = await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true);var orderShippingTotalExclTax = (await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false)).shoppingCartShippingTotal;if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)throw new GrandException("Shipping total couldn't be calculated");- foreach (var disc in shippingTotalDiscounts)+ foreach (var disc in shippingTotalDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId))){- if (!details.AppliedDiscounts.Where(x => x.DiscountId == disc.DiscountId).Any())- details.AppliedDiscounts.Add(disc);+ details.AppliedDiscounts.Add(disc);}--details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;//paymentvar paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod, _workContext.CurrentStore.Id);details.PaymentMethodSystemName = paymentMethodSystemName;- double paymentAdditionalFee = await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);+ var paymentAdditionalFee = await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);details.PaymentAdditionalFeeInclTax = (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer)).paymentPrice;details.PaymentAdditionalFeeExclTax = (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer)).paymentPrice;//tax total//tax amount- var (taxtotal, taxRates) = await _orderTotalCalculationService.GetTaxTotal(details.Cart);- details.OrderTaxTotal = taxtotal;+ var (taxTotal, taxRates) = await _orderTotalCalculationService.GetTaxTotal(details.Cart);+ details.OrderTaxTotal = taxTotal;//tax ratesforeach (var kvp in taxRates){- details.Taxes.Add(new OrderTax() {+ details.Taxes.Add(new OrderTax {Percent = Math.Round(kvp.Key, 2),Amount = kvp.Value});}//order total (and applied discounts, gift vouchers, loyalty points)- var shoppingCartTotal = await _orderTotalCalculationService.GetShoppingCartTotal(details.Cart);- List<AppliedGiftVoucher> appliedGiftVouchers = shoppingCartTotal.appliedGiftVouchers;- List<ApplyDiscount> orderAppliedDiscounts = shoppingCartTotal.appliedDiscounts;- double orderDiscountAmount = shoppingCartTotal.discountAmount;- int redeemedLoyaltyPoints = shoppingCartTotal.redeemedLoyaltyPoints;- var orderTotal = shoppingCartTotal.shoppingCartTotal;+ var (orderTotal, orderDiscountAmount, orderAppliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints, redeemedLoyaltyPointsAmount) = await _orderTotalCalculationService.GetShoppingCartTotal(details.Cart);if (!orderTotal.HasValue)throw new GrandException("Order total couldn't be calculated");details.OrderDiscountAmount = orderDiscountAmount;details.RedeemedLoyaltyPoints = redeemedLoyaltyPoints;- details.RedeemedLoyaltyPointsAmount = shoppingCartTotal.redeemedLoyaltyPointsAmount;+ details.RedeemedLoyaltyPointsAmount = redeemedLoyaltyPointsAmount;details.AppliedGiftVouchers = appliedGiftVouchers;details.OrderTotal = orderTotal.Value;//discount history- foreach (var disc in orderAppliedDiscounts)+ foreach (var disc in orderAppliedDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId))){- if (!details.AppliedDiscounts.Where(x => x.DiscountId == disc.DiscountId).Any())- details.AppliedDiscounts.Add(disc);+ details.AppliedDiscounts.Add(disc);}return details;}- protected virtual async Task<OrderItem> PrepareOrderItem(ShoppingCartItem sc, Product product, PlaceOrderContainter details)+ protected virtual async Task<OrderItem> PrepareOrderItem(ShoppingCartItem sc, Product product, PlaceOrderContainer details){- List<ApplyDiscount> scDiscounts;- double discountAmount;- double scUnitPrice = (await _pricingService.GetUnitPrice(sc, product)).unitprice;- double scUnitPriceWithoutDisc = (await _pricingService.GetUnitPrice(sc, product, false)).unitprice;+ var scUnitPrice = (await _pricingService.GetUnitPrice(sc, product)).unitprice;+ var scUnitPriceWithoutDisc = (await _pricingService.GetUnitPrice(sc, product, false)).unitprice;- var subtotal = await _pricingService.GetSubTotal(sc, product, true);- double scSubTotal = subtotal.subTotal;- discountAmount = subtotal.discountAmount;- scDiscounts = subtotal.appliedDiscounts;+ var (scSubTotal, discountAmount, scDiscounts) = await _pricingService.GetSubTotal(sc, product);var prices = await _taxService.GetTaxProductPrice(product, details.Customer, scUnitPrice, scUnitPriceWithoutDisc, sc.Quantity, scSubTotal, discountAmount, _taxSettings.PricesIncludeTax);- double scUnitPriceWithoutDiscInclTax = prices.UnitPriceWihoutDiscInclTax;- double scUnitPriceWithoutDiscExclTax = prices.UnitPriceWihoutDiscExclTax;- double scUnitPriceInclTax = prices.UnitPriceInclTax;- double scUnitPriceExclTax = prices.UnitPriceExclTax;- double scSubTotalInclTax = prices.SubTotalInclTax;- double scSubTotalExclTax = prices.SubTotalExclTax;- double discountAmountInclTax = prices.discountAmountInclTax;- double discountAmountExclTax = prices.discountAmountExclTax;-- foreach (var disc in scDiscounts)+ var scUnitPriceWithoutDiscInclTax = prices.UnitPriceWithoutDiscInclTax;+ var scUnitPriceWithoutDiscExclTax = prices.UnitPriceWithoutDiscExclTax;+ var scUnitPriceInclTax = prices.UnitPriceInclTax;+ var scUnitPriceExclTax = prices.UnitPriceExclTax;+ var scSubTotalInclTax = prices.SubTotalInclTax;+ var scSubTotalExclTax = prices.SubTotalExclTax;+ var discountAmountInclTax = prices.DiscountAmountInclTax;+ var discountAmountExclTax = prices.DiscountAmountExclTax;++ foreach (var disc in scDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId))){- if (!details.AppliedDiscounts.Where(x => x.DiscountId == disc.DiscountId).Any())- details.AppliedDiscounts.Add(disc);+ details.AppliedDiscounts.Add(disc);}//attributes- string attributeDescription = await _productAttributeFormatter.FormatAttributes(product, sc.Attributes, details.Customer);+ var attributeDescription = await _productAttributeFormatter.FormatAttributes(product, sc.Attributes, details.Customer);if (string.IsNullOrEmpty(attributeDescription) && sc.ShoppingCartTypeId == ShoppingCartType.Auctions)- attributeDescription = _translationService.GetResource("ShoppingCart.auctionwonon") + " " + product.AvailableEndDateTimeUtc;+ attributeDescription = _translationService.GetResource("ShoppingCart.AuctionWonOn") + " " + product.AvailableEndDateTimeUtc;var itemWeight = await GetShoppingCartItemWeight(sc);@@ -687,8 +657,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}var commissionRate = await PrepareCommissionRate(product, details);- var commision = commissionRate.HasValue ?- Math.Round((commissionRate.Value * scSubTotal / 100), 2) : 0;+ var commission = commissionRate.HasValue ?+ Math.Round(commissionRate.Value * scSubTotal / 100, 2) : 0;//save order itemvar orderItem = new OrderItem {@@ -698,7 +668,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersVendorId = product.VendorId,WarehouseId = warehouseId,SeId = details.Customer.SeId,- TaxRate = Math.Round(prices.taxRate, 2),+ TaxRate = Math.Round(prices.TaxRate, 2),UnitPriceWithoutDiscInclTax = Math.Round(scUnitPriceWithoutDiscInclTax, 6),UnitPriceWithoutDiscExclTax = Math.Round(scUnitPriceWithoutDiscExclTax, 6),UnitPriceInclTax = Math.Round(scUnitPriceInclTax, 6),@@ -720,11 +690,11 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersRentalStartDateUtc = sc.RentalStartDateUtc,RentalEndDateUtc = sc.RentalEndDateUtc,CreatedOnUtc = DateTime.UtcNow,- Commission = commision,+ Commission = commission,cId = sc.cId};- string reservationInfo = "";+ var reservationInfo = "";if (product.ProductTypeId == ProductType.Reservation){if (sc.RentalEndDateUtc == default(DateTime) || sc.RentalEndDateUtc == null)@@ -744,21 +714,20 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersreservationInfo += "<br>" + _translationService.GetResource("Products.Duration") + ": " + sc.Duration;}}- if (!string.IsNullOrEmpty(reservationInfo))++ if (string.IsNullOrEmpty(reservationInfo)) return orderItem;+ if (!string.IsNullOrEmpty(orderItem.AttributeDescription)){- if (!string.IsNullOrEmpty(orderItem.AttributeDescription))- {- orderItem.AttributeDescription += "<br>" + reservationInfo;- }- else- {- orderItem.AttributeDescription = reservationInfo;- }+ orderItem.AttributeDescription += "<br>" + reservationInfo;+ }+ else+ {+ orderItem.AttributeDescription = reservationInfo;}return orderItem;}- protected virtual async Task GenerateGiftVoucher(PlaceOrderContainter details, ShoppingCartItem sc, Order order, OrderItem orderItem, Product product)+ protected virtual async Task GenerateGiftVoucher(PlaceOrderContainer details, ShoppingCartItem sc, Order order, OrderItem orderItem, Product product){GiftVoucherExtensions.GetGiftVoucherAttribute(sc.Attributes,out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,@@ -790,7 +759,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}}- protected virtual async Task UpdateProductReservation(Order order, PlaceOrderContainter details)+ protected virtual async Task UpdateProductReservation(Order order, PlaceOrderContainer details){var reservationsToUpdate = new List<ProductReservation>();foreach (var sc in details.Cart.Where(x => (x.RentalStartDateUtc.HasValue && x.RentalEndDateUtc.HasValue) || !string.IsNullOrEmpty(x.ReservationId)))@@ -802,69 +771,60 @@ namespace Grand.Business.Checkout.Commands.Handlers.OrdersreservationsToUpdate.Add(reservation);}- if (sc.RentalStartDateUtc.HasValue && sc.RentalEndDateUtc.HasValue)- {- var reservations = await _productReservationService.GetProductReservationsByProductId(product.Id, true, null);- var grouped = reservations.GroupBy(x => x.Resource);+ if (!sc.RentalStartDateUtc.HasValue || !sc.RentalEndDateUtc.HasValue) continue;+ var reservations = await _productReservationService.GetProductReservationsByProductId(product.Id, true, null);+ var grouped = reservations.GroupBy(x => x.Resource);- IGrouping<string, ProductReservation> groupToBook = null;- foreach (var group in grouped)+ IGrouping<string, ProductReservation> groupToBook = null;+ foreach (var group in grouped)+ {+ var groupCanBeBooked = true;+ if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day){- bool groupCanBeBooked = true;- if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)- {- for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator <= sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }- }- }- else+ for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator <= sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0)){- for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator < sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }- }- }- if (groupCanBeBooked)- {- groupToBook = group;+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;break;}}-- if (groupToBook == null)- {- throw new Exception("ShoppingCart.Reservation.Nofreereservationsinthisperiod");- }else{- var temp = groupToBook.AsQueryable();- if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)- {- temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date <= sc.RentalEndDateUtc);- }- else+ for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator < sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0)){- temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date < sc.RentalEndDateUtc);+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}+ }- foreach (var item in temp)- {- item.OrderId = order.OrderGuid.ToString();- await _productReservationService.UpdateProductReservation(item);- }+ if (!groupCanBeBooked) continue;+ groupToBook = group;+ break;+ }- reservationsToUpdate.AddRange(temp);- }+ if (groupToBook == null)+ {+ throw new Exception("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod");+ }++ var temp = groupToBook.AsQueryable();+ if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)+ {+ temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date <= sc.RentalEndDateUtc);}+ else+ {+ temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date < sc.RentalEndDateUtc);+ }++ foreach (var item in temp)+ {+ item.OrderId = order.OrderGuid.ToString();+ await _productReservationService.UpdateProductReservation(item);+ }++ reservationsToUpdate.AddRange(temp);}var reserved = await _productReservationService.GetCustomerReservationsHelpers(order.CustomerId);foreach (var res in reserved)@@ -900,23 +860,21 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}if (product.ProductTypeId == ProductType.Auction && _orderSettings.UnpublishAuctionProduct){- await _productService.UnpublishProduct(product);+ await _productService.UnPublishProduct(product);}}- protected virtual async Task UpdateBids(Order order, PlaceOrderContainter details)+ protected virtual async Task UpdateBids(Order order, PlaceOrderContainer details){foreach (var sc in details.Cart.Where(x => x.ShoppingCartTypeId == ShoppingCartType.Auctions)){- var bid = (await _auctionService.GetBidsByProductId(sc.Id)).Where(x => x.CustomerId == details.Customer.Id).FirstOrDefault();- if (bid != null)- {- bid.OrderId = order.Id;- await _auctionService.UpdateBid(bid);- }+ var bid = (await _auctionService.GetBidsByProductId(sc.Id)).FirstOrDefault(x => x.CustomerId == details.Customer.Id);+ if (bid == null) continue;+ bid.OrderId = order.Id;+ await _auctionService.UpdateBid(bid);}}- protected virtual async Task InsertDiscountUsageHistory(Order order, PlaceOrderContainter details)+ protected virtual async Task InsertDiscountUsageHistory(Order order, PlaceOrderContainer details){foreach (var discount in details.AppliedDiscounts){@@ -931,18 +889,18 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}}- protected virtual async Task AppliedGiftVouchers(Order order, PlaceOrderContainter details)+ protected virtual async Task AppliedGiftVouchers(Order order, PlaceOrderContainer details){foreach (var agc in details.AppliedGiftVouchers){- double amountUsed = agc.AmountCanBeUsed;- var gcuh = new GiftVoucherUsageHistory {+ var amountUsed = agc.AmountCanBeUsed;+ var giftVoucherUsageHistory = new GiftVoucherUsageHistory {GiftVoucherId = agc.GiftVoucher.Id,UsedWithOrderId = order.Id,UsedValue = amountUsed,CreatedOnUtc = DateTime.UtcNow};- agc.GiftVoucher.GiftVoucherUsageHistory.Add(gcuh);+ agc.GiftVoucher.GiftVoucherUsageHistory.Add(giftVoucherUsageHistory);await _giftVoucherService.UpdateGiftVoucher(agc.GiftVoucher);}}@@ -952,7 +910,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders/// </summary>/// <returns>Order</returns>protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction,- ProcessPaymentResult processPaymentResult, PlaceOrderContainter details)+ ProcessPaymentResult processPaymentResult, PlaceOrderContainer details){var paymentStatus = PaymentStatus.Pending;@@ -1036,10 +994,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders/// <summary>/// Save order details/// </summary>- /// <param name="details">Place order containter</param>+ /// <param name="details">Place order container</param>/// <param name="order">Order</param>/// <returns>Order</returns>- protected virtual async Task<Order> SaveOrderDetails(PlaceOrderContainter details, Order order)+ protected virtual async Task<Order> SaveOrderDetails(PlaceOrderContainer details, Order order){//move shopping cart items to order itemsforeach (var sc in details.Cart)@@ -1094,7 +1052,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders/// <summary>/// Send notification order/// </summary>+ /// <param name="scopeFactory"></param>/// <param name="order">Order</param>+ /// <param name="customer"></param>+ /// <param name="originalCustomerIfImpersonated"></param>protected virtual async Task SendNotification(IServiceScopeFactory scopeFactory, Order order, Customer customer, Customer originalCustomerIfImpersonated){using var scope = scopeFactory.CreateScope();@@ -1111,7 +1072,6 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar languageSettings = scope.ServiceProvider.GetRequiredService<LanguageSettings>();var pdfService = scope.ServiceProvider.GetRequiredService<IPdfService>();var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();- var logger = scope.ServiceProvider.GetRequiredService<ILogger>();try{//notes, messages@@ -1119,8 +1079,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders{//this order is placed by a store administrator impersonating a customerawait orderService.InsertOrderNote(new OrderNote {- Note = string.Format("Order placed by a store owner ('{0}'. ID = {1}) impersonating the customer.",- originalCustomerIfImpersonated.Email, originalCustomerIfImpersonated.Id),+ Note =+ $"Order placed by a store owner ('{originalCustomerIfImpersonated.Email}'. ID = {originalCustomerIfImpersonated.Id}) impersonating the customer.",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,OrderId = order.Id,@@ -1171,7 +1131,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders}catch (Exception e){- await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Place order send notifiaction error", e.Message);+ await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Place order send notification error", e.Message);}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.csindex 604529c97..712a6f380 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs@@ -73,13 +73,12 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _messageProviderService.SendOrderPaidStoreOwnerMessage(order, customer, _languageSettings.DefaultAdminLanguageId);if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId))){- var vendors = await _mediator.Send(new GetVendorsInOrderQuery() { Order = order });+ var vendors = await _mediator.Send(new GetVendorsInOrderQuery { Order = order });foreach (var vendor in vendors){await _messageProviderService.SendOrderPaidVendorMessage(order, vendor, _languageSettings.DefaultAdminLanguageId);}}- //TODO add "order paid email sent" order note}}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.csindex c9050b0b1..20e72d129 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs@@ -52,7 +52,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders: (double?)default,orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc,orderItem.Quantity, false,- validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false })).warnings);+ validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false })).warnings);}}elsediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.csindex 95a465865..2ab87df7a 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs@@ -43,7 +43,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar amount = await _currencyService.ConvertToPrimaryStoreCurrency(request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);- int points = await _mediator.Send(new CalculateLoyaltyPointsCommand() { Customer = customer, Amount = amount });+ var points = await _mediator.Send(new CalculateLoyaltyPointsCommand() { Customer = customer, Amount = amount }, cancellationToken);if (points <= 0)return false;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.csindex 5bfc08955..213bc7643 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs@@ -67,7 +67,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (order == null)throw new ArgumentNullException(nameof(order));- double totalAmountRefunded = order.RefundedAmount + request.AmountToRefund;+ var totalAmountRefunded = order.RefundedAmount + request.AmountToRefund;//update order infoorder.RefundedAmount = totalAmountRefunded;@@ -75,7 +75,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);//notifications for store ownerawait _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, request.AmountToRefund, _languageSettings.DefaultAdminLanguageId);@@ -84,32 +84,29 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _messageProviderService.SendOrderRefundedCustomerMessage(order, request.AmountToRefund, order.CustomerLanguageId);//raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, request.AmountToRefund));+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, request.AmountToRefund), cancellationToken);}}catch (Exception exc){- if (result == null)- result = new RefundPaymentResult();- result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc.ToString()));+ result ??= new RefundPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");}//process errors- string error = "";- for (int i = 0; i < result.Errors.Count; i++)+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++){- error += string.Format("Error {0}: {1}", i, result.Errors[i]);+ error += $"Error {i}: {result.Errors[i]}";if (i != result.Errors.Count - 1)error += ". ";}- if (!String.IsNullOrEmpty(error))- {- //log it- string logError = string.Format("Error refunding order #{0}. Error: {1}", paymentTransaction.OrderCode, error);- await _logger.InsertLog(LogLevel.Error, logError, logError);- }+ if (string.IsNullOrEmpty(error)) return result.Errors;+ //log it+ var logError = $"Error refunding order #{paymentTransaction.OrderCode}. Error: {error}";+ await _logger.InsertLog(LogLevel.Error, logError, logError);return result.Errors;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.csindex 28461869d..bdc0713e0 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs@@ -39,7 +39,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- var canRefundOffline = await _mediator.Send(new CanRefundOfflineQuery() { PaymentTransaction = paymentTransaction });+ var canRefundOffline = await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction }, cancellationToken);if (!canRefundOffline)throw new GrandException("You can't refund this payment transaction");@@ -52,11 +52,11 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (order == null)throw new ArgumentNullException(nameof(order));- //amout to refund- double amountToRefund = order.OrderTotal;+ //amount to refund+ var amountToRefund = order.OrderTotal;//total amount refunded- double totalAmountRefunded = order.RefundedAmount + amountToRefund;+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;//update order infoorder.RefundedAmount = totalAmountRefunded;@@ -66,7 +66,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);//notifications for store ownerawait _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);@@ -75,7 +75,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);//raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund));+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);return true;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.csindex 012ed2321..91da8ea88 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs@@ -40,45 +40,47 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersvar originalOrder = await _orderService.GetOrderById(request.Order.Id);var originalOrderItem = originalOrder.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id);-- request.Order.OrderSubtotalExclTax += (request.OrderItem.PriceExclTax - originalOrderItem.PriceExclTax);- request.Order.OrderSubtotalInclTax += (request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax);- request.Order.OrderTax +=- ((request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax)- - (originalOrderItem.PriceInclTax - originalOrderItem.PriceExclTax));- request.Order.OrderTotal += (request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax);-- //TODO- //request.Order.OrderTaxes-- //adjust inventory- if (originalOrderItem.Quantity != request.OrderItem.Quantity)+ if (originalOrderItem != null){- int qtyDifference = originalOrderItem.Quantity - request.OrderItem.Quantity;- var product = await _productService.GetProductById(request.OrderItem.ProductId);- await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes, request.OrderItem.WarehouseId);+ request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax - originalOrderItem.PriceExclTax;+ request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;+ request.Order.OrderTax +=+ request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax+ - (originalOrderItem.PriceInclTax - originalOrderItem.PriceExclTax);+ request.Order.OrderTotal += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;- if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)+ //TODO+ //request.Order.OrderTaxes++ //adjust inventory+ if (originalOrderItem.Quantity != request.OrderItem.Quantity){- var shipments = (await _shipmentService.GetShipmentsByOrder(request.Order.Id));+ var qtyDifference = originalOrderItem.Quantity - request.OrderItem.Quantity;+ var product = await _productService.GetProductById(request.OrderItem.ProductId);+ await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes,+ request.OrderItem.WarehouseId);- if (!request.Order.HasItemsToAddToShipment() && !shipments.Where(x => x.DeliveryDateUtc == null).Any())+ if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped){- request.Order.ShippingStatusId = ShippingStatus.Delivered;+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);++ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))+ {+ request.Order.ShippingStatusId = ShippingStatus.Delivered;+ }}}}await _orderService.UpdateOrder(request.Order);-//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = request.Order });+ await _mediator.Send(new CheckOrderStatusCommand() { Order = request.Order }, cancellationToken);//add a noteawait _orderService.InsertOrderNote(new OrderNote {Note = "Order item has been edited",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = request.Order.Id,+ OrderId = request.Order.Id});return true;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.csindex 1446100ce..8c91187df 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs@@ -38,15 +38,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersreturn false;//min order amount sub-total validation- if (cart.Any() && _orderSettings.MinOrderSubtotalAmount > 0)- {- //subtotal- var (_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false);- if (subTotalWithoutDiscount < _orderSettings.MinOrderSubtotalAmount)- return false;- }-- return true;+ if (!cart.Any() || !(_orderSettings.MinOrderSubtotalAmount > 0)) return true;+ //subtotal+ var (_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false);+ return !(subTotalWithoutDiscount < _orderSettings.MinOrderSubtotalAmount);}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.csindex 4fd12bd1e..7a2970516 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs@@ -31,23 +31,19 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersthrow new ArgumentNullException(nameof(request.Customer));var customerGroups = await _groupService.GetAllByIds(request.Customer.Groups.ToArray());- var minroles = customerGroups.OrderBy(x => x.MinOrderAmount).FirstOrDefault(x => x.MinOrderAmount.HasValue);- var minOrderAmount = minroles?.MinOrderAmount ?? double.MinValue;+ var minRoles = customerGroups.OrderBy(x => x.MinOrderAmount).FirstOrDefault(x => x.MinOrderAmount.HasValue);+ var minOrderAmount = minRoles?.MinOrderAmount ?? double.MinValue;- var maxroles = customerGroups.OrderByDescending(x => x.MaxOrderAmount).FirstOrDefault(x => x.MaxOrderAmount.HasValue);- var maxOrderAmount = maxroles?.MaxOrderAmount ?? double.MaxValue;+ var maxRoles = customerGroups.OrderByDescending(x => x.MaxOrderAmount).FirstOrDefault(x => x.MaxOrderAmount.HasValue);+ var maxOrderAmount = maxRoles?.MaxOrderAmount ?? double.MaxValue;- if (request.Cart.Any() && (minOrderAmount > 0 || maxOrderAmount > 0 || _orderSettings.MinOrderTotalAmount > 0))- {- double? shoppingCartTotalBase = (await _orderTotalCalculationService.GetShoppingCartTotal(request.Cart)).shoppingCartTotal;- if (shoppingCartTotalBase.HasValue && (shoppingCartTotalBase.Value < minOrderAmount || shoppingCartTotalBase.Value > maxOrderAmount))- return false;+ if (!request.Cart.Any() || (!(minOrderAmount > 0) && !(maxOrderAmount > 0) &&+ !(_orderSettings.MinOrderTotalAmount > 0))) return true;+ var shoppingCartTotalBase = (await _orderTotalCalculationService.GetShoppingCartTotal(request.Cart)).shoppingCartTotal;+ if (shoppingCartTotalBase.HasValue && (shoppingCartTotalBase.Value < minOrderAmount || shoppingCartTotalBase.Value > maxOrderAmount))+ return false;- if (_orderSettings.MinOrderTotalAmount > 0 && shoppingCartTotalBase.HasValue && shoppingCartTotalBase.Value < _orderSettings.MinOrderTotalAmount)- return false;- }-- return true;+ return !(_orderSettings.MinOrderTotalAmount > 0) || !shoppingCartTotalBase.HasValue || !(shoppingCartTotalBase.Value < _orderSettings.MinOrderTotalAmount);}}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.csindex ddd1ca1c4..62be759bf 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs@@ -38,7 +38,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(command.PaymentTransaction));- var canVoid = await _mediator.Send(new CanVoidQuery() { PaymentTransaction = paymentTransaction });+ var canVoid = await _mediator.Send(new CanVoidQuery { PaymentTransaction = paymentTransaction }, cancellationToken);if (!canVoid)throw new GrandException("Cannot do void for order.");@@ -66,30 +66,28 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _orderService.UpdateOrder(order);//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand() { Order = order }, cancellationToken);}}}catch (Exception exc){- if (result == null)- result = new VoidPaymentResult();- result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc.ToString()));+ result ??= new VoidPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");}//process errors- string error = "";- for (int i = 0; i < result.Errors.Count; i++)+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++){- error += string.Format("Error {0}: {1}", i, result.Errors[i]);+ error += $"Error {i}: {result.Errors[i]}";if (i != result.Errors.Count - 1)error += ". ";}- if (!String.IsNullOrEmpty(error))- {- string logError = string.Format("Error voiding order #{0}. Error: {1}", paymentTransaction.OrderCode, error);- await _logger.InsertLog(LogLevel.Error, logError, logError);- }++ if (string.IsNullOrEmpty(error)) return result.Errors;+ var logError = $"Error voiding order #{paymentTransaction.OrderCode}. Error: {error}";+ await _logger.InsertLog(LogLevel.Error, logError, logError);return result.Errors;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.csindex 05d0a26eb..9ad1e85fe 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs@@ -38,17 +38,17 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (order == null)throw new ArgumentNullException(nameof(order));- if (!(await _mediator.Send(new CanVoidOfflineQuery() { PaymentTransaction = paymentTransaction })))+ if (!await _mediator.Send(new CanVoidOfflineQuery() { PaymentTransaction = paymentTransaction }, cancellationToken))throw new GrandException("You can't void this order");order.PaymentStatusId = PaymentStatus.Voided;await _orderService.UpdateOrder(order);//event notification- await _mediator.Publish(new PaymentTransactionVoidOfflineEvent(paymentTransaction));+ await _mediator.Publish(new PaymentTransactionVoidOfflineEvent(paymentTransaction), cancellationToken);- //check orer status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand() { Order = order }, cancellationToken);return true;}}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.csindex f4b180edb..94ca419c8 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs@@ -48,7 +48,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Shippingawait _shipmentService.UpdateShipment(request.Shipment);var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);- if (!order.HasItemsToAddToShipment() && !shipments.Where(x => x.DeliveryDateUtc == null).Any())+ if (!order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null)){order.ShippingStatusId = ShippingStatus.Delivered;await _orderService.UpdateOrder(order);@@ -59,7 +59,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.ShippingNote = $"Shipment #{request.Shipment.ShipmentNumber} has been delivered",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = order.Id,+ OrderId = order.Id});if (request.NotifyCustomer){@@ -67,7 +67,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Shippingawait _messageProviderService.SendShipmentDeliveredCustomerMessage(request.Shipment, order);}//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);//eventawait _mediator.PublishShipmentDelivered(request.Shipment);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.csindex 20172c338..93e42f631 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs@@ -50,10 +50,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Shippingelse{var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);- if (!shipments.Where(x => x.ShippedDateUtc == null).Any())- order.ShippingStatusId = ShippingStatus.Shipped;- else- order.ShippingStatusId = ShippingStatus.PartiallyShipped;+ order.ShippingStatusId = shipments.All(x => x.ShippedDateUtc != null) ? ShippingStatus.Shipped : ShippingStatus.PartiallyShipped;}await _orderService.UpdateOrder(order);@@ -62,7 +59,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.ShippingNote = $"Shipment #{request.Shipment.ShipmentNumber} has been sent",DisplayToCustomer = false,CreatedOnUtc = DateTime.UtcNow,- OrderId = order.Id,+ OrderId = order.Id});if (request.NotifyCustomer)@@ -71,7 +68,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Shippingawait _messageProviderService.SendShipmentSentCustomerMessage(request.Shipment, order);}//check order status- await _mediator.Send(new CheckOrderStatusCommand() { Order = order });+ await _mediator.Send(new CheckOrderStatusCommand() { Order = order }, cancellationToken);//eventawait _mediator.PublishShipmentSent(request.Shipment);diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.csindex e0958a65e..4c5c188d3 100644--- a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs@@ -27,38 +27,35 @@ namespace Grand.Business.Checkout.Events.Orderspublic Task Handle(OrderPlacedEvent notification, CancellationToken cancellationToken){//insert product also purchased- InsertProductAlsoPurchased(notification.Order);+ _ = InsertProductAlsoPurchased(notification.Order);//update customer- UpdateCustomer(notification.Order);-+ _ = UpdateCustomer(notification.Order);//Insert Loyalty Points History- InsertLoyaltyPointsHistory(notification.Order);-+ _ = InsertLoyaltyPointsHistory(notification.Order);return Task.CompletedTask;}- protected Task InsertProductAlsoPurchased(Order order)+ private Task InsertProductAlsoPurchased(Order order){foreach (var item in order.OrderItems){foreach (var it in order.OrderItems.Where(x => x.ProductId != item.ProductId)){- var productPurchase = new ProductAlsoPurchased();- productPurchase.ProductId = item.ProductId;- productPurchase.OrderId = order.Id;- productPurchase.CreatedOrderOnUtc = order.CreatedOnUtc;- productPurchase.Quantity = it.Quantity;- productPurchase.StoreId = order.StoreId;- productPurchase.ProductId2 = it.ProductId;+ var productPurchase = new ProductAlsoPurchased {+ ProductId = item.ProductId,+ OrderId = order.Id,+ CreatedOrderOnUtc = order.CreatedOnUtc,+ Quantity = it.Quantity,+ StoreId = order.StoreId,+ ProductId2 = it.ProductId+ };_productAlsoPurchasedRepository.InsertAsync(productPurchase);}}return Task.CompletedTask;--}- protected Task UpdateCustomer(Order order)+ private Task UpdateCustomer(Order order){//Updated field "free shipping" after added a new order_customerService.UpdateCustomerField(order.CustomerId, x => x.FreeShipping, false);@@ -75,7 +72,7 @@ namespace Grand.Business.Checkout.Events.Ordersreturn Task.CompletedTask;}- protected Task InsertLoyaltyPointsHistory(Order order)+ private Task InsertLoyaltyPointsHistory(Order order){//loyalty points historyif (order.RedeemedLoyaltyPointsAmount > 0)diff --git a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.csindex efbd0a33e..e26f46795 100644--- a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs@@ -27,7 +27,7 @@ namespace Grand.Business.Checkout.Events.Shippingpublic async Task Handle(EntityDeleted<Shipment> notification, CancellationToken cancellationToken){- //reverse booked invetory+ //reverse booked inventoryforeach (var shipmentItem in notification.Entity.ShipmentItems){await _inventoryManageService.ReverseBookedInventory(notification.Entity, shipmentItem);@@ -40,15 +40,13 @@ namespace Grand.Business.Checkout.Events.Shippingforeach (var item in notification.Entity.ShipmentItems){var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem != null)- {- orderItem.ShipQty -= item.Quantity;- orderItem.OpenQty += item.Quantity;- orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;- }+ if (orderItem == null) continue;+ orderItem.ShipQty -= item.Quantity;+ orderItem.OpenQty += item.Quantity;+ orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;}- if (!order.OrderItems.Where(x => x.ShipQty > 0).Any())+ if (!order.OrderItems.Any(x => x.ShipQty > 0)){order.ShippingStatusId = ShippingStatus.Pending;}@@ -61,9 +59,9 @@ namespace Grand.Business.Checkout.Events.Shippingvar shipments = await _shipmentService.GetShipmentsByOrder(order.Id);if (shipments.Any()){- if (shipments.Where(x => x.ShippedDateUtc == null).Any())+ if (shipments.Any(x => x.ShippedDateUtc == null))order.ShippingStatusId = ShippingStatus.PreparedToShipped;- if (shipments.Where(x => x.ShippedDateUtc != null).Any())+ if (shipments.Any(x => x.ShippedDateUtc != null))order.ShippingStatusId = ShippingStatus.PartiallyShipped;}}diff --git a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.csindex 8f63987c3..8c1155186 100644--- a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs@@ -30,12 +30,10 @@ namespace Grand.Business.Checkout.Events.Shippingforeach (var item in notification.Entity.ShipmentItems){var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem != null)- {- orderItem.ShipQty += item.Quantity;- orderItem.OpenQty -= item.Quantity;- orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;- }+ if (orderItem == null) continue;+ orderItem.ShipQty += item.Quantity;+ orderItem.OpenQty -= item.Quantity;+ orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;}if (order.ShippingStatusId == ShippingStatus.Pending)diff --git a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.csindex 4ca30bc34..dc1a3b798 100644--- a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs@@ -3,7 +3,7 @@ using Grand.Domain.Orders;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.Shipping+namespace Grand.Business.Checkout.Events.ShoppingCart{/// <summary>/// Update order itemsdiff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.csindex e5e61092f..f182d12bc 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs@@ -12,10 +12,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (order == null)throw new ArgumentNullException(nameof(request.Order));- if (order.OrderStatusId == (int)OrderStatusSystem.Pending)- return Task.FromResult(true);-- return Task.FromResult(false);+ return Task.FromResult(order.OrderStatusId == (int)OrderStatusSystem.Pending);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.csindex 95b7a275c..2e9834d60 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs@@ -20,15 +20,11 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionStatus == TransactionStatus.Canceled ||- paymentTransaction.TransactionStatus == TransactionStatus.Pending)+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Pending)return false;- if (paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&- await _paymentService.SupportCapture(paymentTransaction.PaymentMethodSystemName))- return true;-- return false;+ return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&+ await _paymentService.SupportCapture(paymentTransaction.PaymentMethodSystemName);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.csindex cde62e90b..888b373ba 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs@@ -12,13 +12,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionStatus == TransactionStatus.Canceled)- return Task.FromResult(false);-- if (paymentTransaction.TransactionStatus == TransactionStatus.Pending)- return Task.FromResult(true);-- return Task.FromResult(false);+ return paymentTransaction.TransactionStatus == TransactionStatus.Canceled ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Pending);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.csindex d0422246a..2af4804fd 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs@@ -12,12 +12,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (- paymentTransaction.TransactionStatus == TransactionStatus.Canceled ||- paymentTransaction.TransactionStatus == TransactionStatus.Paid ||- paymentTransaction.TransactionStatus == TransactionStatus.Refunded ||- paymentTransaction.TransactionStatus == TransactionStatus.PartiallyRefunded ||- paymentTransaction.TransactionStatus == TransactionStatus.Voided)+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Paid or TransactionStatus.Refunded or TransactionStatus.PartiallyRefunded or TransactionStatus.Voided)return false;return await Task.FromResult(true);diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.csindex 068f77a4d..ec1d11ea4 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs@@ -17,21 +17,11 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction.TransactionAmount == 0)return Task.FromResult(false);- double canBePaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;+ var canBePaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;if (canBePaid <= 0)return Task.FromResult(false);- if (amountToPaid > canBePaid)- return Task.FromResult(false);-- if (paymentTransaction.TransactionStatus == TransactionStatus.PartialPaid ||- paymentTransaction.TransactionStatus == TransactionStatus.Pending ||- paymentTransaction.TransactionStatus == TransactionStatus.PartiallyRefunded ||- paymentTransaction.TransactionStatus == TransactionStatus.Refunded- )- return Task.FromResult(true);-- return Task.FromResult(false);+ return amountToPaid > canBePaid ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.PartialPaid or TransactionStatus.Pending or TransactionStatus.PartiallyRefunded or TransactionStatus.Refunded);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.csindex 9cf61df04..8547028ea 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs@@ -17,19 +17,11 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction.TransactionAmount == 0)return Task.FromResult(false);- double canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;+ var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;if (canBeRefunded <= 0)return Task.FromResult(false);- if (amountToRefund > canBeRefunded)- return Task.FromResult(false);-- if (paymentTransaction.TransactionStatus == TransactionStatus.Paid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartialPaid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartiallyRefunded)- return Task.FromResult(true);-- return Task.FromResult(false);+ return amountToRefund > canBeRefunded ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.csindex 2eca3faa4..71363d198 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs@@ -29,20 +29,15 @@ namespace Grand.Business.Checkout.Queries.Handlers.Orders//if (order.OrderStatus == OrderStatus.Cancelled)// return false;- double canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;+ var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;if (canBeRefunded <= 0)return false;if (amountToRefund > canBeRefunded)return false;- if ((paymentTransaction.TransactionStatus == TransactionStatus.Paid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartialPaid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartiallyRefunded) &&- await _paymentService.SupportPartiallyRefund(paymentTransaction.PaymentMethodSystemName))- return true;-- return false;+ return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded &&+ await _paymentService.SupportPartiallyRefund(paymentTransaction.PaymentMethodSystemName);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.csindex 95c9f13c3..47797d3b7 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs@@ -16,13 +16,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersreturn Task.FromResult(false);//refund cannot be made if previously a partial refund has been already done. only other partial refund can be made in this case- if (paymentTransaction.RefundedAmount > 0)- return Task.FromResult(false);-- if (paymentTransaction.TransactionStatus == TransactionStatus.Paid)- return Task.FromResult(true);-- return Task.FromResult(false);+ return paymentTransaction.RefundedAmount > 0 ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Paid);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.csindex 4497f2b64..f49d49cba 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs@@ -28,14 +28,8 @@ namespace Grand.Business.Checkout.Queries.Handlers.Orders//if (order.OrderStatus == OrderStatus.Cancelled)// return false;-- if ((paymentTransaction.TransactionStatus == TransactionStatus.Paid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartialPaid ||- paymentTransaction.TransactionStatus == TransactionStatus.PartiallyRefunded) &&- await _paymentService.SupportRefund(paymentTransaction.PaymentMethodSystemName))- return true;-- return false;+ return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded &&+ await _paymentService.SupportRefund(paymentTransaction.PaymentMethodSystemName);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.csindex ffdf938c1..43dace663 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs@@ -12,13 +12,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction == null)throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionAmount == 0)- return Task.FromResult(false);-- if (paymentTransaction.TransactionStatus == TransactionStatus.Authorized)- return Task.FromResult(true);-- return Task.FromResult(false);+ return paymentTransaction.TransactionAmount == 0 ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Authorized);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.csindex 0ef946abc..55487eae8 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs@@ -23,11 +23,8 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (paymentTransaction.TransactionAmount == 0)return false;- if (paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&- await _paymentService.SupportVoid(paymentTransaction.PaymentMethodSystemName))- return true;-- return false;+ return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&+ await _paymentService.SupportVoid(paymentTransaction.PaymentMethodSystemName);}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.csindex 337c86bf6..790d95203 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs@@ -17,8 +17,8 @@ namespace Grand.Business.Checkout.Queries.Handlers.Orderspublic async Task<int> Handle(GetMerchandiseReturnCountQuery request, CancellationToken cancellationToken){return await Task.FromResult(- _merchandiseReturnRepository.Table.Where(x => x.MerchandiseReturnStatusId == request.RequestStatusId &&- (string.IsNullOrEmpty(request.StoreId) || x.StoreId == request.StoreId)).Count());+ _merchandiseReturnRepository.Table.Count(x => x.MerchandiseReturnStatusId == request.RequestStatusId &&+ (string.IsNullOrEmpty(request.StoreId) || x.StoreId == request.StoreId)));}}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.csindex 800d167f6..250653c38 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs@@ -90,8 +90,8 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (!string.IsNullOrEmpty(request.OrderGuid)){- if (Guid.TryParse(request.OrderGuid, out Guid orderguid))- query = query.Where(o => o.OrderGuid == orderguid);+ if (Guid.TryParse(request.OrderGuid, out Guid orderGuid))+ query = query.Where(o => o.OrderGuid == orderGuid);}if (!string.IsNullOrEmpty(request.OrderCode)){diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.csindex cde351c6a..5bf4ba27a 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs@@ -25,13 +25,11 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersvar vendors = new List<Vendor>();foreach (var vendorKey in order.OrderItems.GroupBy(x => x.VendorId)){- if (!string.IsNullOrEmpty(vendorKey.Key))+ if (string.IsNullOrEmpty(vendorKey.Key)) continue;+ var vendor = await _vendorService.GetVendorById(vendorKey.Key);+ if (vendor is { Deleted: false, Active: true }){- var vendor = await _vendorService.GetVendorById(vendorKey.Key);- if (vendor != null && !vendor.Deleted && vendor.Active)- {- vendors.Add(vendor);- }+ vendors.Add(vendor);}}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.csindex 2f13c083f..0298ab378 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs@@ -49,15 +49,8 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersreturn false;var qtyDelivery = shipments.Where(x => x.DeliveryDateUtc.HasValue).SelectMany(x => x.ShipmentItems).Where(x => x.OrderItemId == item.Id).Sum(x => x.Quantity);- var merchandiseReturns = (await _mediator.Send(new GetMerchandiseReturnQuery() { OrderItemId = item.Id })).ToList();- int qtyReturn = 0;- foreach (var rr in merchandiseReturns)- {- foreach (var rrItem in rr.MerchandiseReturnItems)- {- qtyReturn += rrItem.Quantity;- }- }+ var merchandiseReturns = (await _mediator.Send(new GetMerchandiseReturnQuery { OrderItemId = item.Id }, cancellationToken)).ToList();+ var qtyReturn = merchandiseReturns.Sum(rr => rr.MerchandiseReturnItems.Sum(rrItem => rrItem.Quantity));if (!product.NotReturnable && qtyDelivery - qtyReturn > 0)return true;diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.csindex a81e07a1a..b63c92413 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Checkout attribute helper/// </summary>- public partial class CheckoutAttributeFormatter : ICheckoutAttributeFormatter+ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter{private readonly IWorkContext _workContext;private readonly ICheckoutAttributeParser _checkoutAttributeParser;@@ -42,14 +42,14 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// </summary>/// <param name="customAttributes">Attributes</param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,Customer customer,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true,bool renderPrices = true,bool allowHyperlinks = true)@@ -60,7 +60,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesreturn result.ToString();var attributes = await _checkoutAttributeParser.ParseCheckoutAttributes(customAttributes);- for (int i = 0; i < attributes.Count; i++)+ for (var i = 0; i < attributes.Count; i++){var attribute = attributes[i];var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();@@ -73,13 +73,13 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes//no valuesif (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox){- //multiline textbox+ //multiline text boxvar attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);//encode (if required)if (htmlEncode)attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));- //we never encode multiline textbox input+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input}else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload){@@ -91,16 +91,19 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesif (allowHyperlinks){//hyperlinks are allowed- var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentHost.Url.TrimEnd('/'), downloadGuid);- attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id));+ var downloadLink =+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";+ attributeText =+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";}- formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);+ formattedAttribute = $"{attributeName}: {attributeText}";}}else{- //other attributes (textbox, datepicker)- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);+ //other attributes (text box, datepicker)+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);@@ -108,18 +111,19 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes}else{- var attributeValue = attribute.CheckoutAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();+ var attributeValue = attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr);if (attributeValue != null){- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id));+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}";if (renderPrices){- double priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer)).checkoutPrice;- double priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);+ var priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer)).checkoutPrice;+ var priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);if (priceAdjustmentBase > 0){- string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);- formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);+ var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);+ formattedAttribute += $" [+{priceAdjustmentStr}]";}}}@@ -128,16 +132,13 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesformattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}- if (!String.IsNullOrEmpty(formattedAttribute))- {- if (i != 0 || j != 0)- result.Append(serapator);- result.Append(formattedAttribute);- }+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}}-return result.ToString();}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.csindex d1a8f19c4..f57e8ff3a 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Checkout attribute parser/// </summary>- public partial class CheckoutAttributeParser : ICheckoutAttributeParser+ public class CheckoutAttributeParser : ICheckoutAttributeParser{private readonly ICheckoutAttributeService _checkoutAttributeService;@@ -19,7 +19,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Gets selected checkout attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Selected checkout attributes</returns>public virtual async Task<IList<CheckoutAttribute>> ParseCheckoutAttributes(IList<CustomAttribute> customAttributes){@@ -56,15 +56,8 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributescontinue;var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- foreach (var valueStr in valuesStr)- {- if (!string.IsNullOrEmpty(valueStr))- {- var value = attribute.CheckoutAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();- if (value != null)- values.Add(value);- }- }+ values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr)+ select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);}return values;}@@ -87,15 +80,8 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributescontinue;var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- foreach (var valueStr in valuesStr)- {- if (!string.IsNullOrEmpty(valueStr))- {- var value = attribute.CheckoutAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();- if (value != null)- values.Add((attribute, value));- }- }+ values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr)+ select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select (attribute, value));}return values;}@@ -103,16 +89,15 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="ca">Checkout attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>public virtual IList<CustomAttribute> AddCheckoutAttribute(IList<CustomAttribute> customAttributes, CheckoutAttribute ca, string value){- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();+ customAttributes ??= new List<CustomAttribute>();- customAttributes.Add(new CustomAttribute() { Key = ca.Id, Value = value });+ customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });return customAttributes;}@@ -124,23 +109,15 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <returns>Updated attributes</returns>public virtual async Task<IList<CustomAttribute>> EnsureOnlyActiveAttributes(IList<CustomAttribute> customAttributes, IList<ShoppingCartItem> cart){- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();+ customAttributes ??= new List<CustomAttribute>();- if (!cart.RequiresShipping())- {- var checkoutAttributeIdsToRemove = new List<string>();- var attributes = await ParseCheckoutAttributes(customAttributes);- foreach (var ca in attributes)- if (ca.ShippableProductRequired)- checkoutAttributeIdsToRemove.Add(ca.Id);+ if (cart.RequiresShipping()) return customAttributes;+ var attributes = await ParseCheckoutAttributes(customAttributes);+ var checkoutAttributeIdsToRemove = (from ca in attributes where ca.ShippableProductRequired select ca.Id).ToList();- foreach (var id in checkoutAttributeIdsToRemove)- {- var attr = customAttributes.FirstOrDefault(x => x.Key == id);- if (attr != null)- customAttributes.Remove(attr);- }+ foreach (var attr in checkoutAttributeIdsToRemove.Select(id => customAttributes.FirstOrDefault(x => x.Key == id)).Where(attr => attr != null))+ {+ customAttributes.Remove(attr);}return customAttributes;@@ -149,15 +126,14 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// Check whether condition of some attribute is met./// </summary>/// <param name="attribute">Checkout attribute</param>- /// <param name="selectedAttributes">Selected attributes</param>+ /// <param name="customAttributes">Selected attributes</param>/// <returns>Result</returns>public virtual async Task<bool?> IsConditionMet(CheckoutAttribute attribute, IList<CustomAttribute> customAttributes){if (attribute == null)throw new ArgumentNullException(nameof(attribute));- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();+ customAttributes ??= new List<CustomAttribute>();var conditionAttribute = attribute.ConditionAttribute;if (!conditionAttribute.Any())@@ -181,10 +157,9 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesvar allFound = true;foreach (var t1 in valuesThatShouldBeSelected){- bool found = false;- foreach (var t2 in selectedValues)- if (t1 == t2)- found = true;+ var found = false;+ foreach (var t2 in selectedValues.Where(t2 => t1 == t2))+ found = true;if (!found)allFound = false;}@@ -195,7 +170,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Remove an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="attribute">Checkout attribute</param>/// <returns>Updated</returns>public virtual IList<CustomAttribute> RemoveCheckoutAttribute(IList<CustomAttribute> customAttributes, CheckoutAttribute attribute)diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.csindex 830bfe288..259258d8a 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <summary>/// Checkout attribute service/// </summary>- public partial class CheckoutAttributeService : ICheckoutAttributeService+ public class CheckoutAttributeService : ICheckoutAttributeService{#region Fields@@ -46,16 +46,16 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes#region Methods-/// <summary>/// Gets all checkout attributes/// </summary>/// <param name="storeId">Store identifier</param>- /// <param name="excludeShippableAttributes">A value indicating whether we should exlude shippable attributes</param>+ /// <param name="excludeShippableAttributes">A value indicating whether we should exclude shippable attributes</param>+ /// <param name="ignoreAcl"></param>/// <returns>Checkout attributes</returns>- public virtual async Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "", bool excludeShippableAttributes = false, bool ignorAcl = false)+ public virtual async Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "", bool excludeShippableAttributes = false, bool ignoreAcl = false){- string key = string.Format(CacheKey.CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes, ignorAcl);+ var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes, ignoreAcl);return await _cacheBase.GetAsync(key, async () =>{var query = from p in _checkoutAttributeRepository.Table@@ -63,10 +63,10 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesquery = query.OrderBy(c => c.DisplayOrder);- if ((!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||- (!ignorAcl && !CommonHelper.IgnoreAcl))+ if ((!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||+ (!ignoreAcl && !CommonHelper.IgnoreAcl)){- if (!ignorAcl && !CommonHelper.IgnoreAcl)+ if (!ignoreAcl && !CommonHelper.IgnoreAcl){var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();query = from p in query@@ -74,7 +74,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributesselect p;}//Store acl- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){query = from p in querywhere !p.LimitedToStores || p.Stores.Contains(storeId)@@ -97,7 +97,7 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes/// <returns>Checkout attribute</returns>public virtual Task<CheckoutAttribute> GetCheckoutAttributeById(string checkoutAttributeId){- string key = string.Format(CacheKey.CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId);+ var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId);return _cacheBase.GetAsync(key, () => _checkoutAttributeRepository.GetByIdAsync(checkoutAttributeId));}diff --git a/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs b/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.csindex 3f2e9fec5..3c9423dba 100644--- a/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs+++ b/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs@@ -53,7 +53,7 @@ namespace Grand.Business.Checkout.Services.ExportImportnew PropertyByName<Order>("BillingEmail", p=>p.BillingAddress?.Email),new PropertyByName<Order>("BillingCompany", p=>p.BillingAddress?.Company),new PropertyByName<Order>("BillingVatNumber", p=>p.BillingAddress?.VatNumber),- new PropertyByName<Order>("BillingCountry",p=>p.BillingAddress!=null ? (_countryService.GetCountryById(p.BillingAddress.CountryId)).Result?.Name : ""),+ new PropertyByName<Order>("BillingCountry",p=>p.BillingAddress!=null ? _countryService.GetCountryById(p.BillingAddress.CountryId).Result?.Name : ""),new PropertyByName<Order>("BillingCity", p=>p.BillingAddress?.City),new PropertyByName<Order>("BillingAddress1",p=>p.BillingAddress?.Address1),new PropertyByName<Order>("BillingAddress2", p=>p.BillingAddress?.Address2),@@ -65,7 +65,7 @@ namespace Grand.Business.Checkout.Services.ExportImportnew PropertyByName<Order>("ShippingEmail", p=>p.ShippingAddress?.Email),new PropertyByName<Order>("ShippingCompany", p=>p.ShippingAddress?.Company),new PropertyByName<Order>("ShippingVatNumber", p=>p.ShippingAddress?.VatNumber),- new PropertyByName<Order>("ShippingCountry",p=>p.ShippingAddress!=null ? (_countryService.GetCountryById(p.ShippingAddress.CountryId)).Result?.Name : ""),+ new PropertyByName<Order>("ShippingCountry",p=>p.ShippingAddress!=null ? _countryService.GetCountryById(p.ShippingAddress.CountryId).Result?.Name : ""),new PropertyByName<Order>("ShippingCity", p=>p.ShippingAddress?.City),new PropertyByName<Order>("ShippingAddress1", p=>p.ShippingAddress?.Address1),new PropertyByName<Order>("ShippingAddress2", p=>p.ShippingAddress?.Address2),diff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.csindex 5f665b6a8..7cdf2a5c5 100644--- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs+++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Checkout.Services.GiftVouchers/// <summary>/// Gift voucher service/// </summary>- public partial class GiftVoucherService : IGiftVoucherService+ public class GiftVoucherService : IGiftVoucherService{#region Fields@@ -51,11 +51,11 @@ namespace Grand.Business.Checkout.Services.GiftVouchers/// <summary>/// Gets all gift vouchers/// </summary>- /// <param name="purchasedWithOrderId">Associated order ID; null to load all records</param>+ /// <param name="purchasedWithOrderItemId">Associated order ID; null to load all records</param>/// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>/// <param name="isGiftVoucherActivated">Value indicating whether gift voucher is activated; null to load all records</param>- /// <param name="giftVoucherCouponCode">Gift voucher coupon code; nullto load all records</param>+ /// <param name="giftVoucherCouponCode">Gift voucher coupon code; null to load all records</param>/// <param name="recipientName">Recipient name; null to load all records</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>@@ -66,7 +66,7 @@ namespace Grand.Business.Checkout.Services.GiftVouchersstring recipientName = null,int pageIndex = 0, int pageSize = int.MaxValue){- var model = new GetGiftVoucherQuery() {+ var model = new GetGiftVoucherQuery {CreatedFromUtc = createdFromUtc,CreatedToUtc = createdToUtc,Code = giftVoucherCouponCode,diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.csindex 8c0a2957f..560ff1007 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// LoyaltyPoints service interface/// </summary>- public partial class LoyaltyPointsService : ILoyaltyPointsService+ public class LoyaltyPointsService : ILoyaltyPointsService{#region Fields@@ -43,21 +43,21 @@ namespace Grand.Business.Checkout.Services.Orders/// Get loyalty points for customer/// </summary>/// <param name="customerId">Customer Id</param>+ /// <param name="storeId">Store ident</param>/// <returns>PointsBalance</returns>-public virtual async Task<int> GetLoyaltyPointsBalance(string customerId, string storeId){var query = from p in _rphRepository.Tableselect p;- if (!String.IsNullOrEmpty(customerId))+ if (!string.IsNullOrEmpty(customerId))query = query.Where(rph => rph.CustomerId == customerId);if (!_loyaltyPointsSettings.PointsAccumulatedForAllStores)query = query.Where(rph => rph.StoreId == storeId);query = query.OrderByDescending(rph => rph.CreatedOnUtc);var lastRph = await Task.FromResult(query.FirstOrDefault());- return lastRph != null ? lastRph.PointsBalance : 0;+ return lastRph?.PointsBalance ?? 0;}@@ -66,11 +66,11 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="customerId">Customer Id</param>/// <param name="points">Points</param>+ /// <param name="storeId">Store ident</param>/// <param name="message">Message</param>/// <param name="usedWithOrderId">Used with OrderId</param>/// <param name="usedAmount">Used amount</param>/// <returns>LoyaltyPointsHistory</returns>-public virtual async Task<LoyaltyPointsHistory> AddLoyaltyPointsHistory(string customerId, int points, string storeId, string message = "",string usedWithOrderId = "", double usedAmount = 0){diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.csindex cadd33088..bcd1810ea 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs@@ -13,10 +13,10 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Merchandise return service/// </summary>- public partial class MerchandiseReturnService : IMerchandiseReturnService+ public class MerchandiseReturnService : IMerchandiseReturnService{#region Fields- private static readonly Object _locker = new object();+ private static readonly object Locker = new();private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;private readonly IRepository<MerchandiseReturnAction> _merchandiseReturnActionRepository;@@ -36,7 +36,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="merchandiseReturnActionRepository">Merchandise return action repository</param>/// <param name="merchandiseReturnReasonRepository">Merchandise return reason repository</param>/// <param name="merchandiseReturnNoteRepository">Merchandise return note repository</param>- /// <param name="_cacheBase">Cache base</param>+ /// <param name="cacheBase">Cache</param>/// <param name="mediator">Mediator</param>public MerchandiseReturnService(IRepository<MerchandiseReturn> merchandiseReturnRepository,IRepository<MerchandiseReturnAction> merchandiseReturnActionRepository,@@ -75,7 +75,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>Merchandise return</returns>public virtual Task<MerchandiseReturn> GetMerchandiseReturnById(int id){- return Task.FromResult(_merchandiseReturnRepository.Table.Where(x => x.ReturnNumber == id).FirstOrDefault());+ return Task.FromResult(_merchandiseReturnRepository.Table.FirstOrDefault(x => x.ReturnNumber == id));}/// <summary>@@ -96,7 +96,7 @@ namespace Grand.Business.Checkout.Services.Ordersstring orderItemId = "", string vendorId = "", string ownerId = "", MerchandiseReturnStatus? rs = null,int pageIndex = 0, int pageSize = int.MaxValue, DateTime? createdFromUtc = null, DateTime? createdToUtc = null){- var model = new GetMerchandiseReturnQuery()+ var model = new GetMerchandiseReturnQuery{CreatedFromUtc = createdFromUtc,CreatedToUtc = createdToUtc,@@ -107,7 +107,7 @@ namespace Grand.Business.Checkout.Services.OrdersOwnerId = ownerId,StoreId = storeId,OrderItemId = orderItemId,- Rs = rs,+ Rs = rs};var query = await _mediator.Send(model);@@ -148,7 +148,7 @@ namespace Grand.Business.Checkout.Services.Ordersif (merchandiseReturn == null)throw new ArgumentNullException(nameof(merchandiseReturn));- lock (_locker)+ lock (Locker){var requestExists = _merchandiseReturnRepository.Table.FirstOrDefault();var requestNumber = requestExists != null ? _merchandiseReturnRepository.Table.Max(x => x.ReturnNumber) + 1 : 1;@@ -239,7 +239,7 @@ namespace Grand.Business.Checkout.Services.Ordersawait _mediator.EntityDeleted(merchandiseReturnAction);}/// <summary>- /// Delete a merchandise return reaspn+ /// Delete a merchandise return reason/// </summary>/// <param name="merchandiseReturnReason">Merchandise return reason</param>public virtual async Task DeleteMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)@@ -258,9 +258,9 @@ namespace Grand.Business.Checkout.Services.Orders}/// <summary>- /// Gets all merchandise return reaspns+ /// Gets all merchandise return reasons/// </summary>- /// <returns>Merchandise return reaspns</returns>+ /// <returns>Merchandise return reasons</returns>public virtual async Task<IList<MerchandiseReturnReason>> GetAllMerchandiseReturnReasons(){return await _cacheBase.GetAsync(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY, async () =>@@ -273,19 +273,19 @@ namespace Grand.Business.Checkout.Services.Orders}/// <summary>- /// Gets a merchandise return reaspn+ /// Gets a merchandise return reasons/// </summary>- /// <param name="merchandiseReturnReasonId">Merchandise return reaspn identifier</param>- /// <returns>Merchandise return reaspn</returns>+ /// <param name="merchandiseReturnReasonId">Merchandise return reasons identifier</param>+ /// <returns>Merchandise return reasons</returns>public virtual Task<MerchandiseReturnReason> GetMerchandiseReturnReasonById(string merchandiseReturnReasonId){return _merchandiseReturnReasonRepository.GetByIdAsync(merchandiseReturnReasonId);}/// <summary>- /// Inserts a merchandise return reaspn+ /// Inserts a merchandise return reasons/// </summary>- /// <param name="merchandiseReturnReason">Merchandise return reaspn</param>+ /// <param name="merchandiseReturnReason">Merchandise return reasons</param>public virtual async Task InsertMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason){if (merchandiseReturnReason == null)@@ -301,9 +301,9 @@ namespace Grand.Business.Checkout.Services.Orders}/// <summary>- /// Updates the merchandise return reaspn+ /// Updates the merchandise return reasons/// </summary>- /// <param name="merchandiseReturnReason">Merchandise return reaspn</param>+ /// <param name="merchandiseReturnReason">Merchandise return reasons</param>public virtual async Task UpdateMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason){if (merchandiseReturnReason == null)@@ -373,7 +373,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>MerchandiseReturnNote</returns>public virtual Task<MerchandiseReturnNote> GetMerchandiseReturnNote(string merchandiseReturnNoteId){- return Task.FromResult(_merchandiseReturnNoteRepository.Table.Where(x => x.Id == merchandiseReturnNoteId).FirstOrDefault());+ return Task.FromResult(_merchandiseReturnNoteRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnNoteId));}#endregiondiff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.csindex d8a321992..6ac568cee 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -28,7 +28,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Order calc service/// </summary>- public partial class OrderCalculationService : IOrderCalculationService+ public class OrderCalculationService : IOrderCalculationService{#region Fields@@ -136,8 +136,7 @@ namespace Grand.Business.Checkout.Services.Orders{var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal &&- !allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any())+ discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal && allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,@@ -178,8 +177,7 @@ namespace Grand.Business.Checkout.Services.Orders{var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToShipping &&- !allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any())+ discount.DiscountTypeId == DiscountType.AssignedToShipping && allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,@@ -224,13 +222,12 @@ namespace Grand.Business.Checkout.Services.Orders{var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderTotal &&- !allowedDiscounts.Where(x => x.DiscountId == discount.Id).Any())+ discount.DiscountTypeId == DiscountType.AssignedToOrderTotal && allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode,+ CouponCode = validDiscount.CouponCode});}}@@ -252,6 +249,8 @@ namespace Grand.Business.Checkout.Services.Orders/// Get active gift vouchers that are applied by a customer/// </summary>/// <param name="customer">Customer</param>+ /// <param name="currency">Currency</param>+ /// <param name="store">Store</param>/// <returns>Active gift vouchers</returns>private async Task<IList<GiftVoucher>> GetActiveGiftVouchers(Customer customer, Currency currency, Store store){@@ -259,15 +258,11 @@ namespace Grand.Business.Checkout.Services.Ordersif (customer == null)return result;- string[] couponCodes = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);+ var couponCodes = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);foreach (var couponCode in couponCodes){var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(isGiftVoucherActivated: true, giftVoucherCouponCode: couponCode);- foreach (var gc in giftVouchers)- {- if (gc.IsGiftVoucherValid(currency, store))- result.Add(gc);- }+ result.AddRange(giftVouchers.Where(gc => gc.IsGiftVoucherValid(currency, store)));}return result;@@ -277,17 +272,11 @@ namespace Grand.Business.Checkout.Services.Orders#region Methods-/// <summary>/// Gets shopping cart subtotal/// </summary>/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>- /// <param name="discountAmount">Applied discount amount</param>- /// <param name="appliedDiscount">Applied discount</param>- /// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>- /// <param name="subTotalWithDiscount">Sub total (with discount)</param>- /// <param name="taxRates">Tax rates (of order sub total)</param>public virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts,double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax)@@ -314,31 +303,26 @@ namespace Grand.Business.Checkout.Services.Orderscontinue;var subtotal = await _pricingService.GetSubTotal(shoppingCartItem, product);- double sciSubTotal = subtotal.subTotal;+ var sciSubTotal = subtotal.subTotal;- double taxRate;var pricesExcl = await _taxService.GetProductPrice(product, sciSubTotal, false, customer);- double sciExclTax = pricesExcl.productprice;+ var sciExclTax = pricesExcl.productprice;- var pricesIncl = await _taxService.GetProductPrice(product, sciSubTotal, true, customer);- double sciInclTax = pricesIncl.productprice;- taxRate = pricesIncl.taxRate;+ var (sciInclTax, taxRate) = await _taxService.GetProductPrice(product, sciSubTotal, true, customer);subTotalExclTaxWithoutDiscount += sciExclTax;subTotalInclTaxWithoutDiscount += sciInclTax;//tax rates- double sciTax = sciInclTax - sciExclTax;- if (taxRate > 0 && sciTax > 0)+ var sciTax = sciInclTax - sciExclTax;+ if (!(taxRate > 0) || !(sciTax > 0)) continue;+ if (!taxRates.ContainsKey(taxRate)){- if (!taxRates.ContainsKey(taxRate))- {- taxRates.Add(taxRate, sciTax);- }- else- {- taxRates[taxRate] = taxRates[taxRate] + sciTax;- }+ taxRates.Add(taxRate, sciTax);+ }+ else+ {+ taxRates[taxRate] += sciTax;}}@@ -349,30 +333,25 @@ namespace Grand.Business.Checkout.Services.Ordersvar attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes);foreach (var attributeValue in attributeValues){- double taxRate;var checkoutAttributePriceExclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer);- double caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, _workContext.WorkingCurrency);+ var caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, _workContext.WorkingCurrency);- var checkoutAttributePriceInclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer);- double caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceInclTax.checkoutPrice, _workContext.WorkingCurrency);-- taxRate = checkoutAttributePriceInclTax.taxRate;+ var (checkoutPrice, taxRate) = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer);+ var caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice, _workContext.WorkingCurrency);subTotalExclTaxWithoutDiscount += caExclTax;subTotalInclTaxWithoutDiscount += caInclTax;//tax rates- double caTax = caInclTax - caExclTax;- if (taxRate > 0 && caTax > 0)+ var caTax = caInclTax - caExclTax;+ if (!(taxRate > 0) || !(caTax > 0)) continue;+ if (!taxRates.ContainsKey(taxRate)){- if (!taxRates.ContainsKey(taxRate))- {- taxRates.Add(taxRate, caTax);- }- else- {- taxRates[taxRate] = taxRates[taxRate] + caTax;- }+ taxRates.Add(taxRate, caTax);+ }+ else+ {+ taxRates[taxRate] += caTax;}}}@@ -390,39 +369,37 @@ namespace Grand.Business.Checkout.Services.Orders//We calculate discount amount on order subtotal excl tax (discount first)//calculate discount amount ('Applied to order subtotal' discount)var orderSubtotalDiscount = await GetOrderSubtotalDiscount(customer, _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);- double discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;+ var discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;appliedDiscounts = orderSubtotalDiscount.appliedDiscounts;if (subTotalExclTaxWithoutDiscount < discountAmountExclTax)discountAmountExclTax = subTotalExclTaxWithoutDiscount;- double discountAmountInclTax = discountAmountExclTax;+ var discountAmountInclTax = discountAmountExclTax;//subtotal with discount (excl tax)- double subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;- double subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;+ var subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;+ var subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;//add tax for shopping items & checkout attributesvar tempTaxRates = new Dictionary<double, double>(taxRates);foreach (KeyValuePair<double, double> kvp in tempTaxRates){- double taxRate = kvp.Key;- double taxValue = kvp.Value;+ var taxRate = kvp.Key;+ var taxValue = kvp.Value;- if (taxValue != 0)+ if (taxValue == 0) continue;+ //discount the tax amount that applies to subtotal items+ if (subTotalExclTaxWithoutDiscount > 0){- //discount the tax amount that applies to subtotal items- if (subTotalExclTaxWithoutDiscount > 0)- {- double discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);- discountAmountInclTax += discountTax;- taxValue = taxRates[taxRate] - discountTax;- if (_shoppingCartSettings.RoundPrices)- taxValue = RoundingHelper.RoundPrice(taxValue, _workContext.WorkingCurrency);- taxRates[taxRate] = taxValue;- }-- //subtotal with discount (incl tax)- subTotalInclTaxWithDiscount += taxValue;+ var discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);+ discountAmountInclTax += discountTax;+ taxValue = taxRates[taxRate] - discountTax;+ if (_shoppingCartSettings.RoundPrices)+ taxValue = RoundingHelper.RoundPrice(taxValue, _workContext.WorkingCurrency);+ taxRates[taxRate] = taxValue;}++ //subtotal with discount (incl tax)+ subTotalInclTaxWithDiscount += taxValue;}if (_shoppingCartSettings.RoundPrices)@@ -459,17 +436,11 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>Additional shipping charge</returns>public virtual async Task<double> GetShoppingCartAdditionalShippingCharge(IList<ShoppingCartItem> cart){- double additionalShippingCharge = 0;-- bool isFreeShipping = await IsFreeShipping(cart);+ var isFreeShipping = await IsFreeShipping(cart);if (isFreeShipping)return 0;- foreach (var sci in cart)- if (sci.IsShipEnabled && !sci.IsFreeShipping)- additionalShippingCharge += _shippingSettings.AdditionalShippingChargeByQty ? (sci.AdditionalShippingChargeProduct * sci.Quantity) : sci.AdditionalShippingChargeProduct;-- return additionalShippingCharge;+ return cart.Where(sci => sci.IsShipEnabled && !sci.IsFreeShipping).Sum(sci => _shippingSettings.AdditionalShippingChargeByQty ? sci.AdditionalShippingChargeProduct * sci.Quantity : sci.AdditionalShippingChargeProduct);}/// <summary>@@ -488,45 +459,29 @@ namespace Grand.Business.Checkout.Services.Orders//check whether customer is in a customer group with free shipping appliedvar customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());- foreach (var customerGroup in customerGroups)- if (customerGroup.FreeShipping)- return true;+ if (customerGroups.Any(customerGroup => customerGroup.FreeShipping))+ {+ return true;+ }}- bool shoppingCartRequiresShipping = cart.RequiresShipping();+ var shoppingCartRequiresShipping = cart.RequiresShipping();if (!shoppingCartRequiresShipping)return true;//check whether all shopping cart items are marked as free shipping- bool allItemsAreFreeShipping = true;- foreach (var sc in cart)- {- if (sc.IsShipEnabled && !sc.IsFreeShipping)- {- allItemsAreFreeShipping = false;- break;- }- }+ var allItemsAreFreeShipping = cart.All(sc => !sc.IsShipEnabled || sc.IsFreeShipping);if (allItemsAreFreeShipping)return true;//free shipping over $X- if (_shippingSettings.FreeShippingOverXEnabled)- {- //check whether we have subtotal enough to have free shipping- var (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates) = await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);- var subTotalDiscountAmount = discountAmount;- var subTotalAppliedDiscounts = appliedDiscounts;- var subTotalWithoutDiscountBase = subTotalWithoutDiscount;- var subTotalWithDiscountBase = subTotalWithDiscount;-- if (subTotalWithDiscountBase > _shippingSettings.FreeShippingOverXValue)- return true;- }+ if (!_shippingSettings.FreeShippingOverXEnabled) return false;+ //check whether we have subtotal enough to have free shipping+ var (_, _, _, subTotalWithDiscount, _) = await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);+ return subTotalWithDiscount > _shippingSettings.FreeShippingOverXValue;//otherwise, return false- return false;}/// <summary>@@ -534,7 +489,6 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="shippingRate">Shipping rate to adjust</param>/// <param name="cart">Cart</param>- /// <param name="appliedDiscount">Applied discount</param>/// <returns>Adjusted shipping rate</returns>public virtual async Task<(double shippingRate, List<ApplyDiscount> appliedDiscounts)> AdjustShippingRate(double shippingRate, IList<ShoppingCartItem> cart){@@ -545,14 +499,13 @@ namespace Grand.Business.Checkout.Services.Ordersreturn (0, appliedDiscounts);//additional shipping charges- double additionalShippingCharge = await GetShoppingCartAdditionalShippingCharge(cart);+ var additionalShippingCharge = await GetShoppingCartAdditionalShippingCharge(cart);var adjustedRate = shippingRate + additionalShippingCharge;//discountvar customer = _workContext.CurrentCustomer;- var shippingDiscount = await GetShippingDiscount(customer, _workContext.WorkingCurrency, adjustedRate);- double discountAmount = shippingDiscount.shippingDiscount;- appliedDiscounts = shippingDiscount.appliedDiscounts;+ var (discountAmount, applyDiscounts) = await GetShippingDiscount(customer, _workContext.WorkingCurrency, adjustedRate);+ appliedDiscounts = applyDiscounts;adjustedRate -= discountAmount;@@ -574,7 +527,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>Shipping total</returns>public virtual async Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)> GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart){- bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetShoppingCartShippingTotal(cart, includingTax);}@@ -584,8 +537,6 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>- /// <param name="taxRate">Applied tax rate</param>- /// <param name="appliedDiscount">Applied discount</param>/// <returns>Shipping total</returns>public virtual async Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)> GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax){@@ -597,7 +548,7 @@ namespace Grand.Business.Checkout.Services.Ordersvar customer = _workContext.CurrentCustomer;var currency = await _currencyService.GetPrimaryExchangeRateCurrency();- bool isFreeShipping = await IsFreeShipping(cart);+ var isFreeShipping = await IsFreeShipping(cart);if (isFreeShipping)return (0, taxRate, appliedDiscounts);@@ -608,9 +559,9 @@ namespace Grand.Business.Checkout.Services.Ordersif (shippingOption != null){var rate = shippingOption.Rate;- var adjustshipingRate = await AdjustShippingRate(rate, cart);- shippingTotal = adjustshipingRate.shippingRate;- appliedDiscounts = adjustshipingRate.appliedDiscounts;+ var adjustShippingRate = await AdjustShippingRate(rate, cart);+ shippingTotal = adjustShippingRate.shippingRate;+ appliedDiscounts = adjustShippingRate.appliedDiscounts;}else{@@ -637,9 +588,7 @@ namespace Grand.Business.Checkout.Services.Ordersvar fixedRateTmp = await shippingRateMethod.GetFixedRate(shippingOptionRequest);if (fixedRateTmp.HasValue){- if (!fixedRate.HasValue)- fixedRate = 0;-+ fixedRate = 0;fixedRate += fixedRateTmp.Value;}@@ -653,23 +602,21 @@ namespace Grand.Business.Checkout.Services.Orders}}- if (shippingTotal.HasValue)- {- if (shippingTotal.Value < 0)- shippingTotal = 0;+ if (!shippingTotal.HasValue) return (null, taxRate, appliedDiscounts);+ if (shippingTotal.Value < 0)+ shippingTotal = 0;- //round- if (_shoppingCartSettings.RoundPrices)- shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value, currency);+ //round+ if (_shoppingCartSettings.RoundPrices)+ shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value, currency);- var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer);- shippingTotalTaxed = shippingPrice.shippingPrice;- taxRate = shippingPrice.taxRate;+ var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer);+ shippingTotalTaxed = shippingPrice.shippingPrice;+ taxRate = shippingPrice.taxRate;- //round- if (_shoppingCartSettings.RoundPrices)- shippingTotalTaxed = RoundingHelper.RoundPrice(shippingTotalTaxed.Value, currency);- }+ //round+ if (_shoppingCartSettings.RoundPrices)+ shippingTotalTaxed = RoundingHelper.RoundPrice(shippingTotalTaxed.Value, currency);return (shippingTotalTaxed, taxRate, appliedDiscounts);}@@ -678,7 +625,6 @@ namespace Grand.Business.Checkout.Services.Orders/// Gets tax/// </summary>/// <param name="cart">Shopping cart</param>- /// <param name="taxRates">Tax rates</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param>/// <returns>Tax total</returns>public virtual async Task<(double taxtotal, SortedDictionary<double, double> taxRates)> GetTaxTotal(IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true)@@ -689,7 +635,7 @@ namespace Grand.Business.Checkout.Services.Ordersvar taxRates = new SortedDictionary<double, double>();var customer = _workContext.CurrentCustomer;- string paymentMethodSystemName = "";+ var paymentMethodSystemName = "";if (customer != null){paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(@@ -703,33 +649,25 @@ namespace Grand.Business.Checkout.Services.Ordersvar shoppingCartSubTotal = await GetShoppingCartSubTotal(cart, false);SortedDictionary<double, double> orderSubTotalTaxRates = shoppingCartSubTotal.taxRates;- foreach (KeyValuePair<double, double> kvp in orderSubTotalTaxRates)+ foreach (var (taxRate, taxValue) in orderSubTotalTaxRates){- double taxRate = kvp.Key;- double taxValue = kvp.Value;subTotalTaxTotal += taxValue;- if (taxRate > 0 && taxValue > 0)- {- if (!taxRates.ContainsKey(taxRate))- taxRates.Add(taxRate, taxValue);- else- taxRates[taxRate] = taxRates[taxRate] + taxValue;- }+ if (!(taxRate > 0) || !(taxValue > 0)) continue;+ if (!taxRates.ContainsKey(taxRate))+ taxRates.Add(taxRate, taxValue);+ else+ taxRates[taxRate] += taxValue;}//shippingdouble shippingTax = 0;if (_taxSettings.ShippingIsTaxable){- double taxRate;var shippingTotalExcl = await GetShoppingCartShippingTotal(cart, false);- double? shippingExclTax = shippingTotalExcl.shoppingCartShippingTotal;-- var shippingTotalIncl = await GetShoppingCartShippingTotal(cart, true);- double? shippingInclTax = shippingTotalIncl.shoppingCartShippingTotal;+ var shippingExclTax = shippingTotalExcl.shoppingCartShippingTotal;- taxRate = shippingTotalIncl.taxRate;+ var (shippingInclTax, taxRate, _) = await GetShoppingCartShippingTotal(cart, true);if (shippingExclTax.HasValue && shippingInclTax.HasValue){@@ -744,7 +682,7 @@ namespace Grand.Business.Checkout.Services.Ordersif (!taxRates.ContainsKey(taxRate))taxRates.Add(taxRate, shippingTax);else- taxRates[taxRate] = taxRates[taxRate] + shippingTax;+ taxRates[taxRate] += shippingTax;}}}@@ -753,16 +691,12 @@ namespace Grand.Business.Checkout.Services.Ordersdouble paymentMethodAdditionalFeeTax = 0;if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable){- double taxRate;- double paymentMethodAdditionalFee = await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);+ var paymentMethodAdditionalFee = await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);var additionalFeeExclTax = await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);- double paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;-- var additionalFeeInclTax = await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);- double paymentMethodAdditionalFeeInclTax = additionalFeeInclTax.paymentPrice;+ var paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;- taxRate = additionalFeeInclTax.taxRate;+ var (paymentMethodAdditionalFeeInclTax, taxRate) = await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;//ensure that tax is equal or greater than zero@@ -775,7 +709,7 @@ namespace Grand.Business.Checkout.Services.Ordersif (!taxRates.ContainsKey(taxRate))taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);else- taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;+ taxRates[taxRate] += paymentMethodAdditionalFeeTax;}}@@ -784,7 +718,7 @@ namespace Grand.Business.Checkout.Services.OrderstaxRates.Add(0, 0);//summarize taxes- double taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;+ var taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;//ensure that tax is equal or greater than zeroif (taxTotal < 0)taxTotal = 0;@@ -801,7 +735,7 @@ namespace Grand.Business.Checkout.Services.Orders/// Gets shopping cart total/// </summary>/// <param name="cart">Cart</param>- /// <param name="ignoreLoyaltyPonts">A value indicating whether we should ignore loyalty points</param>+ /// <param name="useLoyaltyPoints">Use Loyalty Points</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee</param>/// <returns>Shopping cart total, discount amount, applied discounts, gift vouchers, loyalty point/amount</returns>public virtual async Task<(double? shoppingCartTotal, double discountAmount, List<ApplyDiscount> appliedDiscounts, List<AppliedGiftVoucher> appliedGiftVouchers,@@ -814,7 +748,7 @@ namespace Grand.Business.Checkout.Services.Ordersvar customer = _workContext.CurrentCustomer;- string paymentMethodSystemName = "";+ var paymentMethodSystemName = "";if (customer != null){paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(@@ -824,14 +758,11 @@ namespace Grand.Business.Checkout.Services.Orders//subtotal without taxvar subTotal = await GetShoppingCartSubTotal(cart, false);- double subTotalWithDiscountBase = subTotal.subTotalWithDiscount;-- //subtotal with discount- double subtotalBase = subTotalWithDiscountBase;-+ var subTotalWithDiscountBase = subTotal.subTotalWithDiscount;+//shipping without taxvar shippingTotal = await GetShoppingCartShippingTotal(cart, false);- double? shoppingCartShipping = shippingTotal.shoppingCartShippingTotal;+ var shoppingCartShipping = shippingTotal.shoppingCartShippingTotal;//payment method additional fee without taxdouble paymentMethodAdditionalFeeWithoutTax = 0;@@ -842,11 +773,11 @@ namespace Grand.Business.Checkout.Services.Orders}//tax- double shoppingCartTax = (await GetTaxTotal(cart, usePaymentMethodAdditionalFee)).taxtotal;+ var shoppingCartTax = (await GetTaxTotal(cart, usePaymentMethodAdditionalFee)).taxtotal;//order totaldouble resultTemp = 0;- resultTemp += subtotalBase;+ resultTemp += subTotalWithDiscountBase;if (shoppingCartShipping.HasValue){resultTemp += shoppingCartShipping.Value;@@ -886,8 +817,8 @@ namespace Grand.Business.Checkout.Services.Ordersforeach (var gc in giftVouchers)if (resultTemp > 0){- double remainingAmount = gc.GetGiftVoucherRemainingAmount();- double amountCanBeUsed = resultTemp > remainingAmount ?+ var remainingAmount = gc.GetGiftVoucherRemainingAmount();+ var amountCanBeUsed = resultTemp > remainingAmount ?remainingAmount :resultTemp;@@ -914,21 +845,21 @@ namespace Grand.Business.Checkout.Services.Ordersreturn (null, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints, redeemedLoyaltyPointsAmount);}- double orderTotal = resultTemp;+ var orderTotal = resultTemp;#region Loyalty pointsif (_loyaltyPointsSettings.Enabled){- if (!useLoyaltyPoints.HasValue)- useLoyaltyPoints = customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout, _workContext.CurrentStore.Id);+ useLoyaltyPoints ??= customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,+ _workContext.CurrentStore.Id);if (useLoyaltyPoints.Value){- int loyaltyPointsBalance = await _loyaltyPointsService.GetLoyaltyPointsBalance(customer.Id, _workContext.CurrentStore.Id);+ var loyaltyPointsBalance = await _loyaltyPointsService.GetLoyaltyPointsBalance(customer?.Id, _workContext.CurrentStore.Id);if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance)){- double loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);+ var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);if (orderTotal > 0){if (orderTotal > loyaltyPointsBalanceAmount)@@ -980,7 +911,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>Converted value</returns>public virtual int ConvertAmountToLoyaltyPoints(double amount){- int result = 0;+ var result = 0;if (amount <= 0)return 0;diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.csindex 4a3c2ca35..39ae6affb 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Order service/// </summary>- public partial class OrderService : IOrderService+ public class OrderService : IOrderService{#region Fields@@ -31,7 +31,6 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="orderRepository">Order repository</param>/// <param name="orderNoteRepository">Order note repository</param>- /// <param name="productAlsoPurchasedRepository">Product also purchased repository</param>/// <param name="mediator">Mediator</param>public OrderService(IRepository<Order> orderRepository,IRepository<OrderNote> orderNoteRepository,@@ -63,7 +62,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Gets an order/// </summary>- /// <param name="orderId">The order item identifier</param>+ /// <param name="orderItemId">The order item identifier</param>/// <returns>Order</returns>public virtual Task<Order> GetOrderByOrderItemId(string orderItemId){@@ -80,7 +79,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <returns>Order</returns>public virtual Task<Order> GetOrderByNumber(int orderNumber){- return Task.FromResult(_orderRepository.Table.Where(x => x.OrderNumber == orderNumber).FirstOrDefault());+ return Task.FromResult(_orderRepository.Table.FirstOrDefault(x => x.OrderNumber == orderNumber));}/// <summary>@@ -112,14 +111,7 @@ namespace Grand.Business.Checkout.Services.Ordersselect o;var orders = await Task.FromResult(query.ToList());//sort by passed identifiers- var sortedOrders = new List<Order>();- foreach (string id in orderIds)- {- var order = orders.Find(x => x.Id == id);- if (order != null)- sortedOrders.Add(order);- }- return sortedOrders;+ return orderIds.Select(id => orders.Find(x => x.Id == id)).Where(order => order != null).ToList();}/// <summary>@@ -146,7 +138,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="warehouseId">Warehouse identifier, only orders with products from a specified warehouse will be loaded; 0 to load all orders</param>/// <param name="billingCountryId">Billing country identifier; 0 to load all orders</param>/// <param name="ownerId">Owner identifier</param>- /// <param name="salesemployeeId">Sales employee identifier</param>+ /// <param name="salesEmployeeId">Sales employee identifier</param>/// <param name="paymentMethodSystemName">Payment method system name; null to load all records</param>/// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>@@ -154,8 +146,9 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="ps">Order payment status; null to load all orders</param>/// <param name="ss">Order shipment status; null to load all orders</param>/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>- /// <param name="orderNotes">Search in order notes. Leave empty to load all records.</param>+ /// <param name="billingLastName"></param>/// <param name="orderGuid">Search by order GUID (Global unique identifier) or part of GUID. Leave empty to load all orders.</param>+ /// <param name="orderCode"></param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="orderTagId">Order tag identifier</param>@@ -163,13 +156,13 @@ namespace Grand.Business.Checkout.Services.Orderspublic virtual async Task<IPagedList<Order>> SearchOrders(string storeId = "",string vendorId = "", string customerId = "",string productId = "", string affiliateId = "", string warehouseId = "",- string billingCountryId = "", string ownerId = "", string salesemployeeId = "", string paymentMethodSystemName = null,+ string billingCountryId = "", string ownerId = "", string salesEmployeeId = "", string paymentMethodSystemName = null,DateTime? createdFromUtc = null, DateTime? createdToUtc = null,int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,string billingEmail = null, string billingLastName = "", string orderGuid = null,string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = ""){- var querymodel = new GetOrderQuery()+ var queryModel = new GetOrderQuery{AffiliateId = affiliateId,BillingCountryId = billingCountryId,@@ -192,9 +185,9 @@ namespace Grand.Business.Checkout.Services.OrdersWarehouseId = warehouseId,OrderTagId = orderTagId,OwnerId = ownerId,- SalesEmployeeId = salesemployeeId+ SalesEmployeeId = salesEmployeeId};- var query = await _mediator.Send(querymodel);+ var query = await _mediator.Send(queryModel);return await PagedList<Order>.Create(query, pageIndex, pageSize);}@@ -234,17 +227,17 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Cancel UnPaid Orders and has pending status/// </summary>- /// <param name="expirationDateUTC">Date at which all unPaid orders and has pending status Would be Canceled</param>- public async Task CancelExpiredOrders(DateTime expirationDateUTC)+ /// <param name="expirationDateUtc">Date at which all unPaid orders and has pending status Would be Canceled</param>+ public async Task CancelExpiredOrders(DateTime expirationDateUtc){var orders = _orderRepository.Table- .Where(o => o.CreatedOnUtc < expirationDateUTC && o.PaymentStatusId == PaymentStatus.Pending &&+ .Where(o => o.CreatedOnUtc < expirationDateUtc && o.PaymentStatusId == PaymentStatus.Pending &&o.OrderStatusId == (int)OrderStatusSystem.Pending && (o.ShippingStatusId == ShippingStatus.Pending|| o.ShippingStatusId == ShippingStatus.ShippingNotRequired)).ToList();foreach (var order in orders)- await _mediator.Send(new CancelOrderCommand() { Order = order, NotifyCustomer = true });+ await _mediator.Send(new CancelOrderCommand { Order = order, NotifyCustomer = true });}#endregion@@ -331,13 +324,13 @@ namespace Grand.Business.Checkout.Services.Orders}/// <summary>- /// Get ordernote by id+ /// Get order note by id/// </summary>- /// <param name="ordernoteId">Order note identifier</param>+ /// <param name="orderNoteId">Order note identifier</param>/// <returns>OrderNote</returns>- public virtual Task<OrderNote> GetOrderNote(string ordernoteId)+ public virtual Task<OrderNote> GetOrderNote(string orderNoteId){- return Task.FromResult(_orderNoteRepository.Table.Where(x => x.Id == ordernoteId).FirstOrDefault());+ return Task.FromResult(_orderNoteRepository.Table.FirstOrDefault(x => x.Id == orderNoteId));}diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.csindex b53fba901..f1097560f 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs@@ -26,8 +26,7 @@ namespace Grand.Business.Checkout.Services.Orderspublic virtual async Task<IList<OrderStatus>> GetAll(){- string key = string.Format(CacheKey.ORDER_STATUS_ALL);- var orderstatuses = await _cacheBase.GetAsync(CacheKey.ORDER_STATUS_ALL, async () =>+ var orderStatuses = await _cacheBase.GetAsync(CacheKey.ORDER_STATUS_ALL, async () =>{var query = from p in _orderStatusRepository.Tableselect p;@@ -36,7 +35,7 @@ namespace Grand.Business.Checkout.Services.Ordersreturn await Task.FromResult(query.ToList());});- return orderstatuses;+ return orderStatuses;}public virtual async Task<OrderStatus> GetById(string id){diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.csindex d0b0ed8de..725298645 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs@@ -8,7 +8,7 @@ using MediatR;namespace Grand.Business.Checkout.Services.Orders{- public partial class OrderTagService : IOrderTagService+ public class OrderTagService : IOrderTagService{#region Fields@@ -41,21 +41,17 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Get order's count for each of existing order tag/// </summary>- /// <param name="storeId">Store identifier</param>+ /// <param name="orderTagId">Order tag identifier</param>/// <returns>Dictionary of "order's tag ID : order's count"</returns>private async Task<Dictionary<string, int>> GetOrderCount(string orderTagId){- string key = string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId);+ var key = string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId);return await _cacheBase.GetAsync(key, async () =>{var query = from ot in _orderTagRepository.Tableselect ot;- var dictionary = new Dictionary<string, int>();- foreach (var tag in query.ToList())- {- dictionary.Add(tag.Id, tag.Count);- }+ var dictionary = query.ToList().ToDictionary(tag => tag.Id, tag => tag.Count);return await Task.FromResult(dictionary);});}@@ -159,7 +155,8 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Attach a tag to the order/// </summary>- /// <param name="orderTag">Order's identification</param>+ /// <param name="orderTagId">Order tag ident</param>+ /// <param name="orderId">Order's identification</param>public virtual async Task AttachOrderTag(string orderTagId, string orderId){//assign to product@@ -177,10 +174,11 @@ namespace Grand.Business.Checkout.Services.Ordersawait _mediator.EntityUpdated(orderTag);}- // <summary>+ /// <summary>/// Detach a tag from the order/// </summary>- /// <param name="orderTag">Order Tag</param>+ /// <param name="orderTagId">Order Tag ident</param>+ /// <param name="orderId">Order ident</param>public virtual async Task DetachOrderTag(string orderTagId, string orderId){await _orderRepository.Pull(orderId, x => x.OrderTags, orderTagId);@@ -203,10 +201,7 @@ namespace Grand.Business.Checkout.Services.Orderspublic virtual async Task<int> GetOrderCount(string orderTagId, string storeId){var dictionary = await GetOrderCount(orderTagId);- if (dictionary.ContainsKey(orderTagId))- return dictionary[orderTagId];-- return 0;+ return dictionary.ContainsKey(orderTagId) ? dictionary[orderTagId] : 0;}#endregiondiff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.csindex 8e40fada1..8729b4087 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs@@ -19,7 +19,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Shopping cart service/// </summary>- public partial class ShoppingCartService : IShoppingCartService+ public class ShoppingCartService : IShoppingCartService{#region Fields@@ -90,11 +90,12 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="shoppingCart">Shopping cart</param>/// <param name="shoppingCartType">Shopping cart type</param>- /// <param name="product">Product</param>+ /// <param name="warehouseId"></param>/// <param name="attributes">Attributes</param>/// <param name="customerEnteredPrice">Price entered by a customer</param>/// <param name="rentalStartDate">Rental start date</param>/// <param name="rentalEndDate">Rental end date</param>+ /// <param name="productId"></param>/// <returns>Found shopping cart item</returns>public virtual async Task<ShoppingCartItem> FindShoppingCartItem(IList<ShoppingCartItem> shoppingCart,ShoppingCartType shoppingCartType,@@ -110,59 +111,55 @@ namespace Grand.Business.Checkout.Services.Ordersforeach (var sci in shoppingCart.Where(a => a.ShoppingCartTypeId == shoppingCartType)){- if (sci.ProductId == productId && sci.WarehouseId == warehouseId)+ if (sci.ProductId != productId || sci.WarehouseId != warehouseId) continue;+ //attributes+ var product = await _productService.GetProductById(sci.ProductId);+ var attributesEqual = ProductExtensions.AreProductAttributesEqual(product, sci.Attributes, attributes, false);+ if (product.ProductTypeId == ProductType.BundledProduct){- //attributes- var _product = await _productService.GetProductById(sci.ProductId);- bool attributesEqual = ProductExtensions.AreProductAttributesEqual(_product, sci.Attributes, attributes, false);- if (_product.ProductTypeId == ProductType.BundledProduct)+ foreach (var bundle in product.BundleProducts){- foreach (var bundle in _product.BundleProducts)- {- var p1 = await _productService.GetProductById(bundle.ProductId);- if (p1 != null)- {- if (!ProductExtensions.AreProductAttributesEqual(p1, sci.Attributes, attributes, false))- attributesEqual = false;- }- }+ var p1 = await _productService.GetProductById(bundle.ProductId);+ if (p1 == null) continue;+ if (!ProductExtensions.AreProductAttributesEqual(p1, sci.Attributes, attributes, false))+ attributesEqual = false;}- //gift vouchers- bool giftVoucherInfoSame = true;- if (_product.IsGiftVoucher)- {- GiftVoucherExtensions.GetGiftVoucherAttribute(attributes,- out var giftVoucherRecipientName1, out var giftVoucherRecipientEmail1,- out var giftVoucherSenderName1, out var giftVoucherSenderEmail1, out var giftVoucherMessage1);+ }+ //gift vouchers+ var giftVoucherInfoSame = true;+ if (product.IsGiftVoucher)+ {+ GiftVoucherExtensions.GetGiftVoucherAttribute(attributes,+ out var giftVoucherRecipientName1, out _,+ out var giftVoucherSenderName1, out _, out _);- GiftVoucherExtensions.GetGiftVoucherAttribute(sci.Attributes,- out var giftVoucherRecipientName2, out var giftVoucherRecipientEmail2,- out var giftVoucherSenderName2, out var giftVoucherSenderEmail2, out var giftVoucherMessage2);+ GiftVoucherExtensions.GetGiftVoucherAttribute(sci.Attributes,+ out var giftVoucherRecipientName2, out _,+ out var giftVoucherSenderName2, out _, out _);- if (giftVoucherRecipientName1.ToLowerInvariant() != giftVoucherRecipientName2.ToLowerInvariant() ||- giftVoucherSenderName1.ToLowerInvariant() != giftVoucherSenderName2.ToLowerInvariant())- giftVoucherInfoSame = false;- }+ if (!string.Equals(giftVoucherRecipientName1, giftVoucherRecipientName2, StringComparison.InvariantCultureIgnoreCase) ||+ !string.Equals(giftVoucherSenderName1, giftVoucherSenderName2, StringComparison.InvariantCultureIgnoreCase))+ giftVoucherInfoSame = false;+ }- //price is the same (for products which require customers to enter a price)- bool customerEnteredPricesEqual = true;- if (sci.EnteredPrice.HasValue)- {- if (customerEnteredPrice.HasValue)- customerEnteredPricesEqual = Math.Round(sci.EnteredPrice.Value, 2) == Math.Round(customerEnteredPrice.Value, 2);- else- customerEnteredPricesEqual = false;- }+ //price is the same (for products which require customers to enter a price)+ var customerEnteredPricesEqual = true;+ if (sci.EnteredPrice.HasValue)+ {+ if (customerEnteredPrice.HasValue)+ customerEnteredPricesEqual = Math.Round(sci.EnteredPrice.Value, 2) == Math.Round(customerEnteredPrice.Value, 2);else- {- if (customerEnteredPrice.HasValue)- customerEnteredPricesEqual = false;- }-- //found?- if (attributesEqual && giftVoucherInfoSame && customerEnteredPricesEqual)- return sci;+ customerEnteredPricesEqual = false;}+ else+ {+ if (customerEnteredPrice.HasValue)+ customerEnteredPricesEqual = false;+ }++ //found?+ if (attributesEqual && giftVoucherInfoSame && customerEnteredPricesEqual)+ return sci;}return null;@@ -199,8 +196,7 @@ namespace Grand.Business.Checkout.Services.Ordersif (customer == null)throw new ArgumentNullException(nameof(customer));- if (validator == null)- validator = new ShoppingCartValidatorOptions();+ validator ??= new ShoppingCartValidatorOptions();var product = await _productService.GetProductById(productId);if (product == null)@@ -251,23 +247,21 @@ namespace Grand.Business.Checkout.Services.Orders}warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, validator));- if (!warnings.Any())- {- if (update) await UpdateExistingShoppingCartItem(shoppingCartItem, customer, attributes);- else shoppingCartItem = await InsertNewItem(customer, product, shoppingCartItem, automaticallyAddRequiredProductsIfEnabled);-- if (product.ProductTypeId == ProductType.Reservation)- await _mediator.Send(new AddCustomerReservationCommand() {- Customer = customer,- Product = product,- ShoppingCartItem = shoppingCartItem,- RentalStartDate = rentalStartDate,- RentalEndDate = rentalEndDate,- ReservationId = reservationId,- });- //reset checkout info- await _customerService.ResetCheckoutData(customer, storeId);- }+ if (warnings.Any()) return (warnings, shoppingCartItem);+ if (update) await UpdateExistingShoppingCartItem(shoppingCartItem, customer, attributes);+ else shoppingCartItem = await InsertNewItem(customer, product, shoppingCartItem, automaticallyAddRequiredProductsIfEnabled);++ if (product.ProductTypeId == ProductType.Reservation)+ await _mediator.Send(new AddCustomerReservationCommand() {+ Customer = customer,+ Product = product,+ ShoppingCartItem = shoppingCartItem,+ RentalStartDate = rentalStartDate,+ RentalEndDate = rentalEndDate,+ ReservationId = reservationId,+ });+ //reset checkout info+ await _customerService.ResetCheckoutData(customer, storeId);return (warnings, shoppingCartItem);}@@ -310,12 +304,15 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="customer">Customer</param>/// <param name="shoppingCartItemId">Shopping cart item identifier</param>+ /// <param name="warehouseId"></param>/// <param name="attributes">Attributes</param>/// <param name="customerEnteredPrice">New customer entered price</param>/// <param name="rentalStartDate">Rental start date</param>/// <param name="rentalEndDate">Rental end date</param>/// <param name="quantity">New shopping cart item quantity</param>/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>+ /// <param name="reservationId"></param>+ /// <param name="sciId"></param>/// <returns>Warnings</returns>public virtual async Task<IList<string>> UpdateShoppingCartItem(Customer customer,string shoppingCartItemId, string warehouseId, IList<CustomAttribute> attributes,@@ -329,44 +326,40 @@ namespace Grand.Business.Checkout.Services.Ordersvar warnings = new List<string>();var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);- if (shoppingCartItem != null)+ if (shoppingCartItem == null) return warnings;+ if (resetCheckoutData){- if (resetCheckoutData)- {- //reset checkout data- await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);- }- if (quantity > 0)- {- var product = await _productService.GetProductById(shoppingCartItem.ProductId);- shoppingCartItem.Quantity = quantity;- shoppingCartItem.WarehouseId = warehouseId;- shoppingCartItem.Attributes = attributes;- shoppingCartItem.EnteredPrice = customerEnteredPrice;- shoppingCartItem.RentalStartDateUtc = rentalStartDate;- shoppingCartItem.RentalEndDateUtc = rentalEndDate;- shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;- shoppingCartItem.AdditionalShippingChargeProduct = product.AdditionalShippingCharge;- shoppingCartItem.IsFreeShipping = product.IsFreeShipping;- shoppingCartItem.IsShipEnabled = product.IsShipEnabled;- shoppingCartItem.IsTaxExempt = product.IsTaxExempt;- shoppingCartItem.IsGiftVoucher = product.IsGiftVoucher;- //check warnings- warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, new ShoppingCartValidatorOptions()));- if (!warnings.Any())- {- //if everything is OK, then update a shopping cart item- await _customerService.UpdateShoppingCartItem(customer.Id, shoppingCartItem);-- //event notification- await _mediator.EntityUpdated(shoppingCartItem);- }- }- else- {- //delete a shopping cart item- await DeleteShoppingCartItem(customer, shoppingCartItem, resetCheckoutData, true);- }+ //reset checkout data+ await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);+ }+ if (quantity > 0)+ {+ var product = await _productService.GetProductById(shoppingCartItem.ProductId);+ shoppingCartItem.Quantity = quantity;+ shoppingCartItem.WarehouseId = warehouseId;+ shoppingCartItem.Attributes = attributes;+ shoppingCartItem.EnteredPrice = customerEnteredPrice;+ shoppingCartItem.RentalStartDateUtc = rentalStartDate;+ shoppingCartItem.RentalEndDateUtc = rentalEndDate;+ shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;+ shoppingCartItem.AdditionalShippingChargeProduct = product.AdditionalShippingCharge;+ shoppingCartItem.IsFreeShipping = product.IsFreeShipping;+ shoppingCartItem.IsShipEnabled = product.IsShipEnabled;+ shoppingCartItem.IsTaxExempt = product.IsTaxExempt;+ shoppingCartItem.IsGiftVoucher = product.IsGiftVoucher;+ //check warnings+ warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, new ShoppingCartValidatorOptions()));+ if (warnings.Any()) return warnings;+ //if everything is OK, then update a shopping cart item+ await _customerService.UpdateShoppingCartItem(customer.Id, shoppingCartItem);++ //event notification+ await _mediator.EntityUpdated(shoppingCartItem);+ }+ else+ {+ //delete a shopping cart item+ await DeleteShoppingCartItem(customer, shoppingCartItem, resetCheckoutData, true);}return warnings;@@ -375,6 +368,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <summary>/// Delete shopping cart item/// </summary>+ /// <param name="customer"></param>/// <param name="shoppingCartItem">Shopping cart item</param>/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>/// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param>@@ -391,7 +385,7 @@ namespace Grand.Business.Checkout.Services.Orders}//delete item- customer.ShoppingCartItems.Remove(customer.ShoppingCartItems.Where(x => x.Id == shoppingCartItem.Id).FirstOrDefault());+ customer.ShoppingCartItems.Remove(customer.ShoppingCartItems.FirstOrDefault(x => x.Id == shoppingCartItem.Id));await _customerService.DeleteShoppingCartItem(customer.Id, shoppingCartItem);//event notification@@ -417,17 +411,15 @@ namespace Grand.Business.Checkout.Services.Orders//shopping cart itemsvar fromCart = fromCustomer.ShoppingCartItems.ToList();- for (int i = 0; i < fromCart.Count; i++)+ foreach (var sci in fromCart){- var sci = fromCart[i];await AddToCart(toCustomer, sci.ProductId, sci.ShoppingCartTypeId, sci.StoreId, sci.WarehouseId,sci.Attributes, sci.EnteredPrice,sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.ReservationId, sci.Parameter, sci.Duration,new ShoppingCartValidatorOptions());}- for (int i = 0; i < fromCart.Count; i++)+ foreach (var sci in fromCart){- var sci = fromCart[i];await DeleteShoppingCartItem(fromCustomer, sci);}@@ -436,13 +428,13 @@ namespace Grand.Business.Checkout.Services.Orders{//discountvar coupons = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);- var resultcoupons = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons, coupons);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.DiscountCoupons, resultcoupons);+ var resultCoupons = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons, coupons);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.DiscountCoupons, resultCoupons);//gift voucher- var giftvoucher = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);- var resultgift = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons, giftvoucher);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, resultgift);+ var giftVoucher = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);+ var resultGift = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons, giftVoucher);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, resultGift);}//copy url refererdiff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.csindex 593ed4db3..4bf06bba2 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs@@ -73,13 +73,11 @@ namespace Grand.Business.Checkout.Services.Ordersvar warnings = new List<string>();//gift vouchers- if (product.IsGiftVoucher)- {- var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartGiftVoucherValidatorRecord>>();- var result = await validator.ValidateAsync(new ShoppingCartGiftVoucherValidatorRecord(customer, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- }+ if (!product.IsGiftVoucher) return warnings;+ var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartGiftVoucherValidatorRecord>>();+ var result = await validator.ValidateAsync(new ShoppingCartGiftVoucherValidatorRecord(customer, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));return warnings;}@@ -100,14 +98,11 @@ namespace Grand.Business.Checkout.Services.Orderspublic virtual async Task<IList<string>> GetAuctionProductWarning(double bid, Product product, Customer customer){var warnings = new List<string>();- if (product.ProductTypeId == ProductType.Auction)- {- var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartAuctionValidatorRecord>>();- var result = await validator.ValidateAsync(new ShoppingCartAuctionValidatorRecord(customer, product, null, bid));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));-- }+ if (product.ProductTypeId != ProductType.Auction) return warnings;+ var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartAuctionValidatorRecord>>();+ var result = await validator.ValidateAsync(new ShoppingCartAuctionValidatorRecord(customer, product, null, bid));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));return warnings;}@@ -131,8 +126,7 @@ namespace Grand.Business.Checkout.Services.OrdersIList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes){var warnings = new List<string>();- if (checkoutAttributes == null)- checkoutAttributes = new List<CustomAttribute>();+ checkoutAttributes ??= new List<CustomAttribute>();var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartWarningsValidatorRecord>>();var result = await validator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore, shoppingCart));@@ -219,13 +213,11 @@ namespace Grand.Business.Checkout.Services.Ordersvar warnings = new List<string>();- if (product.RequireOtherProducts)- {- var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartRequiredProductValidatorRecord>>();- var result = await validator.ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- }+ if (!product.RequireOtherProducts) return warnings;+ var validator = _serviceProvider.GetRequiredService<IValidator<ShoppingCartRequiredProductValidatorRecord>>();+ var result = await validator.ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));return warnings;}}diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.csindex 050a8ed1a..fb4aeda7f 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs@@ -15,7 +15,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Payment service/// </summary>- public partial class PaymentService : IPaymentService+ public class PaymentService : IPaymentService{#region Fields@@ -31,7 +31,7 @@ namespace Grand.Business.Checkout.Services.Payments/// Ctor/// </summary>/// <param name="paymentSettings">Payment settings</param>- /// <param name="PaymentProviders">Payment providers</param>+ /// <param name="paymentProviders">Payment providers</param>/// <param name="settingService">Setting service</param>public PaymentService(PaymentSettings paymentSettings,IEnumerable<IPaymentProvider> paymentProviders,@@ -59,23 +59,18 @@ namespace Grand.Business.Checkout.Services.Payments.Where(provider => _paymentSettings.ActivePaymentProviderSystemNames.Contains(provider.SystemName, StringComparer.OrdinalIgnoreCase)).ToList();- if (customer != null)- {- var selectedShippingOption = customer.GetUserFieldFromEntity<ShippingOption>(- SystemCustomerFieldNames.SelectedShippingOption, storeId);+ if (customer == null) return await Task.FromResult(pm);+ var selectedShippingOption = customer.GetUserFieldFromEntity<ShippingOption>(+ SystemCustomerFieldNames.SelectedShippingOption, storeId);- if (selectedShippingOption != null)+ if (selectedShippingOption == null) return await Task.FromResult(pm);+ for (var i = pm.Count - 1; i >= 0; i--)+ {+ var restrictedGroupIds = GetRestrictedShippingIds(pm[i]);+ if (restrictedGroupIds.Contains(selectedShippingOption.Name)){- for (int i = pm.Count - 1; i >= 0; i--)- {- var restictedGroupIds = GetRestrictedShippingIds(pm[i]);- if (restictedGroupIds.Contains(selectedShippingOption.Name))- {- pm.Remove(pm[i]);- }- }+ pm.Remove(pm[i]);}-}return await Task.FromResult(pm);}@@ -104,24 +99,13 @@ namespace Grand.Business.Checkout.Services.Paymentsx.IsAuthenticateStore(storeId) &&x.IsAuthenticateGroup(customer)).OrderBy(x => x.Priority).ToList();- if (String.IsNullOrEmpty(filterByCountryId))- return paymentMethods;-- //filter by country- var paymentMetodsByCountry = new List<IPaymentProvider>();- foreach (var pm in paymentMethods)- {- var restictedCountryIds = GetRestrictedCountryIds(pm);- if (!restictedCountryIds.Contains(filterByCountryId))- {- paymentMetodsByCountry.Add(pm);- }- }- return paymentMetodsByCountry;+ return string.IsNullOrEmpty(filterByCountryId) ? paymentMethods :+ //filter by country+ (from pm in paymentMethods let restrictedCountryIds = GetRestrictedCountryIds(pm) where !restrictedCountryIds.Contains(filterByCountryId) select pm).ToList();}/// <summary>- /// Gets a list of coutnry identifiers in which a certain payment method is now allowed+ /// Gets a list of country identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <returns>A list of country identifiers</returns>@@ -130,11 +114,9 @@ namespace Grand.Business.Checkout.Services.Paymentsif (paymentMethod == null)throw new ArgumentNullException(nameof(paymentMethod));- var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.SystemName);- var restictedCountryIds = _settingService.GetSettingByKey<PaymentRestictedSettings>(settingKey);- if (restictedCountryIds == null)- return new List<string>();- return restictedCountryIds.Ids;+ var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";+ var restrictedCountryIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ return restrictedCountryIds == null ? new List<string>() : restrictedCountryIds.Ids;}/// <summary>@@ -147,38 +129,36 @@ namespace Grand.Business.Checkout.Services.Paymentsif (paymentMethod == null)throw new ArgumentNullException(nameof(paymentMethod));- var settingKey = string.Format("PaymentMethodRestictionsShipping.{0}", paymentMethod.SystemName);- var restictedShippingIds = _settingService.GetSettingByKey<PaymentRestictedSettings>(settingKey);- if (restictedShippingIds == null)- return new List<string>();- return restictedShippingIds.Ids;+ var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";+ var restrictedShippingIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ return restrictedShippingIds == null ? new List<string>() : restrictedShippingIds.Ids;}/// <summary>/// Saves a list of country identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="countryIds">A list of country identifiers</param>- public virtual async Task SaveRestictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds)+ public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds){if (paymentMethod == null)throw new ArgumentNullException(nameof(paymentMethod));- var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.SystemName);- await _settingService.SetSetting(settingKey, new PaymentRestictedSettings() { Ids = countryIds });+ var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds });}/// <summary>/// Saves a list of role identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>- /// <param name="countryIds">A list of country identifiers</param>- public virtual async Task SaveRestictedGroupIds(IPaymentProvider paymentMethod, List<string> groupIds)+ /// <param name="groupIds">A list of group identifiers</param>+ public virtual async Task SaveRestrictedGroupIds(IPaymentProvider paymentMethod, List<string> groupIds){if (paymentMethod == null)throw new ArgumentNullException(nameof(paymentMethod));- var settingKey = string.Format("PaymentMethodRestictionsGroup.{0}", paymentMethod.SystemName);- await _settingService.SetSetting(settingKey, new PaymentRestictedSettings() { Ids = groupIds });+ var settingKey = $"PaymentMethodRestictionsGroup.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = groupIds });}/// <summary>@@ -186,19 +166,19 @@ namespace Grand.Business.Checkout.Services.Payments/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="shippingIds">A list of country identifiers</param>- public virtual async Task SaveRestictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds)+ public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds){if (paymentMethod == null)throw new ArgumentNullException(nameof(paymentMethod));- var settingKey = string.Format("PaymentMethodRestictionsShipping.{0}", paymentMethod.SystemName);- await _settingService.SetSetting(settingKey, new PaymentRestictedSettings() { Ids = shippingIds });+ var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds });}/// <summary>/// Process a payment/// </summary>- /// <param name="processPaymentRequest">Payment info required for an order processing</param>+ /// <param name="paymentTransaction">Payment transaction</param>/// <returns>Process payment result</returns>public virtual async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction){@@ -223,7 +203,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Post process payment/// </summary>- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>+ /// <param name="paymentTransaction">Payment transaction</param>public virtual async Task PostProcessPayment(PaymentTransaction paymentTransaction){if (paymentTransaction == null)@@ -241,7 +221,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Post redirect payment (used by payment gateways that redirecting to a another URL)/// </summary>- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>+ /// <param name="paymentTransaction">Payment Transaction</param>public virtual async Task PostRedirectPayment(PaymentTransaction paymentTransaction){if (paymentTransaction == null)@@ -277,7 +257,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)/// </summary>- /// <param name="order">Order</param>+ /// <param name="paymentTransaction">Payment transaction</param>/// <returns>Result</returns>public virtual async Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction){@@ -288,18 +268,12 @@ namespace Grand.Business.Checkout.Services.Paymentsreturn false;var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)+ if (paymentMethod is not { PaymentMethodType: PaymentMethodType.Redirection })return false; //Payment method couldn't be loaded (for example, was uninstalled)- if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection)- return false; //this option is available only for redirection payment methods-- if (paymentTransaction.TransactionStatus == TransactionStatus.Canceled)+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or not TransactionStatus.Pending)return false; //do not allow for cancelled orders- if (paymentTransaction.TransactionStatus != TransactionStatus.Pending)- return false; //payment transaction status should be Pending-return await paymentMethod.CanRePostRedirectPayment(paymentTransaction);}@@ -308,19 +282,19 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Gets an additional handling fee of a payment method/// </summary>- /// <param name="cart">Shoping cart</param>+ /// <param name="cart">Shopping cart</param>/// <param name="paymentMethodSystemName">Payment method system name</param>/// <returns>Additional handling fee</returns>public virtual async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart, string paymentMethodSystemName){- if (String.IsNullOrEmpty(paymentMethodSystemName))+ if (string.IsNullOrEmpty(paymentMethodSystemName))return 0;var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);if (paymentMethod == null)return 0;- double result = await paymentMethod.GetAdditionalHandlingFee(cart);+ var result = await paymentMethod.GetAdditionalHandlingFee(cart);if (result < 0)result = 0;@@ -417,7 +391,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Voids a payment/// </summary>- /// <param name="voidPaymentRequest">Request</param>+ /// <param name="paymentTransaction">Payment transaction</param>/// <returns>Result</returns>public virtual async Task<VoidPaymentResult> Void(PaymentTransaction paymentTransaction){@@ -439,9 +413,7 @@ namespace Grand.Business.Checkout.Services.Paymentspublic virtual PaymentMethodType GetPaymentMethodType(string paymentMethodSystemName){var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return PaymentMethodType.Other;- return paymentMethod.PaymentMethodType;+ return paymentMethod?.PaymentMethodType ?? PaymentMethodType.Other;}#endregiondiff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.csindex 518fbdba3..6ee2c04c4 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs@@ -8,7 +8,7 @@ using MediatR;namespace Grand.Business.Checkout.Services.Payments{- public partial class PaymentTransactionService : IPaymentTransactionService+ public class PaymentTransactionService : IPaymentTransactionService{private readonly IRepository<PaymentTransaction> _repositoryPaymentTransaction;private readonly IMediator _mediator;@@ -92,11 +92,11 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Gets an payment transactions for order guid/// </summary>- /// <param name="orderguid">The order guid</param>+ /// <param name="orderGuid">The order guid</param>/// <returns>PaymentTransaction</returns>- public virtual async Task<PaymentTransaction> GetByOrdeGuid(Guid orderguid)+ public virtual async Task<PaymentTransaction> GetOrderByGuid(Guid orderGuid){- return await Task.FromResult(_repositoryPaymentTransaction.Table.Where(x => x.OrderGuid == orderguid).FirstOrDefault());+ return await Task.FromResult(_repositoryPaymentTransaction.Table.FirstOrDefault(x => x.OrderGuid == orderGuid));}/// <summary>@@ -122,7 +122,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Search payment transactions/// </summary>- /// <param name="orderguid">Order ident by guid</param>+ /// <param name="orderGuid">Order ident by guid</param>/// <param name="storeId">Store ident</param>/// <param name="customerEmail">Customer email</param>/// <param name="ts">Transaction status</param>@@ -132,7 +132,7 @@ namespace Grand.Business.Checkout.Services.Payments/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>/// <returns>Page list payment transaction</returns>public virtual async Task<IPagedList<PaymentTransaction>> SearchPaymentTransactions(- Guid? orderguid = null,+ Guid? orderGuid = null,string storeId = "",string customerEmail = "",TransactionStatus? ts = null,@@ -140,15 +140,15 @@ namespace Grand.Business.Checkout.Services.PaymentsDateTime? createdFromUtc = null,DateTime? createdToUtc = null){- var model = new GetPaymentTransactionQuery() {+ var model = new GetPaymentTransactionQuery {CreatedFromUtc = createdFromUtc,CreatedToUtc = createdToUtc,PageIndex = pageIndex,PageSize = pageSize,- OrderGuid = orderguid,+ OrderGuid = orderGuid,CustomerEmail = customerEmail,StoreId = storeId,- Ts = ts,+ Ts = ts};var query = await _mediator.Send(model);@@ -158,9 +158,9 @@ namespace Grand.Business.Checkout.Services.Payments/// <summary>/// Set payment error for transaction/// </summary>- public virtual async Task SetError(string paymenttransactionId, List<string> errors)+ public virtual async Task SetError(string paymentTransactionId, List<string> errors){- await _repositoryPaymentTransaction.UpdateField(paymenttransactionId, x => x.Errors, errors);+ await _repositoryPaymentTransaction.UpdateField(paymentTransactionId, x => x.Errors, errors);}}}diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.csindex 0ba43da03..10a038c2d 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs@@ -44,7 +44,7 @@ namespace Grand.Business.Checkout.Services.Shipping/// <returns>Delivery date</returns>public virtual Task<DeliveryDate> GetDeliveryDateById(string deliveryDateId){- string key = string.Format(CacheKey.DELIVERYDATE_BY_ID_KEY, deliveryDateId);+ var key = string.Format(CacheKey.DELIVERYDATE_BY_ID_KEY, deliveryDateId);return _cacheBase.GetAsync(key, () => _deliveryDateRepository.GetByIdAsync(deliveryDateId));}diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.csindex 0430fdff8..026c7c6f7 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs@@ -74,9 +74,9 @@ namespace Grand.Business.Checkout.Services.Shipping/// <summary>- /// Inserts a warehouse+ /// Inserts a pickup point/// </summary>- /// <param name="warehouse">Warehouse</param>+ /// <param name="pickupPoint">Pickup Point</param>public virtual async Task InsertPickupPoint(PickupPoint pickupPoint){if (pickupPoint == null)@@ -92,9 +92,9 @@ namespace Grand.Business.Checkout.Services.Shipping}/// <summary>- /// Updates the warehouse+ /// Updates the pickupPoint/// </summary>- /// <param name="warehouse">Warehouse</param>+ /// <param name="pickupPoint">Pickup Point</param>public virtual async Task UpdatePickupPoint(PickupPoint pickupPoint){if (pickupPoint == null)@@ -110,9 +110,9 @@ namespace Grand.Business.Checkout.Services.Shipping}/// <summary>- /// Deletes a delivery date+ /// Deletes a pickup point/// </summary>- /// <param name="deliveryDate">The delivery date</param>+ /// <param name="pickupPoint">pickup point</param>public virtual async Task DeletePickupPoint(PickupPoint pickupPoint){if (pickupPoint == null)diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.csindex 977c7fcee..f0c2b9c3b 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Checkout.Services.Shipping/// <summary>/// Shipment service/// </summary>- public partial class ShipmentService : IShipmentService+ public class ShipmentService : IShipmentService{#region Fields@@ -213,17 +213,16 @@ namespace Grand.Business.Checkout.Services.Shipping}/// <summary>- /// Get shipmentnote by id+ /// Get shipment note by id/// </summary>- /// <param name="shipmentnoteId">Shipment note identifier</param>+ /// <param name="shipmentNoteId">Shipment note identifier</param>/// <returns>shipmentNote</returns>- public virtual Task<ShipmentNote> GetShipmentNote(string shipmentnoteId)+ public virtual Task<ShipmentNote> GetShipmentNote(string shipmentNoteId){- return Task.FromResult(_shipmentNoteRepository.Table.Where(x => x.Id == shipmentnoteId).FirstOrDefault());+ return Task.FromResult(_shipmentNoteRepository.Table.FirstOrDefault(x => x.Id == shipmentNoteId));}--#endregion+#endregion}}diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.csindex cb744d958..4650be9ea 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs@@ -65,24 +65,23 @@ namespace Grand.Business.Checkout.Services.Shipping/// <returns>Shipping method</returns>public virtual Task<ShippingMethod> GetShippingMethodById(string shippingMethodId){- string key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId);+ var key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId);return _cacheBase.GetAsync(key, () => _shippingMethodRepository.GetByIdAsync(shippingMethodId));}/// <summary>/// Gets all shipping methods/// </summary>- /// <param name="filterByCountryId">The country indentifier to filter by</param>+ /// <param name="filterByCountryId">The country ident to filter by</param>+ /// <param name="customer"></param>/// <returns>Shipping methods</returns>public virtual async Task<IList<ShippingMethod>> GetAllShippingMethods(string filterByCountryId = "", Customer customer = null){- var shippingMethods = new List<ShippingMethod>();-- shippingMethods = await _cacheBase.GetAsync(CacheKey.SHIPPINGMETHOD_ALL, async () =>+ var shippingMethods = await _cacheBase.GetAsync(CacheKey.SHIPPINGMETHOD_ALL, async () =>{var query = from sm in _shippingMethodRepository.Table- orderby sm.DisplayOrder- select sm;+ orderby sm.DisplayOrder+ select sm;return await Task.FromResult(query.ToList());});diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.csindex 633c9b30b..c7bc6a4db 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Checkout.Services.Shipping/// <summary>/// Shipping service/// </summary>- public partial class ShippingService : IShippingService+ public class ShippingService : IShippingService{#region Fields@@ -153,10 +153,11 @@ namespace Grand.Business.Checkout.Services.Shipping/// <summary>/// Gets available shipping options/// </summary>+ /// <param name="customer"></param>/// <param name="cart">Shopping cart</param>/// <param name="shippingAddress">Shipping address</param>/// <param name="allowedShippingRateMethodSystemName">Filter by Shipping rate method identifier; null to load shipping options of all Shipping rate methods</param>- /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>+ /// <param name="store">Store</param>/// <returns>Shipping options</returns>public virtual async Task<GetShippingOptionResponse> GetShippingOptions(Customer customer, IList<ShoppingCartItem> cart,Address shippingAddress, string allowedShippingRateMethodSystemName = "",@@ -172,7 +173,7 @@ namespace Grand.Business.Checkout.Services.Shippingvar shippingRateMethods = await LoadActiveShippingRateCalculationProviders(customer, store?.Id, cart);//filter by system name- if (!String.IsNullOrWhiteSpace(allowedShippingRateMethodSystemName))+ if (!string.IsNullOrWhiteSpace(allowedShippingRateMethodSystemName)){shippingRateMethods = shippingRateMethods.Where(srcm => allowedShippingRateMethodSystemName.Equals(srcm.SystemName, StringComparison.OrdinalIgnoreCase))@@ -182,67 +183,40 @@ namespace Grand.Business.Checkout.Services.Shippingthrow new GrandException("Shipping rate method could not be loaded");//request shipping options from each Shipping rate methods- foreach (var srcm in shippingRateMethods)+ foreach (var shippingRateMethod in shippingRateMethods){//request shipping options (separately for each package-request)- IList<ShippingOption> srcmShippingOptions = null;-- var getShippingOptionResponse = await srcm.GetShippingOptions(shippingOptionRequest);+ IList<ShippingOption> shippingRateMethodOptions = null;+ var getShippingOptionResponse = await shippingRateMethod.GetShippingOptions(shippingOptionRequest);if (getShippingOptionResponse.Success){//success- if (srcmShippingOptions == null)- {- //first shipping option request- srcmShippingOptions = getShippingOptionResponse.ShippingOptions;- }- else- {- //get shipping options which already exist for prior requested packages for this scrm (i.e. common options)- srcmShippingOptions = srcmShippingOptions- .Where(existingso => getShippingOptionResponse.ShippingOptions.Any(newso => newso.Name == existingso.Name))- .ToList();-- //and sum the rates- foreach (var existingso in srcmShippingOptions)- {- existingso.Rate += getShippingOptionResponse- .ShippingOptions- .First(newso => newso.Name == existingso.Name)- .Rate;- }- }+ shippingRateMethodOptions = getShippingOptionResponse.ShippingOptions;}else{//errors- foreach (string error in getShippingOptionResponse.Errors)+ foreach (var error in getShippingOptionResponse.Errors){result.AddError(error);- _ = _logger.Warning(string.Format("Shipping ({0}). {1}", srcm.FriendlyName, error));+ _ = _logger.Warning($"Shipping ({shippingRateMethod.FriendlyName}). {error}");}//clear the shipping options in this case- srcmShippingOptions = new List<ShippingOption>();break;}--- // add this scrm's options to the result- if (srcmShippingOptions != null)+ if (shippingRateMethodOptions == null) continue;+ foreach (var so in shippingRateMethodOptions){- foreach (var so in srcmShippingOptions)- {- //set system name if not set yet- if (String.IsNullOrEmpty(so.ShippingRateProviderSystemName))- so.ShippingRateProviderSystemName = srcm.SystemName;+ //set system name if not set yet+ if (string.IsNullOrEmpty(so.ShippingRateProviderSystemName))+ so.ShippingRateProviderSystemName = shippingRateMethod.SystemName;- result.ShippingOptions.Add(so);- }+ result.ShippingOptions.Add(so);}}- //returnvalidoptions if there are any (no matter of the errors returned by other shipping rate compuation methods).+ //return valid options if there are any (no matter of the errors returned by other shipping rate computation methods).if (!result.ShippingOptions.Any() && !result.Errors.Any())result.Errors.Clear();@@ -255,4 +229,4 @@ namespace Grand.Business.Checkout.Services.Shipping#endregion}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.csindex 0c42fd586..fd30227e3 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs@@ -44,7 +44,7 @@ namespace Grand.Business.Checkout.Services.Shipping/// <returns>Warehouse</returns>public virtual Task<Warehouse> GetWarehouseById(string warehouseId){- string key = string.Format(CacheKey.WAREHOUSES_BY_ID_KEY, warehouseId);+ var key = string.Format(CacheKey.WAREHOUSES_BY_ID_KEY, warehouseId);return _cacheBase.GetAsync(key, () => _warehouseRepository.GetByIdAsync(warehouseId));}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.csindex eb5626c75..70f104d2e 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs@@ -18,7 +18,7 @@ namespace Grand.Business.Checkout.ValidatorsICheckoutAttributeParser checkoutAttributeParser, ICheckoutAttributeService checkoutAttributeService){- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{//selected attributesvar attributes1 = await checkoutAttributeParser.ParseCheckoutAttributes(value.CheckoutAttributes);@@ -28,29 +28,26 @@ namespace Grand.Business.Checkout.Validatorsforeach (var a2 in attributes2){var conditionMet = await checkoutAttributeParser.IsConditionMet(a2, value.CheckoutAttributes);- if (a2.IsRequired && ((conditionMet.HasValue && conditionMet.Value) || !conditionMet.HasValue))+ if (!a2.IsRequired || ((!conditionMet.HasValue || !conditionMet.Value) && conditionMet.HasValue))+ continue;+ var found = false;+ //selected checkout attributes+ foreach (var a1 in attributes1){- bool found = false;- //selected checkout attributes- foreach (var a1 in attributes1)- {- if (a1.Id == a2.Id)+ if (a1.Id != a2.Id) continue;+ var attributeValuesStr = value.CheckoutAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);+ foreach (var str1 in attributeValuesStr)+ if (!string.IsNullOrEmpty(str1.Trim())){- var attributeValuesStr = value.CheckoutAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);- foreach (var str1 in attributeValuesStr)- if (!string.IsNullOrEmpty(str1.Trim()))- {- found = true;- break;- }+ found = true;+ break;}- }+ }- //if not found- if (!found)- {- context.AddFailure(a2.TextPrompt ?? string.Format(translationService.GetResource("ShoppingCart.SelectAttribute"), a2.Name));- }+ //if not found+ if (!found)+ {+ context.AddFailure(a2.TextPrompt ?? string.Format(translationService.GetResource("ShoppingCart.SelectAttribute"), a2.Name));}}@@ -61,34 +58,30 @@ namespace Grand.Business.Checkout.Validators{if (ca.ValidationMinLength.HasValue){- if (ca.AttributeControlTypeId == AttributeControlType.TextBox ||- ca.AttributeControlTypeId == AttributeControlType.MultilineTextbox)+ if (ca.AttributeControlTypeId is AttributeControlType.TextBox or AttributeControlType.MultilineTextbox){var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);- var enteredText = valuesStr?.FirstOrDefault();- int enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;+ var enteredText = valuesStr.FirstOrDefault();+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;if (ca.ValidationMinLength.Value > enteredTextLength){- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextboxMinimumLength"), ca.Name, ca.ValidationMinLength.Value));+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextBoxMinimumLength"), ca.Name, ca.ValidationMinLength.Value));}}}-//maximum length- if (ca.ValidationMaxLength.HasValue)+ if (!ca.ValidationMaxLength.HasValue) continue;{- if (ca.AttributeControlTypeId == AttributeControlType.TextBox ||- ca.AttributeControlTypeId == AttributeControlType.MultilineTextbox)- {- var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);- var enteredText = valuesStr?.FirstOrDefault();- int enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;+ if (ca.AttributeControlTypeId != AttributeControlType.TextBox &&+ ca.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;+ var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);+ var enteredText = valuesStr.FirstOrDefault();+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;- if (ca.ValidationMaxLength.Value < enteredTextLength)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextboxMaximumLength"), ca.Name, ca.ValidationMaxLength.Value));- }+ if (ca.ValidationMaxLength.Value < enteredTextLength)+ {+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextBoxMaximumLength"), ca.Name, ca.ValidationMaxLength.Value));}}}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.csindex 2a9a12da6..727edf889 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs@@ -20,7 +20,7 @@ namespace Grand.Business.Checkout.ValidatorsIPermissionService permissionService, ShoppingCartSettings shoppingCartSettings){- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{//maximum items validationswitch (value.ShoppingCartType)diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.csindex 93b33f45a..ea1631c50 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs@@ -18,7 +18,7 @@ namespace Grand.Business.Checkout.Validators{GiftVoucherExtensions.GetGiftVoucherAttribute(value.ShoppingCartItem.Attributes,out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var _);+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);if (string.IsNullOrEmpty(giftVoucherRecipientName))context.AddFailure(translationService.GetResource("ShoppingCart.RecipientNameError"));@@ -33,12 +33,10 @@ namespace Grand.Business.Checkout.Validatorsif (string.IsNullOrEmpty(giftVoucherSenderName))context.AddFailure(translationService.GetResource("ShoppingCart.SenderNameError"));- if (value.Product.GiftVoucherTypeId == GiftVoucherType.Virtual)- {- //validate for virtual gift vouchers only- if (string.IsNullOrEmpty(giftVoucherSenderEmail) || !CommonHelper.IsValidEmail(giftVoucherSenderEmail))- context.AddFailure(translationService.GetResource("ShoppingCart.SenderEmailError"));- }+ if (value.Product.GiftVoucherTypeId != GiftVoucherType.Virtual) return;+ //validate for virtual gift vouchers only+ if (string.IsNullOrEmpty(giftVoucherSenderEmail) || !CommonHelper.IsValidEmail(giftVoucherSenderEmail))+ context.AddFailure(translationService.GetResource("ShoppingCart.SenderEmailError"));});}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.csindex 9ba2afa61..0660eb944 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs@@ -69,10 +69,11 @@ namespace Grand.Business.Checkout.Validatorsvar maximumQuantityCanBeAdded = stockQuantityService.GetTotalStockQuantity(value.Product, warehouseId: warehouseId);if (maximumQuantityCanBeAdded < qty){- if (maximumQuantityCanBeAdded <= 0)- context.AddFailure(translationService.GetResource("ShoppingCart.OutOfStock"));- else- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));+ context.AddFailure(maximumQuantityCanBeAdded <= 0+ ? translationService.GetResource("ShoppingCart.OutOfStock")+ : string.Format(+ translationService.GetResource("ShoppingCart.QuantityExceedsStock"),+ maximumQuantityCanBeAdded));}}}@@ -81,46 +82,41 @@ namespace Grand.Business.Checkout.Validators{foreach (var item in value.Product.BundleProducts){- var _qty = value.ShoppingCartItem.Quantity * item.Quantity;+ var qty = value.ShoppingCartItem.Quantity * item.Quantity;var p1 = await productService.GetProductById(item.ProductId);- if (p1 != null)+ if (p1 is not { BackorderModeId: BackorderMode.NoBackorders }) continue;+ if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock){- if (p1.BackorderModeId == BackorderMode.NoBackorders)+ var maximumQuantityCanBeAdded = stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);+ if (maximumQuantityCanBeAdded < qty){- if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)- {- int maximumQuantityCanBeAdded = stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);- if (maximumQuantityCanBeAdded < _qty)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));- }- }- if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)- {- var combination = p1.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);- if (combination != null)- {- //combination exists - check stock level- var stockquantity = stockQuantityService.GetTotalStockQuantityForCombination(p1, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockquantity < _qty)- {- if (stockquantity <= 0)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));- }- else- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name, stockquantity));- }- }- }- else- {- context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));- }- }+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));}}++ if (p1.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes)+ continue;+ var combination = p1.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);+ if (combination != null)+ {+ //combination exists - check stock level+ var stockQuantity = stockQuantityService.GetTotalStockQuantityForCombination(p1, combination, warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockQuantity < qty)+ {+ context.AddFailure(stockQuantity <= 0+ ? string.Format(+ translationService.GetResource(+ "ShoppingCart.OutOfStock.BundleProduct"), p1.Name)+ : string.Format(+ translationService.GetResource(+ "ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name,+ stockQuantity));+ }+ }+ else+ {+ context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));+ }}}break;@@ -130,18 +126,14 @@ namespace Grand.Business.Checkout.Validatorsif (combination != null){//combination exists - check stock level- var stockquantity = stockQuantityService.GetTotalStockQuantityForCombination(value.Product, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockquantity < value.ShoppingCartItem.Quantity)+ var stockQuantity = stockQuantityService.GetTotalStockQuantityForCombination(value.Product, combination, warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockQuantity < value.ShoppingCartItem.Quantity){- int maximumQuantityCanBeAdded = stockquantity;- if (maximumQuantityCanBeAdded <= 0)- {- context.AddFailure(translationService.GetResource("ShoppingCart.OutOfStock"));- }- else- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));- }+ context.AddFailure(stockQuantity <= 0+ ? translationService.GetResource("ShoppingCart.OutOfStock")+ : string.Format(+ translationService.GetResource("ShoppingCart.QuantityExceedsStock"),+ stockQuantity));}}else@@ -156,8 +148,5 @@ namespace Grand.Business.Checkout.Validators}});}---}}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.csindex 3af482dc6..cb91a7c35 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs@@ -1,7 +1,6 @@using FluentValidation;using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Interfaces.Common.Security;using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;@@ -15,14 +14,12 @@ namespace Grand.Business.Checkout.Validatorspublic class ShoppingCartItemAttributeValidator : AbstractValidator<ShoppingCartItemAttributeValidatorRecord>{private readonly ITranslationService _translationService;- private readonly IAclService _aclService;private readonly IProductService _productService;private readonly IProductAttributeService _productAttributeService;- public ShoppingCartItemAttributeValidator(ITranslationService translationService, IAclService aclService, IProductService productService, IProductAttributeService productAttributeService)+ public ShoppingCartItemAttributeValidator(ITranslationService translationService, IProductService productService, IProductAttributeService productAttributeService){_translationService = translationService;- _aclService = aclService;_productService = productService;_productAttributeService = productAttributeService;@@ -31,7 +28,7 @@ namespace Grand.Business.Checkout.Validatorsvar warnings = await GetShoppingCartItemWarnings(value);if (warnings.Any()){- warnings.ToList().ForEach(x => context.AddFailure(x));+ warnings.ToList().ForEach(context.AddFailure);return;}@@ -40,11 +37,11 @@ namespace Grand.Business.Checkout.Validatorsvar attributeValues = value.Product.ParseProductAttributeValues(value.ShoppingCartItem.Attributes);foreach (var attributeValue in attributeValues){- var _productAttributeMapping = value.Product.ProductAttributeMappings.Where(x => x.ProductAttributeValues.Any(z => z.Id == attributeValue.Id)).FirstOrDefault();- //TODO - check value.Product.ProductAttributeMappings.Where(x => x.Id == attributeValue.ProductAttributeMappingId).FirstOrDefault();- if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct && _productAttributeMapping != null)+ var productAttributeMapping = value.Product.ProductAttributeMappings.FirstOrDefault(x => x.ProductAttributeValues.Any(z => z.Id == attributeValue.Id));+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct ||+ productAttributeMapping == null) continue;{- if (value.IgnoreNonCombinableAttributes && _productAttributeMapping.IsNonCombinable())+ if (value.IgnoreNonCombinableAttributes && productAttributeMapping.IsNonCombinable())continue;//associated product (bundle)@@ -53,16 +50,16 @@ namespace Grand.Business.Checkout.Validators{var totalQty = value.ShoppingCartItem.Quantity * attributeValue.Quantity;var associatedProductWarnings = await GetShoppingCartItemWarnings(- new ShoppingCartItemAttributeValidatorRecord(value.Customer, associatedProduct, new ShoppingCartItem() {+ value with { Product = associatedProduct, ShoppingCartItem = new ShoppingCartItem() {ShoppingCartTypeId = value.ShoppingCartItem.ShoppingCartTypeId,StoreId = value.ShoppingCartItem.Id,Quantity = totalQty,WarehouseId = value.ShoppingCartItem.WarehouseId,Attributes = value.ShoppingCartItem.Attributes- }, value.IgnoreNonCombinableAttributes));+ } });foreach (var associatedProductWarning in associatedProductWarnings){- var productAttribute = await productAttributeService.GetProductAttributeById(_productAttributeMapping.ProductAttributeId);+ var productAttribute = await productAttributeService.GetProductAttributeById(productAttributeMapping.ProductAttributeId);var attributeName = productAttribute.Name;var attributeValueName = attributeValue.Name;warnings.Add(string.Format(@@ -72,14 +69,12 @@ namespace Grand.Business.Checkout.Validators}else{- warnings.Add(string.Format("Associated product cannot be loaded - {0}", attributeValue.AssociatedProductId));+ warnings.Add($"Associated product cannot be loaded - {attributeValue.AssociatedProductId}");}- if (warnings.Any())- {- warnings.ToList().ForEach(x => context.AddFailure(x));- return;- }+ if (!warnings.Any()) continue;+ warnings.ToList().ForEach(context.AddFailure);+ return;}}});@@ -147,22 +142,14 @@ namespace Grand.Business.Checkout.Validators{if (a2.IsRequired){- bool found = false;+ var found = false;//selected product attributes- foreach (var a1 in attributes1)+ foreach (var attributeValuesStr in from a1 in attributes1 where a1.Id == a2.Id+ select ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, a1.Id)+ into attributeValuesStr+ where attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())) select attributeValuesStr){- if (a1.Id == a2.Id)- {- var attributeValuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, a1.Id);- foreach (string str1 in attributeValuesStr)- {- if (!string.IsNullOrEmpty(str1.Trim()))- {- found = true;- break;- }- }- }+ found = true;}//if not found@@ -209,37 +196,31 @@ namespace Grand.Business.Checkout.Validators//minimum lengthif (pam.ValidationMinLength.HasValue){- if (pam.AttributeControlTypeId == AttributeControlType.TextBox ||- pam.AttributeControlTypeId == AttributeControlType.MultilineTextbox)+ if (pam.AttributeControlTypeId is AttributeControlType.TextBox or AttributeControlType.MultilineTextbox){var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);var enteredText = valuesStr.FirstOrDefault();- int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;if (pam.ValidationMinLength.Value > enteredTextLength){- var _pam = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength"), _pam.Name, pam.ValidationMinLength.Value));+ var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength"), productAttribute.Name, pam.ValidationMinLength.Value));}}}-//maximum length- if (pam.ValidationMaxLength.HasValue)+ if (!pam.ValidationMaxLength.HasValue) continue;{- if (pam.AttributeControlTypeId == AttributeControlType.TextBox ||- pam.AttributeControlTypeId == AttributeControlType.MultilineTextbox)- {- var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);- var enteredText = valuesStr.FirstOrDefault();- int enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;-- if (pam.ValidationMaxLength.Value < enteredTextLength)- {- var _pam = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength"), _pam.Name, pam.ValidationMaxLength.Value));- }- }+ if (pam.AttributeControlTypeId != AttributeControlType.TextBox &&+ pam.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;+ var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);+ var enteredText = valuesStr.FirstOrDefault();+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;++ if (pam.ValidationMaxLength.Value >= enteredTextLength) continue;+ var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength"), productAttribute.Name, pam.ValidationMaxLength.Value));}}return warnings;diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.csindex ae38e9930..e55fc5c91 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs@@ -16,7 +16,7 @@ namespace Grand.Business.Checkout.Validatorspublic ShoppingCartRequiredProductValidator(ITranslationService translationService, IProductService productService, ShoppingCartSettings shoppingCartSettings){- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{var cart = value.Customer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == value.ShoppingCartItem.ShoppingCartTypeId).LimitPerStore(shoppingCartSettings.SharedCartBetweenStores, value.Store.Id)@@ -30,23 +30,9 @@ namespace Grand.Business.Checkout.ValidatorsrequiredProducts.Add(rp);}- foreach (var rp in requiredProducts)+ foreach (var rp in from rp in requiredProducts let alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id) where !alreadyInTheCart select rp){- //ensure that product is in the cart- bool alreadyInTheCart = false;- foreach (var sci in cart)- {- if (sci.ProductId == rp.Id)- {- alreadyInTheCart = true;- break;- }- }- //not in the cart- if (!alreadyInTheCart)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.Name));- }+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.Name));}});}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.csindex ed5e13b10..613471b09 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs@@ -15,26 +15,26 @@ namespace Grand.Business.Checkout.Validatorspublic ShoppingCartReservationProductValidator(ITranslationService translationService, IProductReservationService productReservationService){- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{if (!string.IsNullOrEmpty(value.ShoppingCartItem.ReservationId)){var reservations = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);- if (!value.Customer.ShoppingCartItems.Any(x => x.Id == value.ShoppingCartItem.Id))+ if (value.Customer.ShoppingCartItems.All(x => x.Id != value.ShoppingCartItem.Id)){- if (reservations.Where(x => x.ReservationId == value.ShoppingCartItem.ReservationId).Any())+ if (reservations.Any(x => x.ReservationId == value.ShoppingCartItem.ReservationId))context.AddFailure(translationService.GetResource("ShoppingCart.AlreadyReservation"));}}if (value.ShoppingCartItem.RentalStartDateUtc.HasValue && value.ShoppingCartItem.RentalEndDateUtc.HasValue){- var _canBeBook = false;+ var canBeBook = false;var reservations = await productReservationService.GetProductReservationsByProductId(value.Product.Id, true, null);var reserved = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);foreach (var item in reserved.Where(x => x.ShoppingCartItemId != value.ShoppingCartItem.Id)){- var match = reservations.Where(x => x.Id == item.ReservationId).FirstOrDefault();+ var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);if (match != null){reservations.Remove(match);@@ -44,37 +44,31 @@ namespace Grand.Business.Checkout.Validatorsvar grouped = reservations.GroupBy(x => x.Resource);foreach (var group in grouped){- bool groupCanBeBooked = true;+ var groupCanBeBooked = true;if (value.Product.IncBothDate && value.Product.IntervalUnitId == IntervalUnit.Day){for (DateTime iterator = value.ShoppingCartItem.RentalStartDateUtc.Value; iterator <= value.ShoppingCartItem.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0)){- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}}else{for (DateTime iterator = value.ShoppingCartItem.RentalStartDateUtc.Value; iterator < value.ShoppingCartItem.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0)){- if (!group.Select(x => x.Date).Contains(iterator))- {- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}}- if (groupCanBeBooked)- {- _canBeBook = true;- break;- }+ if (!groupCanBeBooked) continue;+ canBeBook = true;+ break;}- if (!_canBeBook)+ if (!canBeBook){context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod"));return;@@ -106,7 +100,7 @@ namespace Grand.Business.Checkout.Validators{if (!(value.ShoppingCartItem.RentalStartDateUtc.HasValue && value.ShoppingCartItem.RentalEndDateUtc.HasValue)){- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ChoosebothDates"));+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ChooseBothDates"));}else{@@ -144,11 +138,10 @@ namespace Grand.Business.Checkout.Validatorscontext.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationDeleted"));break;}- else if (!string.IsNullOrEmpty(reservation.OrderId))- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));- break;- }++ if (string.IsNullOrEmpty(reservation.OrderId)) continue;+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));+ break;}}}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.csindex 0cdb61730..0061169a7 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs@@ -60,7 +60,7 @@ namespace Grand.Business.Checkout.Validators//customer entered priceif (value.Product.EnteredPrice){- var shoppingCartItemEnteredPrice = value.ShoppingCartItem.EnteredPrice.HasValue ? value.ShoppingCartItem.EnteredPrice.Value : 0;+ var shoppingCartItemEnteredPrice = value.ShoppingCartItem.EnteredPrice ?? 0;if (shoppingCartItemEnteredPrice < value.Product.MinEnteredPrice ||shoppingCartItemEnteredPrice > value.Product.MaxEnteredPrice){@@ -71,7 +71,7 @@ namespace Grand.Business.Checkout.Validators}//availability dates- bool availableStartDateError = false;+ var availableStartDateError = false;if (value.Product.AvailableStartDateTimeUtc.HasValue){DateTime now = DateTime.UtcNow;@@ -82,7 +82,9 @@ namespace Grand.Business.Checkout.ValidatorsavailableStartDateError = true;}}- if (value.Product.AvailableEndDateTimeUtc.HasValue && !availableStartDateError && value.ShoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)++ if (!value.Product.AvailableEndDateTimeUtc.HasValue || availableStartDateError ||+ value.ShoppingCartItem.ShoppingCartTypeId != ShoppingCartType.ShoppingCart) return;{DateTime now = DateTime.UtcNow;DateTime availableEndDateTime = DateTime.SpecifyKind(value.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.csindex 2ed93defb..34218cff3 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs@@ -16,9 +16,9 @@ namespace Grand.Business.Checkout.Validatorspublic ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService){- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{- var hasStandartProducts = false;+ var hasStandardProducts = false;var hasRecurringProducts = false;var hasRecurringProductsMix = false;@@ -46,11 +46,11 @@ namespace Grand.Business.Checkout.ValidatorshasRecurringProductsMix = true;}else- hasStandartProducts = true;+ hasStandardProducts = true;}//don't mix standard and recurring products- if (hasStandartProducts && hasRecurringProducts)+ if (hasStandardProducts && hasRecurringProducts)context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts"));//don't mix recurring productsdiff --git a/src/Business/Grand.Business.Cms/Services/BlogService.cs b/src/Business/Grand.Business.Cms/Services/BlogService.csindex 6ce28e14b..832ec7eb5 100644--- a/src/Business/Grand.Business.Cms/Services/BlogService.cs+++ b/src/Business/Grand.Business.Cms/Services/BlogService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// Blog service/// </summary>- public partial class BlogService : IBlogService+ public class BlogService : IBlogService{#region Fields@@ -56,13 +56,14 @@ namespace Grand.Business.Cms.Services/// Gets all blog posts/// </summary>/// <param name="storeId">The store identifier; pass "" to load all records</param>- /// <param name="languageId">Language identifier; 0 if you want to get all records</param>/// <param name="dateFrom">Filter by created date; null if you want to get all records</param>/// <param name="dateTo">Filter by created date; null if you want to get all records</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value indicating whether to show hidden records</param>+ /// <param name="tag">Tag</param>/// <param name="blogPostName">Blog post name</param>+ /// <param name="categoryId">Category ident</param>/// <returns>Blog posts</returns>public virtual async Task<IPagedList<BlogPost>> GetAllBlogPosts(string storeId = "",DateTime? dateFrom = null, DateTime? dateTo = null,@@ -82,7 +83,7 @@ namespace Grand.Business.Cms.Services}}- if (!String.IsNullOrWhiteSpace(blogPostName))+ if (!string.IsNullOrWhiteSpace(blogPostName)){query = query.Where(b => (b.Title != null && b.Title.ToLower().Contains(blogPostName.ToLower())) ||@@ -100,11 +101,11 @@ namespace Grand.Business.Cms.Servicesquery = query.Where(b => !b.EndDateUtc.HasValue || b.EndDateUtc >= utcNow);}- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){query = query.Where(b => b.Stores.Contains(storeId) || !b.LimitedToStores);}- if (!(String.IsNullOrEmpty(tag)))+ if (!string.IsNullOrEmpty(tag)){query = query.Where(x => x.Tags.Contains(tag));}@@ -120,7 +121,6 @@ namespace Grand.Business.Cms.Services/// Gets all blog posts/// </summary>/// <param name="storeId">The store identifier; pass "" to load all records</param>- /// <param name="languageId">Language identifier. 0 if you want to get all news</param>/// <param name="tag">Tag</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>@@ -134,13 +134,7 @@ namespace Grand.Business.Cms.Services//we load all records and only then filter them by tagvar blogPostsAll = await GetAllBlogPosts(storeId: storeId, showHidden: showHidden, tag: tag);- var taggedBlogPosts = new List<BlogPost>();- foreach (var blogPost in blogPostsAll)- {- var tags = blogPost.ParseTags();- if (!String.IsNullOrEmpty(tags.FirstOrDefault(t => t.Equals(tag, StringComparison.OrdinalIgnoreCase))))- taggedBlogPosts.Add(blogPost);- }+ var taggedBlogPosts = (from blogPost in blogPostsAll let tags = blogPost.ParseTags() where !string.IsNullOrEmpty(tags.FirstOrDefault(t => t.Equals(tag, StringComparison.OrdinalIgnoreCase))) select blogPost).ToList();//server-side pagingreturn new PagedList<BlogPost>(taggedBlogPosts, pageIndex, pageSize);@@ -150,7 +144,6 @@ namespace Grand.Business.Cms.Services/// Gets all blog post tags/// </summary>/// <param name="storeId">The store identifier; pass "" to load all records</param>- /// <param name="languageId">Language identifier. 0 if you want to get all news</param>/// <param name="showHidden">A value indicating whether to show hidden records</param>/// <returns>Blog post tags</returns>public virtual async Task<IList<BlogPostTag>> GetAllBlogPostTags(string storeId, bool showHidden = false)@@ -161,7 +154,7 @@ namespace Grand.Business.Cms.Servicesforeach (var blogPost in blogPosts){var tags = blogPost.ParseTags();- foreach (string tag in tags)+ foreach (var tag in tags){var foundBlogPostTag = blogPostTags.Find(bpt => bpt.Name.Equals(tag, StringComparison.OrdinalIgnoreCase));if (foundBlogPostTag == null)@@ -229,6 +222,7 @@ namespace Grand.Business.Cms.Services/// Gets all comments/// </summary>/// <param name="customerId">Customer identifier; "" to load all records</param>+ /// <param name="storeId">Store ident</param>/// <returns>Comments</returns>public virtual async Task<IList<BlogComment>> GetAllComments(string customerId, string storeId){@@ -259,7 +253,7 @@ namespace Grand.Business.Cms.Servicesreturn await Task.FromResult(query.ToList());}-+ /// <summary>/// Get blog comments by identifiers/// </summary>/// <param name="commentIds">Blog comment identifiers</param>@@ -274,20 +268,14 @@ namespace Grand.Business.Cms.Servicesselect bc;var comments = query.ToList();//sort by passed identifiers- var sortedComments = new List<BlogComment>();- foreach (string id in commentIds)- {- var comment = comments.Find(x => x.Id == id);- if (comment != null)- sortedComments.Add(comment);- }+ var sortedComments = commentIds.Select(id => comments.Find(x => x.Id == id)).Where(comment => comment != null).ToList();return await Task.FromResult(sortedComments);}/// <summary>/// Inserts a blog post comment/// </summary>- /// <param name="blogPost">Blog post comment</param>+ /// <param name="blogComment">Blog post comment</param>public virtual async Task InsertBlogComment(BlogComment blogComment){if (blogComment == null)@@ -330,16 +318,16 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Get category by sename+ /// Get category by se-name/// </summary>- /// <param name="blogCategorySeName">Blog category sename</param>+ /// <param name="blogCategorySeName">Blog category se-name</param>/// <returns></returns>public virtual async Task<BlogCategory> GetBlogCategoryBySeName(string blogCategorySeName){if (string.IsNullOrEmpty(blogCategorySeName))throw new ArgumentNullException(nameof(blogCategorySeName));- return await Task.FromResult(_blogCategoryRepository.Table.Where(x => x.SeName == blogCategorySeName.ToLowerInvariant()).FirstOrDefault());+ return await Task.FromResult(_blogCategoryRepository.Table.FirstOrDefault(x => x.SeName == blogCategorySeName.ToLowerInvariant()));}/// <summary>@@ -351,7 +339,7 @@ namespace Grand.Business.Cms.Servicesvar query = from c in _blogCategoryRepository.Tableselect c;- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){query = query.Where(b => b.Stores.Contains(storeId) || !b.LimitedToStores);}@@ -441,7 +429,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// Update an blog product/// </summary>- /// <param name="blogPostProduct">Blog product</param>+ /// <param name="blogProduct">Blog product</param>public virtual async Task UpdateBlogProduct(BlogProduct blogProduct){if (blogProduct == null)diff --git a/src/Business/Grand.Business.Cms/Services/CookiePreference.cs b/src/Business/Grand.Business.Cms/Services/CookiePreference.csindex bdded6489..48bccaae5 100644--- a/src/Business/Grand.Business.Cms/Services/CookiePreference.cs+++ b/src/Business/Grand.Business.Cms/Services/CookiePreference.cs@@ -25,11 +25,11 @@ namespace Grand.Business.Cms.Servicespublic virtual async Task<bool?> IsEnable(Customer customer, Store store, string cookieSystemName){- bool? result = default(bool?);+ var result = default(bool?);var savedCookiesConsent = await _userFieldService.GetFieldsForEntity<Dictionary<string, bool>>(customer, SystemCustomerFieldNames.ConsentCookies, store.Id);- if (savedCookiesConsent != null)- if (savedCookiesConsent.ContainsKey(cookieSystemName))- result = savedCookiesConsent[cookieSystemName];+ if (savedCookiesConsent == null) return null;+ if (savedCookiesConsent.ContainsKey(cookieSystemName))+ result = savedCookiesConsent[cookieSystemName];return result;}diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.csindex a009a7e55..bfbc03930 100644--- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs+++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs@@ -42,9 +42,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Deletes knowledgebase category+ /// Deletes knowledge base category/// </summary>- /// <param name="id"></param>+ /// <param name="kc"></param>public virtual async Task DeleteKnowledgebaseCategory(KnowledgebaseCategory kc){var children = _knowledgebaseCategoryRepository.Table.Where(x => x.ParentCategoryId == kc.Id).ToList();@@ -62,7 +62,7 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Edits knowledgebase category+ /// Edits knowledge base category/// </summary>/// <param name="kc"></param>public virtual async Task UpdateKnowledgebaseCategory(KnowledgebaseCategory kc)@@ -75,23 +75,23 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase category+ /// Gets knowledge base category/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase category</returns>+ /// <returns>knowledge base category</returns>public virtual async Task<KnowledgebaseCategory> GetKnowledgebaseCategory(string id){- return await Task.FromResult(_knowledgebaseCategoryRepository.Table.Where(x => x.Id == id).FirstOrDefault());+ return await Task.FromResult(_knowledgebaseCategoryRepository.Table.FirstOrDefault(x => x.Id == id));}/// <summary>- /// Gets knowledgebase category+ /// Gets knowledge base category/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase category</returns>+ /// <returns>knowledge base category</returns>public virtual async Task<KnowledgebaseCategory> GetPublicKnowledgebaseCategory(string id){- string key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORY_BY_ID, id, _workContext.CurrentCustomer.GetCustomerGroupIds(),+ var key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORY_BY_ID, id, _workContext.CurrentCustomer.GetCustomerGroupIds(),_workContext.CurrentStore.Id);return await _cacheBase.GetAsync(key, async () =>{@@ -124,7 +124,7 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Inserts knowledgebase category+ /// Inserts knowledge base category/// </summary>/// <param name="kc"></param>public virtual async Task InsertKnowledgebaseCategory(KnowledgebaseCategory kc)@@ -141,9 +141,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase categories+ /// Gets knowledge base categories/// </summary>- /// <returns>List of knowledgebase categories</returns>+ /// <returns>List of knowledge base categories</returns>public virtual async Task<List<KnowledgebaseCategory>> GetKnowledgebaseCategories(){var categories = _knowledgebaseCategoryRepository.Table.OrderBy(x => x.ParentCategoryId).ThenBy(x => x.DisplayOrder).ToList();@@ -151,27 +151,24 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase article+ /// Gets knowledge base article/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase article</returns>+ /// <returns>knowledge base article</returns>public virtual Task<KnowledgebaseArticle> GetKnowledgebaseArticle(string id){return _knowledgebaseArticleRepository.GetByIdAsync(id);}/// <summary>- /// Gets knowledgebase articles+ /// Gets knowledge base articles/// </summary>- /// <returns>List of knowledgebase articles</returns>+ /// <returns>List of knowledge base articles</returns>/// <param name="storeId">Store ident</param>public virtual async Task<List<KnowledgebaseArticle>> GetKnowledgebaseArticles(string storeId = ""){var query = from p in _knowledgebaseArticleRepository.Tableselect p;-- var customer = _workContext.CurrentCustomer;-if (!CommonHelper.IgnoreAcl){var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();@@ -192,7 +189,7 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Inserts knowledgebase article+ /// Inserts knowledge base article/// </summary>/// <param name="ka"></param>public virtual async Task InsertKnowledgebaseArticle(KnowledgebaseArticle ka)@@ -206,7 +203,7 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Edits knowledgebase article+ /// Edits knowledge base article/// </summary>/// <param name="ka"></param>public virtual async Task UpdateKnowledgebaseArticle(KnowledgebaseArticle ka)@@ -219,9 +216,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Deletes knowledgebase article+ /// Deletes knowledge base article/// </summary>- /// <param name="id"></param>+ /// <param name="ka"></param>public virtual async Task DeleteKnowledgebaseArticle(KnowledgebaseArticle ka){await _knowledgebaseArticleRepository.DeleteAsync(ka);@@ -231,10 +228,11 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase articles by category id+ /// Gets knowledge base articles by category id/// </summary>/// <param name="id"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>public virtual async Task<IPagedList<KnowledgebaseArticle>> GetKnowledgebaseArticlesByCategoryId(string id, int pageIndex = 0, int pageSize = int.MaxValue){var articles = await Task.FromResult(_knowledgebaseArticleRepository.Table.Where(x => x.ParentCategoryId == id).OrderBy(x => x.DisplayOrder).ToList());@@ -242,7 +240,7 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets public(published etc) knowledgebase categories+ /// Gets public(published etc) knowledge base categories/// </summary>/// <returns>List of public knowledgebase categories</returns>public virtual async Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategories()@@ -278,9 +276,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets public(published etc) knowledgebase articles+ /// Gets public(published etc) knowledge base articles/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles(){var key = string.Format(CacheKey.ARTICLES, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -315,9 +313,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase article if it is published etc+ /// Gets knowledge base article if it is published etc/// </summary>- /// <returns>knowledgebase article</returns>+ /// <returns>knowledge base article</returns>public virtual async Task<KnowledgebaseArticle> GetPublicKnowledgebaseArticle(string id){var key = string.Format(CacheKey.ARTICLE_BY_ID, id, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -351,9 +349,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets public(published etc) knowledgebase articles for category id+ /// Gets public(published etc) knowledge base articles for category id/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByCategory(string categoryId){var key = string.Format(CacheKey.ARTICLES_BY_CATEGORY_ID, categoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -377,7 +375,6 @@ namespace Grand.Business.Cms.Servicesif (!CommonHelper.IgnoreStoreLimitations){//Store acl- var currentStoreId = new List<string> { _workContext.CurrentStore.Id };query = from p in querywhere !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)select p;@@ -388,9 +385,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets public(published etc) knowledgebase articles for keyword+ /// Gets public(published etc) knowledge base articles for keyword/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByKeyword(string keyword){var key = string.Format(CacheKey.ARTICLES_BY_KEYWORD, keyword, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -417,7 +414,6 @@ namespace Grand.Business.Cms.Servicesif (!CommonHelper.IgnoreStoreLimitations){//Store acl- var currentStoreId = new List<string> { _workContext.CurrentStore.Id };query = from p in querywhere !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)select p;@@ -428,9 +424,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets public(published etc) knowledgebase categories for keyword+ /// Gets public(published etc) knowledge base categories for keyword/// </summary>- /// <returns>List of public knowledgebase categories</returns>+ /// <returns>List of public knowledge base categories</returns>public virtual async Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategoriesByKeyword(string keyword){var key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORIES_BY_KEYWORD, keyword, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -458,7 +454,7 @@ namespace Grand.Business.Cms.Services//Store aclquery = from p in querywhere !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)- select p; ;+ select p;}query = query.OrderBy(x => x.DisplayOrder);return await Task.FromResult(query.ToList());@@ -467,9 +463,9 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets homepage knowledgebase articles+ /// Gets homepage knowledge base articles/// </summary>- /// <returns>List of homepage knowledgebase articles</returns>+ /// <returns>List of homepage knowledge base articles</returns>public virtual async Task<List<KnowledgebaseArticle>> GetHomepageKnowledgebaseArticles(){var key = string.Format(CacheKey.HOMEPAGE_ARTICLES, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),@@ -504,10 +500,11 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets knowledgebase articles by name+ /// Gets knowledge base articles by name/// </summary>/// <param name="name"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>public virtual async Task<IPagedList<KnowledgebaseArticle>> GetKnowledgebaseArticlesByName(string name, int pageIndex = 0, int pageSize = int.MaxValue){var query = from p in _knowledgebaseArticleRepository.Table@@ -531,10 +528,8 @@ namespace Grand.Business.Cms.Services}/// <summary>- /// Gets related knowledgebase articles+ /// Gets related knowledge base articles/// </summary>- /// <param name="name"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>public virtual async Task<IPagedList<KnowledgebaseArticle>> GetRelatedKnowledgebaseArticles(string articleId, int pageIndex = 0, int pageSize = int.MaxValue){var article = await GetKnowledgebaseArticle(articleId);@@ -574,7 +569,7 @@ namespace Grand.Business.Cms.Services{var query = from c in _articleCommentRepository.Tableorderby c.CreatedOnUtc- where (customerId == "" || c.CustomerId == customerId)+ where customerId == "" || c.CustomerId == customerIdselect c;return await Task.FromResult(query.ToList());}@@ -592,7 +587,6 @@ namespace Grand.Business.Cms.Services/// <summary>/// Get article comments by identifiers/// </summary>- /// <param name="commentIds"Article comment identifiers</param>/// <returns>Article comments</returns>public virtual async Task<IList<KnowledgebaseArticleComment>> GetArticleCommentsByIds(string[] commentIds){@@ -605,7 +599,7 @@ namespace Grand.Business.Cms.Servicesvar comments = query.ToList();//sort by passed identifiersvar sortedComments = new List<KnowledgebaseArticleComment>();- foreach (string id in commentIds)+ foreach (var id in commentIds){var comment = comments.Find(x => x.Id == id);if (comment != null)diff --git a/src/Business/Grand.Business.Cms/Services/NewsService.cs b/src/Business/Grand.Business.Cms/Services/NewsService.csindex 94a7d5112..f476817f7 100644--- a/src/Business/Grand.Business.Cms/Services/NewsService.cs+++ b/src/Business/Grand.Business.Cms/Services/NewsService.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// News service/// </summary>- public partial class NewsService : INewsService+ public class NewsService : INewsService{#region Fields@@ -55,16 +55,17 @@ namespace Grand.Business.Cms.Services/// <param name="storeId">Store identifier; 0 if you want to get all records</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>+ /// <param name="ignoreAcl"></param>/// <param name="showHidden">A value indicating whether to show hidden records</param>/// <param name="newsTitle">News title</param>/// <returns>News items</returns>public virtual async Task<IPagedList<NewsItem>> GetAllNews(string storeId = "",- int pageIndex = 0, int pageSize = int.MaxValue, bool ignorAcl = false, bool showHidden = false, string newsTitle = "")+ int pageIndex = 0, int pageSize = int.MaxValue, bool ignoreAcl = false, bool showHidden = false, string newsTitle = ""){var query = from p in _newsItemRepository.Tableselect p;- if (!String.IsNullOrWhiteSpace(newsTitle))+ if (!string.IsNullOrWhiteSpace(newsTitle))query = query.Where(n => n.Title != null && n.Title.ToLower().Contains(newsTitle.ToLower()));if (!showHidden)@@ -75,10 +76,10 @@ namespace Grand.Business.Cms.Servicesquery = query.Where(n => !n.EndDateUtc.HasValue || n.EndDateUtc >= utcNow);}- if ((!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||- (!ignorAcl && !CommonHelper.IgnoreAcl))+ if ((!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||+ (!ignoreAcl && !CommonHelper.IgnoreAcl)){- if (!ignorAcl && !CommonHelper.IgnoreAcl)+ if (!ignoreAcl && !CommonHelper.IgnoreAcl){var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();query = from p in query@@ -86,7 +87,7 @@ namespace Grand.Business.Cms.Servicesselect p;}//Store acl- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations){query = from p in querywhere !p.LimitedToStores || p.Stores.Contains(storeId)@@ -154,7 +155,7 @@ namespace Grand.Business.Cms.Servicesvar query2 = from c in queryorderby c.CreatedOnUtc- where (customerId == "" || c.CustomerId == customerId)+ where customerId == "" || c.CustomerId == customerIdselect c;return await Task.FromResult(query2.ToList());diff --git a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs b/src/Business/Grand.Business.Cms/Services/PageLayoutService.csindex c6f92d087..bb322a14e 100644--- a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs+++ b/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// Page layout service/// </summary>- public partial class PageLayoutService : IPageLayoutService+ public class PageLayoutService : IPageLayoutService{#region Fields@@ -66,7 +66,7 @@ namespace Grand.Business.Cms.Services/// <returns>Page layout</returns>public virtual Task<PageLayout> GetPageLayoutById(string pageLayoutId){- string key = string.Format(CacheKey.PAGE_LAYOUT_BY_ID_KEY, pageLayoutId);+ var key = string.Format(CacheKey.PAGE_LAYOUT_BY_ID_KEY, pageLayoutId);return _cacheBase.GetAsync(key, () => _pageLayoutRepository.GetByIdAsync(pageLayoutId));}diff --git a/src/Business/Grand.Business.Cms/Services/PageService.cs b/src/Business/Grand.Business.Cms/Services/PageService.csindex 348c73161..07fd0d8fa 100644--- a/src/Business/Grand.Business.Cms/Services/PageService.cs+++ b/src/Business/Grand.Business.Cms/Services/PageService.cs@@ -15,7 +15,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// Page service/// </summary>- public partial class PageService : IPageService+ public class PageService : IPageService{#region Fields@@ -53,7 +53,7 @@ namespace Grand.Business.Cms.Services/// <returns>Page</returns>public virtual Task<Page> GetPageById(string pageId){- string key = string.Format(CacheKey.PAGES_BY_ID_KEY, pageId);+ var key = string.Format(CacheKey.PAGES_BY_ID_KEY, pageId);return _cacheBase.GetAsync(key, () => _pageRepository.GetByIdAsync(pageId));}@@ -68,7 +68,7 @@ namespace Grand.Business.Cms.Servicesif (string.IsNullOrEmpty(systemName))return null;- string key = string.Format(CacheKey.PAGES_BY_SYSTEMNAME, systemName, storeId);+ var key = string.Format(CacheKey.PAGES_BY_SYSTEMNAME, systemName, storeId);return await _cacheBase.GetAsync(key, async () =>{@@ -78,7 +78,7 @@ namespace Grand.Business.Cms.Servicesquery = query.Where(t => t.SystemName.ToLower() == systemName.ToLower());query = query.OrderBy(t => t.Id);var pages = await Task.FromResult(query.ToList());- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId)){pages = pages.Where(x => _aclService.Authorize(x, storeId)).ToList();}@@ -90,10 +90,11 @@ namespace Grand.Business.Cms.Services/// Gets all pages/// </summary>/// <param name="storeId">Store identifier; pass "" to load all records</param>+ /// <param name="ignoreAcl"></param>/// <returns>Pages</returns>- public virtual async Task<IList<Page>> GetAllPages(string storeId, bool ignorAcl = false)+ public virtual async Task<IList<Page>> GetAllPages(string storeId, bool ignoreAcl = false){- string key = string.Format(CacheKey.PAGES_ALL_KEY, storeId, ignorAcl);+ var key = string.Format(CacheKey.PAGES_ALL_KEY, storeId, ignoreAcl);return await _cacheBase.GetAsync(key, async () =>{var query = from p in _pageRepository.Table@@ -101,25 +102,24 @@ namespace Grand.Business.Cms.Servicesquery = query.OrderBy(t => t.DisplayOrder).ThenBy(t => t.SystemName);- if ((!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||- (!ignorAcl && !CommonHelper.IgnoreAcl))+ if ((string.IsNullOrEmpty(storeId) || CommonHelper.IgnoreStoreLimitations) &&+ (ignoreAcl || CommonHelper.IgnoreAcl)) return await Task.FromResult(query.ToList());{- if (!ignorAcl && !CommonHelper.IgnoreAcl)+ if (!ignoreAcl && !CommonHelper.IgnoreAcl){var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;}//Store acl- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)- {- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;+ if (string.IsNullOrEmpty(storeId) || CommonHelper.IgnoreStoreLimitations)+ return await Task.FromResult(query.ToList());+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ select p;- query = query.OrderBy(t => t.SystemName);- }+ query = query.OrderBy(t => t.SystemName);}return await Task.FromResult(query.ToList());});diff --git a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.csindex 75573b792..cfadaba8c 100644--- a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs+++ b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs@@ -8,7 +8,7 @@ using MediatR;namespace Grand.Business.Cms.Services{- public partial class RobotsTxtService : IRobotsTxtService+ public class RobotsTxtService : IRobotsTxtService{#region Fieldsdiff --git a/src/Business/Grand.Business.Cms/Services/WidgetService.cs b/src/Business/Grand.Business.Cms/Services/WidgetService.csindex 93d9c35d8..8ae4f155a 100644--- a/src/Business/Grand.Business.Cms/Services/WidgetService.cs+++ b/src/Business/Grand.Business.Cms/Services/WidgetService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Cms.Services/// <summary>/// Widget service/// </summary>- public partial class WidgetService : IWidgetService+ public class WidgetService : IWidgetService{#region Fieldsdiff --git a/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs b/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.csindex 3daf14c60..3bc44b7b8 100644--- a/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs@@ -30,12 +30,10 @@ namespace Grand.Business.Common.Events{foreach (var activeLanguage in await _languageService.GetAllLanguages()){- if (activeLanguage.Id != notification.Entity.Id)- {- _languageSettings.DefaultAdminLanguageId = activeLanguage.Id;- await _settingService.SaveSetting(_languageSettings);- break;- }+ if (activeLanguage.Id == notification.Entity.Id) continue;+ _languageSettings.DefaultAdminLanguageId = activeLanguage.Id;+ await _settingService.SaveSetting(_languageSettings);+ break;}}diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.csindex 1080e69f0..0cdad4bda 100644--- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs+++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Common.Services.Addresses/// <summary>/// Address attribute parser/// </summary>- public partial class AddressAttributeParser : IAddressAttributeParser+ public class AddressAttributeParser : IAddressAttributeParser{private readonly IAddressAttributeService _addressAttributeService;private readonly ITranslationService _translationService;@@ -28,7 +28,7 @@ namespace Grand.Business.Common.Services.Addresses/// <summary>/// Gets selected address attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Selected address attributes</returns>public virtual async Task<IList<AddressAttribute>> ParseAddressAttributes(IList<CustomAttribute> customAttributes){@@ -50,7 +50,7 @@ namespace Grand.Business.Common.Services.Addresses/// <summary>/// Get address attribute values/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Address attribute values</returns>public virtual async Task<IList<AddressAttributeValue>> ParseAddressAttributeValues(IList<CustomAttribute> customAttributes){@@ -65,15 +65,7 @@ namespace Grand.Business.Common.Services.Addressescontinue;var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- foreach (var valueStr in valuesStr)- {- if (!string.IsNullOrEmpty(valueStr))- {- var value = attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == valueStr);- if (value != null)- values.Add(value);- }- }+ values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr) select attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);}return values;}@@ -81,24 +73,21 @@ namespace Grand.Business.Common.Services.Addresses/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="attribute">Address attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>public virtual IList<CustomAttribute> AddAddressAttribute(IList<CustomAttribute> customAttributes, AddressAttribute attribute, string value){- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();-- customAttributes.Add(new CustomAttribute() { Key = attribute.Id, Value = value });-+ customAttributes ??= new List<CustomAttribute>();+ customAttributes.Add(new CustomAttribute { Key = attribute.Id, Value = value });return customAttributes;}/// <summary>/// Validates address attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Warnings</returns>public virtual async Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes){@@ -111,33 +100,23 @@ namespace Grand.Business.Common.Services.Addressesvar attributes2 = await _addressAttributeService.GetAllAddressAttributes();foreach (var a2 in attributes2){- if (a2.IsRequired)+ if (!a2.IsRequired) continue;+ var found = false;+ //selected address attributes+ foreach (var a1 in attributes1){- bool found = false;- //selected address attributes- foreach (var a1 in attributes1)+ if (a1.Id != a2.Id) continue;+ var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);+ if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))){- if (a1.Id == a2.Id)- {- var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);- foreach (var str1 in valuesStr)- {- if (!string.IsNullOrEmpty(str1.Trim()))- {- found = true;- break;- }- }- }- }-- //if not found- if (!found)- {- var notFoundWarning = string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetTranslation(a => a.Name, ""));- warnings.Add(notFoundWarning);+ found = true;}}++ //if not found+ if (found) continue;+ var notFoundWarning = string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetTranslation(a => a.Name, ""));+ warnings.Add(notFoundWarning);}return warnings;@@ -147,14 +126,14 @@ namespace Grand.Business.Common.Services.Addresses/// Formats attributes/// </summary>/// <param name="language">Languages</param>- /// <param name="attributes">Attributes</param>- /// <param name="serapator">Serapator</param>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(Language language,IList<CustomAttribute> customAttributes,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true){var result = new StringBuilder();@@ -162,26 +141,26 @@ namespace Grand.Business.Common.Services.Addressesreturn result.ToString();var attributes = await ParseAddressAttributes(customAttributes);- for (int i = 0; i < attributes.Count; i++)+ for (var i = 0; i < attributes.Count; i++){var attribute = attributes[i];var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();- for (int j = 0; j < valuesStr.Count; j++)+ for (var j = 0; j < valuesStr.Count; j++){- string valueStr = valuesStr[j];- string formattedAttribute = "";+ var valueStr = valuesStr[j];+ var formattedAttribute = "";if (!attribute.ShouldHaveValues()){//no valuesif (attribute.AttributeControlType == AttributeControlType.MultilineTextbox){- //multiline textbox+ //multiline text boxvar attributeName = attribute.GetTranslation(a => a.Name, language.Id);//encode (if required)if (htmlEncode)attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));- //we never encode multiline textbox input+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input}else if (attribute.AttributeControlType == AttributeControlType.FileUpload){@@ -190,8 +169,8 @@ namespace Grand.Business.Common.Services.Addresses}else{- //other attributes (textbox, datepicker)- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), valueStr);+ //other attributes (text box, datepicker)+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);@@ -199,28 +178,25 @@ namespace Grand.Business.Common.Services.Addresses}else{- string attributeValueId = valueStr;+ var attributeValueId = valueStr;var attributeValue = attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == attributeValueId);if (attributeValue != null){- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), attributeValue.GetTranslation(a => a.Name, language.Id));+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";}//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}- if (!string.IsNullOrEmpty(formattedAttribute))- {- if (i != 0 || j != 0)- result.Append(serapator);- result.Append(formattedAttribute);- }+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}}-return result.ToString();}-}}diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.csindex c29c0ede8..450b64c43 100644--- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs+++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Common.Services.Addresses/// <summary>/// Address attribute service/// </summary>- public partial class AddressAttributeService : IAddressAttributeService+ public class AddressAttributeService : IAddressAttributeService{#region Fields@@ -49,7 +49,7 @@ namespace Grand.Business.Common.Services.Addresses/// <returns>Address attributes</returns>public virtual async Task<IList<AddressAttribute>> GetAllAddressAttributes(){- string key = CacheKey.ADDRESSATTRIBUTES_ALL_KEY;+ var key = CacheKey.ADDRESSATTRIBUTES_ALL_KEY;return await _cacheBase.GetAsync(key, async () =>{var query = from aa in _addressAttributeRepository.Table@@ -66,10 +66,10 @@ namespace Grand.Business.Common.Services.Addresses/// <returns>Address attribute</returns>public virtual async Task<AddressAttribute> GetAddressAttributeById(string addressAttributeId){- if (String.IsNullOrEmpty(addressAttributeId))+ if (string.IsNullOrEmpty(addressAttributeId))return null;- string key = string.Format(CacheKey.ADDRESSATTRIBUTES_BY_ID_KEY, addressAttributeId);+ var key = string.Format(CacheKey.ADDRESSATTRIBUTES_BY_ID_KEY, addressAttributeId);return await _cacheBase.GetAsync(key, () => _addressAttributeRepository.GetByIdAsync(addressAttributeId));}diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.csindex 24bb632a4..9b2cc36de 100644--- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs+++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Common.Services.Configuration/// <summary>/// Setting manager/// </summary>- public partial class SettingService : ISettingService+ public class SettingService : ISettingService{#region Fields@@ -40,7 +40,7 @@ namespace Grand.Business.Common.Services.Configuration/// <summary>/// Gets a setting by identifier/// </summary>- /// <param name="settingId">Setting identifier</param>+ /// <param name="name">Setting name</param>/// <returns>Setting</returns>private IList<Setting> GetSettingsByName(string name){@@ -131,22 +131,14 @@ namespace Grand.Business.Common.Services.Configurationreturn defaultValue;var keyCache = string.Format(CacheKey.SETTINGS_BY_KEY, key, storeId);- return _cacheBase.Get<T>(keyCache, () =>+ return _cacheBase.Get(keyCache, () =>{var settings = GetSettingsByName(key);key = key.Trim().ToLowerInvariant();- if (settings.Any())- {- var setting = settings.FirstOrDefault(x => x.StoreId == storeId);- //load default value?- if (setting == null)- setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));-- if (setting != null)- return JsonSerializer.Deserialize<T>(setting.Metadata);- }-- return defaultValue;+ if (!settings.Any()) return defaultValue;++ var setting = settings.FirstOrDefault(x => x.StoreId == storeId) ?? settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));+ return setting != null ? JsonSerializer.Deserialize<T>(setting.Metadata) : defaultValue;});}@@ -161,7 +153,7 @@ namespace Grand.Business.Common.Services.Configurationpublic virtual async Task SetSetting<T>(string key, T value, string storeId = "", bool clearCache = true){if (key == null)- throw new ArgumentNullException("key");+ throw new ArgumentNullException(nameof(key));key = key.Trim().ToLowerInvariant();@@ -212,19 +204,17 @@ namespace Grand.Business.Common.Services.Configuration/// <param name="storeId">Store identifier for which settings should be loaded</param>public virtual ISettings LoadSetting(Type type, string storeId = ""){- string key = string.Format(CacheKey.SETTINGS_BY_KEY, type.Name, storeId);+ var key = string.Format(CacheKey.SETTINGS_BY_KEY, type.Name, storeId);return _cacheBase.Get(key, () =>{var settings = GetSettingsByName(type.Name);- if (settings.Any())- {- var setting = settings.FirstOrDefault(x => x.StoreId == storeId);+ if (!settings.Any()) return Activator.CreateInstance(type) as ISettings;+ var setting = settings.FirstOrDefault(x => x.StoreId == storeId);- if (setting == null && !string.IsNullOrEmpty(storeId))- setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));+ if (setting == null && !string.IsNullOrEmpty(storeId))+ setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));- return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;- }+ if (setting != null) return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;return Activator.CreateInstance(type) as ISettings;});}@@ -237,8 +227,8 @@ namespace Grand.Business.Common.Services.Configuration/// <param name="settings">Setting instance</param>public virtual async Task SaveSetting<T>(T settings, string storeId = "") where T : ISettings, new(){- var dbsettings = GetSettingsByName(typeof(T).Name);- var setting = dbsettings.Any() ? dbsettings.FirstOrDefault(x => x.StoreId == storeId) : null;+ var dbSettings = GetSettingsByName(typeof(T).Name);+ var setting = dbSettings.Any() ? dbSettings.FirstOrDefault(x => x.StoreId == storeId) : null;if (setting != null){//updatediff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.csindex 7a2d32d73..f25a233f7 100644--- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Country service/// </summary>- public partial class CountryService : ICountryService+ public class CountryService : ICountryService{#region Fields@@ -54,7 +54,7 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Countries</returns>public virtual async Task<IList<Country>> GetAllCountries(string languageId = "", string storeId = "", bool showHidden = false){- string key = string.Format(CacheKey.COUNTRIES_ALL_KEY, languageId, storeId, showHidden);+ var key = string.Format(CacheKey.COUNTRIES_ALL_KEY, languageId, storeId, showHidden);return await _cacheBase.GetAsync(key, async () =>{@@ -139,14 +139,7 @@ namespace Grand.Business.Common.Services.Directoryselect c;var countries = await Task.FromResult(query.ToList());//sort by passed identifiers- var sortedCountries = new List<Country>();- foreach (string id in countryIds)- {- var country = countries.Find(x => x.Id == id);- if (country != null)- sortedCountries.Add(country);- }- return sortedCountries;+ return countryIds.Select(id => countries.Find(x => x.Id == id)).Where(country => country != null).ToList();}/// <summary>@@ -159,7 +152,7 @@ namespace Grand.Business.Common.Services.Directoryvar key = string.Format(CacheKey.COUNTRIES_BY_TWOLETTER, twoLetterIsoCode);return await _cacheBase.GetAsync(key, async () =>{- return await Task.FromResult(_countryRepository.Table.Where(x => x.TwoLetterIsoCode == twoLetterIsoCode).FirstOrDefault());+ return await Task.FromResult(_countryRepository.Table.FirstOrDefault(x => x.TwoLetterIsoCode == twoLetterIsoCode));});}@@ -173,7 +166,7 @@ namespace Grand.Business.Common.Services.Directoryvar key = string.Format(CacheKey.COUNTRIES_BY_THREELETTER, threeLetterIsoCode);return await _cacheBase.GetAsync(key, async () =>{- return await Task.FromResult(_countryRepository.Table.Where(x => x.ThreeLetterIsoCode == threeLetterIsoCode).FirstOrDefault());+ return await Task.FromResult(_countryRepository.Table.FirstOrDefault(x => x.ThreeLetterIsoCode == threeLetterIsoCode));});}@@ -284,11 +277,14 @@ namespace Grand.Business.Common.Services.Directoryif (country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id) != null){var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);- state.Name = stateProvince.Name;- state.Locales = stateProvince.Locales;- state.Published = stateProvince.Published;- state.Abbreviation = stateProvince.Abbreviation;- state.DisplayOrder = stateProvince.DisplayOrder;+ if (state != null)+ {+ state.Name = stateProvince.Name;+ state.Locales = stateProvince.Locales;+ state.Published = stateProvince.Published;+ state.Abbreviation = stateProvince.Abbreviation;+ state.DisplayOrder = stateProvince.DisplayOrder;+ }}await UpdateCountry(country);}diff --git a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.csindex ad8bfc929..13f89e431 100644--- a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Currency service/// </summary>- public partial class CurrencyService : ICurrencyService+ public class CurrencyService : ICurrencyService{#region Fields@@ -61,7 +61,7 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Currency</returns>public virtual Task<Currency> GetCurrencyById(string currencyId){- string key = string.Format(CacheKey.CURRENCIES_BY_ID_KEY, currencyId);+ var key = string.Format(CacheKey.CURRENCIES_BY_ID_KEY, currencyId);return _cacheBase.GetAsync(key, () => _currencyRepository.GetByIdAsync(currencyId));}@@ -71,10 +71,7 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Currency</returns>public async Task<Currency> GetPrimaryStoreCurrency(){- if (_primaryCurrency == null)- _primaryCurrency = await GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);-- return _primaryCurrency;+ return _primaryCurrency ??= await GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);}/// <summary>@@ -83,10 +80,7 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Currency</returns>public async Task<Currency> GetPrimaryExchangeRateCurrency(){- if (_primaryExchangeRateCurrency == null)- _primaryExchangeRateCurrency = await GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);-- return _primaryExchangeRateCurrency;+ return _primaryExchangeRateCurrency ??= await GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);}/// <summary>@@ -117,7 +111,7 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Currencies</returns>public virtual async Task<IList<Currency>> GetAllCurrencies(bool showHidden = false, string storeId = ""){- string key = string.Format(CacheKey.CURRENCIES_ALL_KEY, showHidden);+ var key = string.Format(CacheKey.CURRENCIES_ALL_KEY, showHidden);var currencies = await _cacheBase.GetAsync(key, async () =>{var query = from p in _currencyRepository.Table@@ -244,11 +238,11 @@ namespace Grand.Business.Common.Services.Directoryif (primaryExchangeRateCurrency == null)throw new Exception("Primary exchange rate currency cannot be loaded");- double result = amount;- double exchangeRate = sourceCurrencyCode.Rate;+ var result = amount;+ var exchangeRate = sourceCurrencyCode.Rate;if (exchangeRate == 0)- throw new GrandException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));- result = result / exchangeRate;+ throw new GrandException($"Exchange rate not found for currency [{sourceCurrencyCode.Name}]");+ result /= exchangeRate;return result;}@@ -267,13 +261,13 @@ namespace Grand.Business.Common.Services.Directoryif (primaryExchangeRateCurrency == null)throw new Exception("Primary exchange rate currency cannot be loaded");- double result = amount;+ var result = amount;- double exchangeRate = targetCurrencyCode.Rate;+ var exchangeRate = targetCurrencyCode.Rate;if (exchangeRate == 0)- throw new GrandException(string.Format("Exchange rate not found for currency [{0}]", targetCurrencyCode.Name));+ throw new GrandException($"Exchange rate not found for currency [{targetCurrencyCode.Name}]");- result = result * exchangeRate;+ result *= exchangeRate;return result;}diff --git a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.csindex 3ec7ebc06..c362f449d 100644--- a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Represents a datetime service/// </summary>- public partial class DateTimeService : IDateTimeService+ public class DateTimeService : IDateTimeService{private readonly DateTimeSettings _dateTimeSettings;private TimeZoneInfo _timeZoneInfo;@@ -44,7 +44,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Converts the date and time to current user date and time/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>public virtual DateTime ConvertToUserTime(DateTime dt){@@ -54,8 +54,8 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Converts the date and time to current user date and time/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>- /// <param name="sourceDateTimeKind">The source datetimekind</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>+ /// <param name="sourceDateTimeKind">The source datetime kind</param>/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>public virtual DateTime ConvertToUserTime(DateTime dt, DateTimeKind sourceDateTimeKind){@@ -79,7 +79,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Converts the date and time to Coordinated Universal Time (UTC)/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>public virtual DateTime ConvertToUtcTime(DateTime dt){@@ -89,8 +89,8 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// Converts the date and time to Coordinated Universal Time (UTC)/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>- /// <param name="sourceDateTimeKind">The source datetimekind</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>+ /// <param name="sourceDateTimeKind">The source datetime kind</param>/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>public virtual DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind){@@ -111,10 +111,7 @@ namespace Grand.Business.Common.Services.Directory//could not convertreturn dt;}- if (dt.Kind == DateTimeKind.Utc)- return dt;-- return TimeZoneInfo.ConvertTimeToUtc(dt, sourceTimeZone);+ return dt.Kind == DateTimeKind.Utc ? dt : TimeZoneInfo.ConvertTimeToUtc(dt, sourceTimeZone);}/// <summary>@@ -122,25 +119,19 @@ namespace Grand.Business.Common.Services.Directory/// </summary>public virtual TimeZoneInfo CurrentTimeZone {get {- if (_timeZoneInfo == null)+ if (_timeZoneInfo != null) return _timeZoneInfo;+ try+ {+ if (!string.IsNullOrEmpty(_dateTimeSettings.DefaultStoreTimeZoneId))+ _timeZoneInfo = FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);+ }+ catch (Exception exc){- try- {- if (!string.IsNullOrEmpty(_dateTimeSettings.DefaultStoreTimeZoneId))- _timeZoneInfo = FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);- }- catch (Exception exc)- {- Debug.Write(exc.ToString());- }+ Debug.Write(exc.ToString());+ }- if (_timeZoneInfo == null)- _timeZoneInfo = TimeZoneInfo.Local;+ return _timeZoneInfo ??= TimeZoneInfo.Local;- return _timeZoneInfo;- }- else- return _timeZoneInfo;}}}diff --git a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.csindex 7bf1147ff..9e343d5b8 100644--- a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs@@ -36,9 +36,8 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Active exchange rate provider</returns>public virtual IExchangeRateProvider LoadActiveExchangeRateProvider(){- var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName);- if (exchangeRateProvider == null)- exchangeRateProvider = LoadAllExchangeRateProviders().FirstOrDefault();+ var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName) ??+ LoadAllExchangeRateProviders().FirstOrDefault();return exchangeRateProvider;}diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.csindex 48925d1cd..13a49254e 100644--- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs@@ -44,7 +44,7 @@ namespace Grand.Business.Common.Services.Directoryvar result =customer.Groups.Contains(customerGroup.Id)&& (!onlyActiveCustomerGroups || customerGroup.Active)- && (customerGroup.SystemName == customerGroupSystemName)+ && customerGroup.SystemName == customerGroupSystemName&& (!isSystem.HasValue || customerGroup.IsSystem == isSystem);return result;@@ -71,13 +71,8 @@ namespace Grand.Business.Common.Services.Directoryif (string.IsNullOrWhiteSpace(customerGroupId))return Task.FromResult<CustomerGroup>(null);- string key = string.Format(CacheKey.CUSTOMERGROUPS_BY_KEY, customerGroupId);- return _cacheBase.GetAsync(key, () =>- {- return _customerGroupRepository.GetByIdAsync(customerGroupId);- });--+ var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_KEY, customerGroupId);+ return _cacheBase.GetAsync(key, () => _customerGroupRepository.GetByIdAsync(customerGroupId));}/// <summary>@@ -87,17 +82,20 @@ namespace Grand.Business.Common.Services.Directory/// <returns>Customer group</returns>public virtual async Task<CustomerGroup> GetCustomerGroupBySystemName(string systemName){- string key = string.Format(CacheKey.CUSTOMERGROUPS_BY_SYSTEMNAME_KEY, systemName);+ var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_SYSTEMNAME_KEY, systemName);return await _cacheBase.GetAsync(key, async () =>{- return await Task.FromResult(_customerGroupRepository.Table.Where(x => x.SystemName == systemName).FirstOrDefault());+ return await Task.FromResult(_customerGroupRepository.Table.FirstOrDefault(x => x.SystemName == systemName));});}/// <summary>/// Gets all customer groups/// </summary>+ /// <param name="pageSize"></param>/// <param name="showHidden">A value indicating whether to show hidden records</param>+ /// <param name="name"></param>+ /// <param name="pageIndex"></param>/// <returns>Customer groups</returns>public virtual async Task<IPagedList<CustomerGroup>> GetAllCustomerGroups(string name = "", int pageIndex = 0,int pageSize = int.MaxValue, bool showHidden = false)diff --git a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.csindex c118c64a4..5f420ebc7 100644--- a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// History service interface/// </summary>- public partial class HistoryService : IHistoryService+ public class HistoryService : IHistoryService{private readonly IRepository<HistoryObject> _historyRepository;@@ -21,7 +21,7 @@ namespace Grand.Business.Common.Services.Directory{if (entity == null)throw new ArgumentNullException(nameof(entity));- var history = new HistoryObject()+ var history = new HistoryObject{CreatedOnUtc = DateTime.UtcNow,Object = entitydiff --git a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.csindex 8a6146632..07be52bac 100644--- a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs@@ -9,19 +9,19 @@ namespace Grand.Business.Common.Services.Directory/// <summary>/// User field service/// </summary>- public partial class UserFieldService : IUserFieldService+ public class UserFieldService : IUserFieldService{#region Fields- private readonly IRepository<UserFieldBaseEntity> _userfieldBaseEntitRepository;+ private readonly IRepository<UserFieldBaseEntity> _userFieldBaseEntityRepository;#endregion#region Ctorpublic UserFieldService(- IRepository<UserFieldBaseEntity> userfieldBaseEntitRepository)+ IRepository<UserFieldBaseEntity> userFieldBaseEntityRepository){- _userfieldBaseEntitRepository = userfieldBaseEntitRepository;+ _userFieldBaseEntityRepository = userFieldBaseEntityRepository;}#endregion@@ -46,11 +46,11 @@ namespace Grand.Business.Common.Services.Directoryvar collectionName = entity.GetType().Name;- _ = _userfieldBaseEntitRepository.SetCollection(collectionName);+ _ = _userFieldBaseEntityRepository.SetCollection(collectionName);- var basefields = await _userfieldBaseEntitRepository.GetByIdAsync(entity.Id);+ var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);- var props = basefields.UserFields.Where(x => string.IsNullOrEmpty(storeId) || x.StoreId == storeId);+ var props = baseFields.UserFields.Where(x => string.IsNullOrEmpty(storeId) || x.StoreId == storeId);var prop = props.FirstOrDefault(ga =>ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); //should be culture invariant@@ -62,7 +62,7 @@ namespace Grand.Business.Common.Services.Directoryif (string.IsNullOrWhiteSpace(valueStr)){//delete- await _userfieldBaseEntitRepository.PullFilter(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId);+ await _userFieldBaseEntityRepository.PullFilter(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId);var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);if (entityProp != null)@@ -72,7 +72,7 @@ namespace Grand.Business.Common.Services.Directory{//updateprop.Value = valueStr;- await _userfieldBaseEntitRepository.UpdateToSet(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId, prop);+ await _userFieldBaseEntityRepository.UpdateToSet(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId, prop);var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);if (entityProp != null)@@ -87,9 +87,9 @@ namespace Grand.Business.Common.Services.Directoryprop = new UserField {Key = key,Value = valueStr,- StoreId = storeId,+ StoreId = storeId};- await _userfieldBaseEntitRepository.AddToSet(entity.Id, x => x.UserFields, prop);+ await _userFieldBaseEntityRepository.AddToSet(entity.Id, x => x.UserFields, prop);entity.UserFields.Add(prop);}@@ -102,24 +102,21 @@ namespace Grand.Business.Common.Services.Directorythrow new ArgumentNullException(nameof(entity));var collectionName = entity.GetType().Name;- _ = _userfieldBaseEntitRepository.SetCollection(collectionName);+ _ = _userFieldBaseEntityRepository.SetCollection(collectionName);- var basefields = await _userfieldBaseEntitRepository.GetByIdAsync(entity.Id);- if (basefields == null)- return default(TPropType);-- var props = basefields.UserFields;+ var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);+ var props = baseFields?.UserFields;if (props == null)- return default(TPropType);+ return default;props = props.Where(x => x.StoreId == storeId).ToList();if (!props.Any())- return default(TPropType);+ return default;var prop = props.FirstOrDefault(ga =>ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase));if (prop == null || string.IsNullOrEmpty(prop.Value))- return default(TPropType);+ return default;return CommonHelper.To<TPropType>(prop.Value);}diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.csindex d127defb2..ba84c82f6 100644--- a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs@@ -21,7 +21,7 @@ namespace Grand.Business.Common.Services.ExportImport}}- protected async Task Import(CountryStates countryStatesDto)+ private async Task Import(CountryStates countryStatesDto){var country = await _countryService.GetCountryByTwoLetterIsoCode(countryStatesDto.Country);if (country == null)@@ -42,7 +42,7 @@ namespace Grand.Business.Common.Services.ExportImportName = countryStatesDto.StateProvinceName,Abbreviation = countryStatesDto.Abbreviation,Published = countryStatesDto.Published,- DisplayOrder = countryStatesDto.DisplayOrder,+ DisplayOrder = countryStatesDto.DisplayOrder};await _countryService.InsertStateProvince(state, country.Id);}diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.csindex d8947b897..14dcb44a1 100644--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs@@ -14,8 +14,6 @@ namespace Grand.Business.Common.Services.ExportImportIWorkbook xlPackage = new XSSFWorkbook();ISheet worksheet = xlPackage.CreateSheet(typeof(T).Name);- var manager = new PropertyManager<T>(properties);-WriteCaption(worksheet, properties);var row = 1;@@ -29,18 +27,15 @@ namespace Grand.Business.Common.Services.ExportImport}}- private MemoryStream stream;- private IWorkbook xlPackage;+ private MemoryStream _stream;+ private IWorkbook _xlPackage;public virtual IExportProvider BuilderExportToByte<T>(PropertyByName<T>[] properties, IEnumerable<T> itemsToExport){- if (stream == null)- stream = new MemoryStream();+ _stream ??= new MemoryStream();- if (xlPackage == null)- xlPackage = new XSSFWorkbook();+ _xlPackage ??= new XSSFWorkbook();- ISheet worksheet = xlPackage.CreateSheet(typeof(T).Name);- var manager = new PropertyManager<T>(properties);+ ISheet worksheet = _xlPackage.CreateSheet(typeof(T).Name);WriteCaption(worksheet, properties);var row = 1;foreach (var items in itemsToExport)@@ -52,14 +47,15 @@ namespace Grand.Business.Common.Services.ExportImport}public virtual byte[] BuilderExportToByte(){- xlPackage.Write(stream, false);- return stream.ToArray();+ _xlPackage.Write(_stream, false);+ return _stream.ToArray();}/// <summary>/// Write caption (first row) to XLSX worksheet/// </summary>- /// <param name="ISheet">sheet</param>+ /// <param name="sheet"></param>+ /// <param name="properties"></param>private void WriteCaption<T>(ISheet sheet, PropertyByName<T>[] properties){IRow row = sheet.CreateRow(0);@@ -72,19 +68,21 @@ namespace Grand.Business.Common.Services.ExportImport/// <summary>/// Write object data to XLSX worksheet/// </summary>- /// <param name="worksheet">worksheet</param>- /// <param name="row">Row index</param>- private void WriteToXlsx<T>(PropertyByName<T>[] properties, ISheet sheet, T items, int row)+ /// <param name="items"></param>+ /// <param name="id">Row index</param>+ /// <param name="properties"></param>+ /// <param name="sheet"></param>+ private void WriteToXlsx<T>(PropertyByName<T>[] properties, ISheet sheet, T items, int id){- IRow _row = sheet.CreateRow(row);+ IRow row = sheet.CreateRow(id);foreach (var prop in properties){- var cellValue = (prop.GetProperty(items)?.ToString());- if (cellValue != null && cellValue.Length >= 32767) // 32767 is the max char size of an excel cell+ var cellValue = prop.GetProperty(items)?.ToString();+ if (cellValue is { Length: >= 32767 }) // 32767 is the max char size of an excel cell{- cellValue = cellValue.Substring(0, 32767); //Truncate the content to max size.+ cellValue = cellValue[..32767]; //Truncate the content to max size.}- _row.CreateCell(prop.PropertyOrderPosition).SetCellValue(cellValue);+ row.CreateCell(prop.PropertyOrderPosition).SetCellValue(cellValue);}}}diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.csindex a889fc712..aa892b299 100644--- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs+++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Common.Services.Localization/// <summary>/// Language service/// </summary>- public partial class LanguageService : ILanguageService+ public class LanguageService : ILanguageService{#region Fields@@ -51,7 +51,7 @@ namespace Grand.Business.Common.Services.Localization/// <returns>Languages</returns>public virtual async Task<IList<Language>> GetAllLanguages(bool showHidden = false, string storeId = ""){- string key = string.Format(CacheKey.LANGUAGES_ALL_KEY, showHidden);+ var key = string.Format(CacheKey.LANGUAGES_ALL_KEY, showHidden);var languages = await _cacheBase.GetAsync(key, async () =>{var query = from p in _languageRepository.Table@@ -80,7 +80,7 @@ namespace Grand.Business.Common.Services.Localization/// <returns>Language</returns>public virtual Task<Language> GetLanguageById(string languageId){- string key = string.Format(CacheKey.LANGUAGES_BY_ID_KEY, languageId);+ var key = string.Format(CacheKey.LANGUAGES_BY_ID_KEY, languageId);return _cacheBase.GetAsync(key, () => _languageRepository.GetByIdAsync(languageId));}diff --git a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.csindex efa915723..f0f81127f 100644--- a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs+++ b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs@@ -13,11 +13,11 @@ namespace Grand.Business.Common.Services.Localization/// <summary>/// Provides information about translations/// </summary>- public partial class TranslationService : ITranslationService+ public class TranslationService : ITranslationService{#region Constants- private Dictionary<string, string> _allTranslateResource = null;+ private Dictionary<string, string> _allTranslateResource;#endregion@@ -68,7 +68,7 @@ namespace Grand.Business.Common.Services.Localization/// <summary>/// Gets a translate resource/// </summary>- /// <param name="Name">A string representing a name</param>+ /// <param name="name">A string representing a name</param>/// <param name="languageId">Language identifier</param>/// <returns>Translate resource</returns>public virtual async Task<TranslationResource> GetTranslateResourceByName(string name, string languageId)@@ -155,10 +155,7 @@ namespace Grand.Business.Common.Services.Localization/// <returns>A string representing the requested resource string.</returns>public virtual string GetResource(string name){- if (_workContext.WorkingLanguage != null)- return GetResource(name, _workContext.WorkingLanguage.Id);-- return "";+ return _workContext.WorkingLanguage != null ? GetResource(name, _workContext.WorkingLanguage.Id) : "";}/// <summary>@@ -171,8 +168,8 @@ namespace Grand.Business.Common.Services.Localization/// <returns>A string representing the requested resource string.</returns>public virtual string GetResource(string name, string languageId, string defaultValue = "", bool returnEmptyIfNotFound = false){- var result = string.Empty;- if (name == null) name = string.Empty;+ string result;+ name ??= string.Empty;name = name.Trim().ToLowerInvariant();if (_allTranslateResource != null)@@ -194,11 +191,9 @@ namespace Grand.Business.Common.Services.Localization_allTranslateResource.TryGetValue(name, out result);}- if (string.IsNullOrEmpty(result))- {- if (!string.IsNullOrEmpty(defaultValue)) result = defaultValue;- else if (!returnEmptyIfNotFound) result = name;- }+ if (!string.IsNullOrEmpty(result)) return result;+ if (!string.IsNullOrEmpty(defaultValue)) result = defaultValue;+ else if (!returnEmptyIfNotFound) result = name;return result;}@@ -218,8 +213,8 @@ namespace Grand.Business.Common.Services.LocalizationAsync = true};- using var stringWriter = new StringWriter(sb);- using var xmlWriter = XmlWriter.Create(stringWriter, xwSettings);+ await using var stringWriter = new StringWriter(sb);+ await using var xmlWriter = XmlWriter.Create(stringWriter, xwSettings);await xmlWriter.WriteStartDocumentAsync();xmlWriter.WriteStartElement("Language");xmlWriter.WriteAttributeString("Name", language.Name);@@ -231,11 +226,11 @@ namespace Grand.Business.Common.Services.LocalizationxmlWriter.WriteAttributeString("Name", resource.Name);xmlWriter.WriteAttributeString("Area", resource.Area.ToString());xmlWriter.WriteElementString("Value", null, resource.Value);- xmlWriter.WriteEndElement();+ await xmlWriter.WriteEndElementAsync();}- xmlWriter.WriteEndElement();- xmlWriter.WriteEndDocument();+ await xmlWriter.WriteEndElementAsync();+ await xmlWriter.WriteEndDocumentAsync();await xmlWriter.FlushAsync();return stringWriter.ToString();}@@ -259,43 +254,45 @@ namespace Grand.Business.Common.Services.LocalizationxmlDoc.LoadXml(xml);var nodes = xmlDoc.SelectNodes(@"//Language/Resource");- foreach (XmlNode node in nodes)- {- string name = node.Attributes["Name"].InnerText.Trim();- string area = node.Attributes["Area"]?.InnerText.Trim();- string value = "";- var valueNode = node.SelectSingleNode("Value");- if (valueNode != null)- value = valueNode.InnerText;-- if (String.IsNullOrEmpty(name))- continue;-- //bulk insert- var resource = (from l in _translationRepository.Table- where l.Name == name.ToLowerInvariant() && l.LanguageId == language.Id- select l).FirstOrDefault();-- if (resource != null)+ if (nodes != null)+ foreach (XmlNode node in nodes){- resource.Name = resource.Name.ToLowerInvariant();- resource.Value = value;- if (Enum.TryParse<TranslationResourceArea>(area, out var areaEnum))- resource.Area = areaEnum;- await _translationRepository.UpdateAsync(resource);+ var name = node.Attributes?["Name"]?.InnerText.Trim();+ var area = node.Attributes?["Area"]?.InnerText.Trim();+ var value = "";+ var valueNode = node.SelectSingleNode("Value");+ if (valueNode != null)+ value = valueNode.InnerText;++ if (string.IsNullOrEmpty(name))+ continue;++ //bulk insert+ var resource = (from l in _translationRepository.Table+ where l.Name == name.ToLowerInvariant() && l.LanguageId == language.Id+ select l).FirstOrDefault();++ if (resource != null)+ {+ resource.Name = resource.Name.ToLowerInvariant();+ resource.Value = value;+ if (Enum.TryParse<TranslationResourceArea>(area, out var areaEnum))+ resource.Area = areaEnum;+ await _translationRepository.UpdateAsync(resource);+ }+ else+ {+ _ = Enum.TryParse(area, out TranslationResourceArea areaEnum);++ translateResources.Add(new TranslationResource {+ LanguageId = language.Id,+ Name = name.ToLowerInvariant(),+ Value = value,+ Area = areaEnum+ });+ }}- else- {- Enum.TryParse<TranslationResourceArea>(area, out TranslationResourceArea areaEnum);-- translateResources.Add(new TranslationResource {- LanguageId = language.Id,- Name = name.ToLowerInvariant(),- Value = value,- Area = areaEnum- });- }- }+if (translateResources.Any())await _translationRepository.InsertManyAsync(translateResources);@@ -313,7 +310,7 @@ namespace Grand.Business.Common.Services.Localizationif (language == null)throw new ArgumentNullException(nameof(language));- if (String.IsNullOrEmpty(xml))+ if (string.IsNullOrEmpty(xml))return;var xmlDoc = new XmlDocument();@@ -322,28 +319,29 @@ namespace Grand.Business.Common.Services.Localizationvar translateResources = new List<TranslationResource>();var nodes = xmlDoc.SelectNodes(@"//Language/Resource");- foreach (XmlNode node in nodes)- {- string name = node.Attributes["Name"].InnerText.Trim();- string area = node.Attributes["Area"]?.InnerText.Trim();- string value = "";- var valueNode = node.SelectSingleNode("Value");- if (valueNode != null)- value = valueNode.InnerText;-- if (string.IsNullOrEmpty(name))- continue;-- Enum.TryParse<TranslationResourceArea>(area, out TranslationResourceArea areaEnum);-- translateResources.Add(- new TranslationResource {- LanguageId = language.Id,- Name = name.ToLowerInvariant(),- Value = value,- Area = areaEnum- });- }+ if (nodes != null)+ foreach (XmlNode node in nodes)+ {+ var name = node.Attributes?["Name"]?.InnerText.Trim();+ var area = node.Attributes?["Area"]?.InnerText.Trim();+ var value = "";+ var valueNode = node.SelectSingleNode("Value");+ if (valueNode != null)+ value = valueNode.InnerText;++ if (string.IsNullOrEmpty(name))+ continue;++ _ = Enum.TryParse(area, out TranslationResourceArea areaEnum);++ translateResources.Add(+ new TranslationResource {+ LanguageId = language.Id,+ Name = name.ToLowerInvariant(),+ Value = value,+ Area = areaEnum+ });+ }await _translationRepository.InsertManyAsync(translateResources);diff --git a/src/Business/Grand.Business.Common/Services/Logging/CustomerActivityService.cs b/src/Business/Grand.Business.Common/Services/Logging/CustomerActivityService.csindex 59663d9c4..91bb1ea45 100644--- a/src/Business/Grand.Business.Common/Services/Logging/CustomerActivityService.cs+++ b/src/Business/Grand.Business.Common/Services/Logging/CustomerActivityService.cs@@ -49,10 +49,7 @@ namespace Grand.Business.Common.Services.Loggingprotected virtual async Task<IList<ActivityLogType>> GetAllActivityTypesCached(){//cache- return await _cacheBase.GetAsync(CacheKey.ACTIVITYTYPE_ALL_KEY, async () =>- {- return await GetAllActivityTypes();- });+ return await _cacheBase.GetAsync(CacheKey.ACTIVITYTYPE_ALL_KEY, async () => await GetAllActivityTypes());}/// <summary>@@ -155,7 +152,7 @@ namespace Grand.Business.Common.Services.Loggingvar activityTypes = GetAllActivityTypesCachedSync();var activityType = activityTypes.FirstOrDefault(at => at.SystemKeyword == systemKeyword);- if (activityType == null || !activityType.Enabled)+ if (activityType is not { Enabled: true })return null;comment = CommonHelper.EnsureNotNull(comment);@@ -195,6 +192,7 @@ namespace Grand.Business.Common.Services.Logging/// <param name="createdOnTo">Log item creation to; null to load all customers</param>/// <param name="customerId">Customer identifier; null to load all customers</param>/// <param name="activityLogTypeId">Activity log type identifier</param>+ /// <param name="ipAddress"></param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Activity log items</returns>@@ -207,17 +205,17 @@ namespace Grand.Business.Common.Services.Loggingvar query = from p in _activityLogRepository.Tableselect p;- if (!String.IsNullOrEmpty(comment))+ if (!string.IsNullOrEmpty(comment))query = query.Where(al => al.Comment != null && al.Comment.ToLower().Contains(comment.ToLower()));if (createdOnFrom.HasValue)query = query.Where(al => createdOnFrom.Value <= al.CreatedOnUtc);if (createdOnTo.HasValue)query = query.Where(al => createdOnTo.Value >= al.CreatedOnUtc);- if (!String.IsNullOrEmpty(activityLogTypeId))+ if (!string.IsNullOrEmpty(activityLogTypeId))query = query.Where(al => activityLogTypeId == al.ActivityLogTypeId);- if (!String.IsNullOrEmpty(customerId))+ if (!string.IsNullOrEmpty(customerId))query = query.Where(al => customerId == al.CustomerId);- if (!String.IsNullOrEmpty(ipAddress))+ if (!string.IsNullOrEmpty(ipAddress))query = query.Where(al => ipAddress == al.IpAddress);query = query.OrderByDescending(al => al.CreatedOnUtc);@@ -244,7 +242,7 @@ namespace Grand.Business.Common.Services.Loggingquery = query.Where(al => createdOnFrom.Value <= al.CreatedOnUtc);if (createdOnTo.HasValue)query = query.Where(al => createdOnTo.Value >= al.CreatedOnUtc);- if (!String.IsNullOrEmpty(activityLogTypeId))+ if (!string.IsNullOrEmpty(activityLogTypeId))query = query.Where(al => activityLogTypeId == al.ActivityLogTypeId);var gquery = query.GroupBy(key => new { key.ActivityLogTypeId, key.EntityKeyId })@@ -289,7 +287,7 @@ namespace Grand.Business.Common.Services.Logging}/// <summary>- /// Gets knowledgebase category activity log items+ /// Gets knowledge base category activity log items/// </summary>/// <param name="createdOnFrom">Log item creation from; null to load all records</param>/// <param name="createdOnTo">Log item creation to; null to load all records</param>@@ -319,7 +317,7 @@ namespace Grand.Business.Common.Services.Logging}/// <summary>- /// Gets knowledgebase article activity log items+ /// Gets knowledge base article activity log items/// </summary>/// <param name="createdOnFrom">Log item creation from; null to load all records</param>/// <param name="createdOnTo">Log item creation to; null to load all records</param>@@ -382,7 +380,7 @@ namespace Grand.Business.Common.Services.Logging/// </summary>/// <param name="createdOnFrom">Log item creation from; null to load all records</param>/// <param name="createdOnTo">Log item creation to; null to load all records</param>- /// <param name="categoryId">Collection identifier</param>+ /// <param name="collectionId">Collection identifier</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Activity log items</returns>diff --git a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs b/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.csindex bb55f9c6a..647838bce 100644--- a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs+++ b/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Common.Services.Logging/// <summary>/// Default logger/// </summary>- public partial class DefaultLogger : ILogger+ public class DefaultLogger : ILogger{#region Fields@@ -93,14 +93,7 @@ namespace Grand.Business.Common.Services.Loggingselect l;var logItems = await Task.FromResult(query.ToList());- var sortedLogItems = new List<Log>();- foreach (string id in logIds)- {- var log = logItems.Find(x => x.Id == id);- if (log != null)- sortedLogItems.Add(log);- }- return sortedLogItems;+ return logIds.Select(id => logItems.Find(x => x.Id == id)).Where(log => log != null).ToList();}/// <summary>@@ -111,11 +104,11 @@ namespace Grand.Business.Common.Services.Logging/// <param name="fullMessage">The full message</param>/// <param name="customer">The customer to associate log record with</param>/// <param name="ipAddress">Ip address</param>- /// <param name="pageurl">Page url</param>+ /// <param name="pageUrl">Page url</param>/// <param name="referrerUrl">Referrer url</param>/// <returns>A log item</returns>public virtual Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null,- string ipAddress = default, string pageurl = default, string referrerUrl = default)+ string ipAddress = default, string pageUrl = default, string referrerUrl = default){var log = new Log {LogLevelId = logLevel,@@ -123,7 +116,7 @@ namespace Grand.Business.Common.Services.LoggingFullMessage = fullMessage,IpAddress = ipAddress,CustomerId = customer != null ? customer.Id : "",- PageUrl = pageurl,+ PageUrl = pageUrl,ReferrerUrl = referrerUrl,CreatedOnUtc = DateTime.UtcNow};diff --git a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.csindex ee05745dd..13f047ac5 100644--- a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs+++ b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs@@ -14,8 +14,8 @@ namespace Grand.Business.Common.Services.Pdf/// </summary>public class HtmlToPdfService : IPdfService{- private const string _orderTemaplate = "~/Views/PdfTemplates/OrderPdfTemplate.cshtml";- private const string _shipmentsTemaplate = "~/Views/PdfTemplates/ShipmentPdfTemplate.cshtml";+ private const string OrderTemplate = "~/Views/PdfTemplates/OrderPdfTemplate.cshtml";+ private const string ShipmentsTemplate = "~/Views/PdfTemplates/ShipmentPdfTemplate.cshtml";private readonly IViewRenderService _viewRenderService;private readonly ILanguageService _languageService;@@ -31,7 +31,7 @@ namespace Grand.Business.Common.Services.Pdf_storeFilesContext = storeFilesContext;}- protected PdfGenerateConfig PdfConfig()+ private PdfGenerateConfig PdfConfig(){var config = new PdfGenerateConfig {PageSize = PdfSharpCore.PageSize.A4@@ -49,7 +49,7 @@ namespace Grand.Business.Common.Services.Pdfif (orders == null)throw new ArgumentNullException(nameof(orders));- var html = await _viewRenderService.RenderToStringAsync<(IList<Order>, string)>(_orderTemaplate, new(orders, vendorId));+ var html = await _viewRenderService.RenderToStringAsync<(IList<Order>, string)>(OrderTemplate, new(orders, vendorId));var pdf = PdfGenerator.GeneratePdf(html, PdfConfig());pdf.Save(stream);}@@ -59,23 +59,23 @@ namespace Grand.Business.Common.Services.Pdfif (order == null)throw new ArgumentNullException(nameof(order));- var fileName = string.Format("order_{0}_{1}.pdf", order.OrderGuid, CommonHelper.GenerateRandomDigitCode(4));+ var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf";var dir = CommonPath.WebMapPath("assets/files/exportimport");+ if (dir == null)+ throw new ArgumentNullException(nameof(dir));+if (!System.IO.Directory.Exists(dir)){System.IO.Directory.CreateDirectory(dir);}-var filePath = Path.Combine(dir, fileName);- using (var fileStream = new FileStream(filePath, FileMode.Create))+ await using var fileStream = new FileStream(filePath, FileMode.Create);+ var orders = new List<Order>{- var orders = new List<Order>- {- order- };- await PrintOrdersToPdf(fileStream, orders, languageId, vendorId);- }+ order+ };+ await PrintOrdersToPdf(fileStream, orders, languageId, vendorId);return filePath;}@@ -89,9 +89,9 @@ namespace Grand.Business.Common.Services.Pdfvar lang = await _languageService.GetLanguageById(languageId);if (lang == null)- throw new ArgumentException(string.Format("Cannot load language. ID={0}", languageId));+ throw new ArgumentException($"Cannot load language. ID={languageId}");- var html = await _viewRenderService.RenderToStringAsync<IList<Shipment>>(_shipmentsTemaplate, shipments);+ var html = await _viewRenderService.RenderToStringAsync<IList<Shipment>>(ShipmentsTemplate, shipments);var pdf = PdfGenerator.GeneratePdf(html, PdfConfig());pdf.Save(stream);}@@ -101,29 +101,24 @@ namespace Grand.Business.Common.Services.Pdfif (order == null)throw new ArgumentNullException(nameof(order));- string fileName = string.Format("order_{0}_{1}", order.OrderGuid, CommonHelper.GenerateRandomDigitCode(4));- string downloadId = string.Empty;- using (MemoryStream ms = new MemoryStream())+ var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}";+ using MemoryStream ms = new MemoryStream();+ var orders = new List<Order>{- var orders = new List<Order>- {- order- };- await PrintOrdersToPdf(ms, orders, languageId, vendorId);- var download = new Download {- Filename = fileName,- Extension = ".pdf",- ContentType = "application/pdf",- };-- download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, ms.ToArray());- await _downloadRepository.InsertAsync(download);-- //TODO- //await _mediator.EntityInserted(download);- downloadId = download.Id;- }- return downloadId;+ order+ };+ await PrintOrdersToPdf(ms, orders, languageId, vendorId);+ var download = new Download {+ Filename = fileName,+ Extension = ".pdf",+ ContentType = "application/pdf",+ };++ download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, ms.ToArray());+ await _downloadRepository.InsertAsync(download);++ //await _mediator.EntityInserted(download);+ return download.Id;}}diff --git a/src/Business/Grand.Business.Common/Services/Security/AclService.cs b/src/Business/Grand.Business.Common/Services/Security/AclService.csindex ca7a4b40b..9a9968133 100644--- a/src/Business/Grand.Business.Common/Services/Security/AclService.cs+++ b/src/Business/Grand.Business.Common/Services/Security/AclService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Common.Services.Security/// <summary>/// ACL service/// </summary>- public partial class AclService : IAclService+ public class AclService : IAclService{#region Ctor@@ -31,7 +31,7 @@ namespace Grand.Business.Common.Services.Security/// Authorize ACL permission/// </summary>/// <typeparam name="T">Type</typeparam>- /// <param name="entity">Wntity</param>+ /// <param name="entity">Entity</param>/// <param name="customer">Customer</param>/// <returns>true - authorized; otherwise, false</returns>public virtual bool Authorize<T>(T entity, Customer customer) where T : BaseEntity, IGroupLinkEntity@@ -45,17 +45,7 @@ namespace Grand.Business.Common.Services.Securityif (!entity.LimitedToGroups)return true;- if (CommonHelper.IgnoreAcl)- return true;-- foreach (var role1 in customer.Groups)- foreach (var role2Id in entity.CustomerGroups)- if (role1 == role2Id)- //yes, we have such permission- return true;-- //no permission found- return false;+ return CommonHelper.IgnoreAcl || customer.Groups.Any(role1 => entity.CustomerGroups.Any(role2Id => role1 == role2Id));}/// <summary>@@ -77,16 +67,7 @@ namespace Grand.Business.Common.Services.Securityif (CommonHelper.IgnoreStoreLimitations)return true;- if (!entity.LimitedToStores)- return true;-- foreach (var storeIdWithAccess in entity.Stores)- if (storeId == storeIdWithAccess)- //yes, we have such permission- return true;-- //no permission found- return false;+ return !entity.LimitedToStores || entity.Stores.Any(storeIdWithAccess => storeId == storeIdWithAccess);}#endregiondiff --git a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.csindex c52294c85..186ca5f3f 100644--- a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs+++ b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs@@ -6,11 +6,6 @@ namespace Grand.Business.Common.Services.Security{public class EncryptionService : IEncryptionService{- public EncryptionService()- {-- }-/// <summary>/// Create salt key/// </summary>@@ -31,19 +26,20 @@ namespace Grand.Business.Common.Services.Security/// <summary>/// Create a password hash/// </summary>- /// <param name="password">{assword</param>- /// <param name="saltkey">Salk key</param>+ /// <param name="password">password</param>+ /// <param name="saltKey">Salk key</param>+ /// <param name="passwordFormat"></param>/// <returns>Password hash</returns>- public virtual string CreatePasswordHash(string password, string saltkey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1)+ public virtual string CreatePasswordHash(string password, string saltKey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1){- var saltAndPassword = string.Concat(password, saltkey);+ var saltAndPassword = string.Concat(password, saltKey);HashAlgorithm algorithm = passwordFormat switch{HashedPasswordFormat.SHA1 => SHA1.Create(),HashedPasswordFormat.SHA256 => SHA256.Create(),HashedPasswordFormat.SHA384 => SHA384.Create(),HashedPasswordFormat.SHA512 => SHA512.Create(),- _ => throw new NotSupportedException("Not supported format"),+ _ => throw new NotSupportedException("Not supported format")};if (algorithm == null)throw new ArgumentException("Unrecognized hash name");@@ -66,12 +62,12 @@ namespace Grand.Business.Common.Services.Securityif (string.IsNullOrEmpty(privateKey) || privateKey.Length != 24)throw new Exception("Wrong private key");- var tDES = TripleDES.Create();+ var tDes = TripleDES.Create();- tDES.Key = new ASCIIEncoding().GetBytes(privateKey);- tDES.IV = new ASCIIEncoding().GetBytes(privateKey[^8..]);+ tDes.Key = new ASCIIEncoding().GetBytes(privateKey);+ tDes.IV = new ASCIIEncoding().GetBytes(privateKey[^8..]);- byte[] encryptedBinary = EncryptTextToMemory(plainText, tDES.Key, tDES.IV);+ var encryptedBinary = EncryptTextToMemory(plainText, tDes.Key, tDes.IV);return Convert.ToBase64String(encryptedBinary);}@@ -87,43 +83,37 @@ namespace Grand.Business.Common.Services.Securityreturn cipherText;if (string.IsNullOrEmpty(encryptionPrivateKey) || encryptionPrivateKey.Length != 24)- throw new Exception("Wrong encryp private key");+ throw new Exception("Wrong encrypt private key");- var tDES = TripleDES.Create();- tDES.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey);- tDES.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey[^8..]);+ var tDes = TripleDES.Create();+ tDes.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey);+ tDes.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey[^8..]);- byte[] buffer = Convert.FromBase64String(cipherText);- return DecryptTextFromMemory(buffer, tDES.Key, tDES.IV);+ var buffer = Convert.FromBase64String(cipherText);+ return DecryptTextFromMemory(buffer, tDes.Key, tDes.IV);}#region Utilitiesprivate byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv){- using (var ms = new MemoryStream())+ using var ms = new MemoryStream();+ using (var cs = new CryptoStream(ms, TripleDES.Create().CreateEncryptor(key, iv), CryptoStreamMode.Write)){- using (var cs = new CryptoStream(ms, TripleDES.Create().CreateEncryptor(key, iv), CryptoStreamMode.Write))- {- byte[] toEncrypt = new UnicodeEncoding().GetBytes(data);- cs.Write(toEncrypt, 0, toEncrypt.Length);- cs.FlushFinalBlock();- }-- return ms.ToArray();+ var toEncrypt = new UnicodeEncoding().GetBytes(data);+ cs.Write(toEncrypt, 0, toEncrypt.Length);+ cs.FlushFinalBlock();}++ return ms.ToArray();}private string DecryptTextFromMemory(byte[] data, byte[] key, byte[] iv){- using (var ms = new MemoryStream(data))- {- using (var cs = new CryptoStream(ms, TripleDES.Create().CreateDecryptor(key, iv), CryptoStreamMode.Read))- {- var sr = new StreamReader(cs, new UnicodeEncoding());- return sr.ReadLine();- }- }+ using var ms = new MemoryStream(data);+ using var cs = new CryptoStream(ms, TripleDES.Create().CreateDecryptor(key, iv), CryptoStreamMode.Read);+ var sr = new StreamReader(cs, new UnicodeEncoding());+ return sr.ReadLine();}#endregiondiff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.csindex 46db27918..7479d1313 100644--- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Common.Services.Security/// <summary>/// Permission service/// </summary>- public partial class PermissionService : IPermissionService+ public class PermissionService : IPermissionService{#region Fields@@ -63,10 +63,10 @@ namespace Grand.Business.Common.Services.Securityif (string.IsNullOrEmpty(permissionSystemName))return false;- string key = string.Format(CacheKey.PERMISSIONS_ALLOWED_KEY, customerGroup.Id, permissionSystemName);+ var key = string.Format(CacheKey.PERMISSIONS_ALLOWED_KEY, customerGroup.Id, permissionSystemName);return await _cacheBase.GetAsync(key, async () =>{- var permissionRecord = await Task.FromResult(_permissionRepository.Table.Where(x => x.SystemName == permissionSystemName).FirstOrDefault());+ var permissionRecord = await Task.FromResult(_permissionRepository.Table.FirstOrDefault(x => x.SystemName == permissionSystemName));return permissionRecord?.CustomerGroups.Contains(customerGroup.Id) ?? false;});}@@ -106,7 +106,7 @@ namespace Grand.Business.Common.Services.Security/// <returns>Permission</returns>public virtual async Task<Permission> GetPermissionBySystemName(string systemName){- if (String.IsNullOrWhiteSpace(systemName))+ if (string.IsNullOrWhiteSpace(systemName))return await Task.FromResult<Permission>(null);var query = from pr in _permissionRepository.Table@@ -201,7 +201,7 @@ namespace Grand.Business.Common.Services.Security/// <returns>true - authorized; otherwise, false</returns>public virtual async Task<bool> Authorize(string permissionSystemName, Customer customer){- if (String.IsNullOrEmpty(permissionSystemName))+ if (string.IsNullOrEmpty(permissionSystemName))return false;var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());@@ -218,18 +218,18 @@ namespace Grand.Business.Common.Services.Security/// Gets a permission action/// </summary>/// <param name="systemName">Permission system name</param>- /// <param name="customeroleId">Customer group ident</param>+ /// <param name="customerGroupId">Customer group ident</param>/// <returns>Permission action</returns>- public virtual async Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customeroleId)+ public virtual async Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customerGroupId){return await Task.FromResult(_permissionActionRepository.Table- .Where(x => x.SystemName == systemName && x.CustomerGroupId == customeroleId).ToList());+ .Where(x => x.SystemName == systemName && x.CustomerGroupId == customerGroupId).ToList());}/// <summary>/// Inserts a permission action record/// </summary>- /// <param name="permission">Permission</param>+ /// <param name="permissionAction">Permission action</param>public virtual async Task InsertPermissionAction(PermissionAction permissionAction){if (permissionAction == null)@@ -244,7 +244,7 @@ namespace Grand.Business.Common.Services.Security/// <summary>/// Inserts a permission action record/// </summary>- /// <param name="permission">Permission</param>+ /// <param name="permissionAction">Permission action</param>public virtual async Task DeletePermissionAction(PermissionAction permissionAction){if (permissionAction == null)@@ -259,7 +259,7 @@ namespace Grand.Business.Common.Services.Security/// <summary>/// Authorize permission for action/// </summary>- /// <param name="permissionRecordSystemName">Permission system name</param>+ /// <param name="permissionSystemName">Permission system name</param>/// <param name="permissionActionName">Permission action name</param>/// <returns>true - authorized; otherwise, false</returns>public virtual async Task<bool> AuthorizeAction(string permissionSystemName, string permissionActionName)@@ -279,8 +279,8 @@ namespace Grand.Business.Common.Services.Securityvar key = string.Format(CacheKey.PERMISSIONS_ALLOWED_ACTION_KEY, group.Id, permissionSystemName, permissionActionName);var permissionAction = await _cacheBase.GetAsync(key, async () =>{- return await Task.FromResult(_permissionActionRepository.Table.Where(x => x.SystemName == permissionSystemName && x.CustomerGroupId == group.Id && x.Action == permissionActionName)- .FirstOrDefault());+ return await Task.FromResult(_permissionActionRepository.Table+ .FirstOrDefault(x => x.SystemName == permissionSystemName && x.CustomerGroupId == group.Id && x.Action == permissionActionName));});if (permissionAction != null)return false;diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.csindex e94d1249d..1739667f3 100644--- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs+++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Common.Services.Seo/// <summary>/// Provides information about Slug URL Entity/// </summary>- public partial class SlugService : ISlugService+ public class SlugService : ISlugService{#region Fields@@ -45,11 +45,8 @@ namespace Grand.Business.Common.Services.Seoprotected virtual async Task<IList<EntityUrl>> GetAllUrlEntityCached(){//cache- string key = string.Format(CacheKey.URLEntity_ALL_KEY);- return await _cacheBase.GetAsync(key, async () =>- {- return await Task.FromResult(_urlEntityRepository.Table.ToList());- });+ var key = string.Format(CacheKey.URLEntity_ALL_KEY);+ return await _cacheBase.GetAsync(key, async () => await Task.FromResult(_urlEntityRepository.Table.ToList()));}#region Methods@@ -57,7 +54,7 @@ namespace Grand.Business.Common.Services.Seo/// <summary>/// Gets an URL Entity/// </summary>- /// <param name="entityUrlId">URL Entity identifier</param>+ /// <param name="urlEntityId">URL Entity identifier</param>/// <returns>URL Entity</returns>public virtual Task<EntityUrl> GetEntityUrlById(string urlEntityId){@@ -116,7 +113,7 @@ namespace Grand.Business.Common.Services.Seo/// <returns>Found URL Entity</returns>public virtual async Task<EntityUrl> GetBySlug(string slug){- if (String.IsNullOrEmpty(slug))+ if (string.IsNullOrEmpty(slug))return null;slug = slug.ToLowerInvariant();@@ -135,7 +132,7 @@ namespace Grand.Business.Common.Services.Seo/// <returns>Found URL Entity</returns>public virtual async Task<EntityUrl> GetBySlugCached(string slug){- if (String.IsNullOrEmpty(slug))+ if (string.IsNullOrEmpty(slug))return null;slug = slug.ToLowerInvariant();@@ -151,13 +148,10 @@ namespace Grand.Business.Common.Services.Seoreturn entityUrlForCaching;}- string key = string.Format(CacheKey.URLEntity_BY_SLUG_KEY, slug);+ var key = string.Format(CacheKey.URLEntity_BY_SLUG_KEY, slug);return await _cacheBase.GetAsync(key, async () =>{var urlEntity = await GetBySlug(slug);- if (urlEntity == null)- return null;-return urlEntity;});}@@ -197,7 +191,7 @@ namespace Grand.Business.Common.Services.Seo{if (_config.LoadAllUrlEntitiesOnStartup){- string key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);+ var key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);return await _cacheBase.GetAsync(key, async () =>{var source = await GetAllUrlEntityCached();@@ -207,15 +201,13 @@ namespace Grand.Business.Common.Services.Seour.LanguageId == languageId &&ur.IsActiveselect ur.Slug;- var slug = query.FirstOrDefault();- if (slug == null)- slug = "";+ var slug = query.FirstOrDefault() ?? "";return slug;});}else{- string key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);+ var key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);return await _cacheBase.GetAsync(key, async () =>{@@ -226,9 +218,7 @@ namespace Grand.Business.Common.Services.Seour.LanguageId == languageId &&ur.IsActiveselect ur.Slug;- var slug = await Task.FromResult(query.FirstOrDefault());- if (slug == null)- slug = "";+ var slug = await Task.FromResult(query.FirstOrDefault()) ?? "";return slug;});}@@ -246,8 +236,8 @@ namespace Grand.Business.Common.Services.Seoif (entity == null)throw new ArgumentNullException(nameof(entity));- string entityId = entity.Id;- string entityName = typeof(T).Name;+ var entityId = entity.Id;+ var entityName = typeof(T).Name;var query = from ur in _urlEntityRepository.Tablewhere ur.EntityId == entityId &&@@ -281,7 +271,7 @@ namespace Grand.Business.Common.Services.SeoEntityName = entityName,Slug = slug,LanguageId = languageId,- IsActive = true,+ IsActive = true};await InsertEntityUrl(entityUrl);}@@ -317,7 +307,7 @@ namespace Grand.Business.Common.Services.SeoEntityName = entityName,Slug = slug,LanguageId = languageId,- IsActive = true,+ IsActive = true};await InsertEntityUrl(entityUrl);diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.csindex 5b66cfeca..a22774d5a 100644--- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs+++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Common.Services.Stores/// <summary>/// Store service/// </summary>- public partial class StoreService : IStoreService+ public class StoreService : IStoreService{#region Fields@@ -50,14 +50,10 @@ namespace Grand.Business.Common.Services.Stores/// <returns>Stores</returns>public virtual async Task<IList<Store>> GetAllStores(){- if (_allStores == null)+ return _allStores ??= await _cacheBase.GetAsync(CacheKey.STORES_ALL_KEY, async () =>{- _allStores = await _cacheBase.GetAsync(CacheKey.STORES_ALL_KEY, async () =>- {- return await Task.FromResult(_storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList());- });- }- return _allStores;+ return await Task.FromResult(_storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList());+ });}/// <summary>@@ -66,14 +62,10 @@ namespace Grand.Business.Common.Services.Stores/// <returns>Stores</returns>public virtual IList<Store> GetAll(){- if (_allStores == null)+ return _allStores ??= _cacheBase.Get(CacheKey.STORES_ALL_KEY, () =>{- _allStores = _cacheBase.Get(CacheKey.STORES_ALL_KEY, () =>- {- return _storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList();- });- }- return _allStores;+ return _storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList();+ });}/// <summary>@@ -83,7 +75,7 @@ namespace Grand.Business.Common.Services.Stores/// <returns>Store</returns>public virtual Task<Store> GetStoreById(string storeId){- string key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId);+ var key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId);return _cacheBase.GetAsync(key, () => _storeRepository.GetByIdAsync(storeId));}diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.csindex 888c0cdc8..91f2077dd 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs@@ -1,7 +1,7 @@using Grand.Domain.Common;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Common{public class InsertContactUsCommand : IRequest<bool>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAttributeCombinationTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAttributeCombinationTokensCommand.csindex ca0de4856..665c37fd9 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAttributeCombinationTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAttributeCombinationTokensCommand.cs@@ -1,8 +1,8 @@-using Grand.Domain.Catalog;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Catalog;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetAttributeCombinationTokensCommand : IRequest<LiquidAttributeCombination>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAuctionTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAuctionTokensCommand.csindex d02aee823..c0a747b3b 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAuctionTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetAuctionTokensCommand.cs@@ -1,8 +1,8 @@-using Grand.Domain.Catalog;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Catalog;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetAuctionTokensCommand : IRequest<LiquidAuctions>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetGiftVoucherTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetGiftVoucherTokensCommand.csindex cb1a8a208..60734f8ab 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetGiftVoucherTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetGiftVoucherTokensCommand.cs@@ -1,9 +1,9 @@-using Grand.Domain.Localization;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Localization;using Grand.Domain.Orders;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetGiftVoucherTokensCommand : IRequest<LiquidGiftVoucher>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetMerchandiseReturnTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetMerchandiseReturnTokensCommand.csindex 57d4e0398..5ecaa2ca2 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetMerchandiseReturnTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetMerchandiseReturnTokensCommand.cs@@ -1,10 +1,10 @@-using Grand.Domain.Localization;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Localization;using Grand.Domain.Orders;using Grand.Domain.Stores;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetMerchandiseReturnTokensCommand : IRequest<LiquidMerchandiseReturn>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetOrderTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetOrderTokensCommand.csindex 055f1e99d..8764a78c0 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetOrderTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetOrderTokensCommand.cs@@ -1,11 +1,11 @@-using Grand.Domain.Customers;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Domain.Stores;using Grand.Domain.Vendors;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetOrderTokensCommand : IRequest<LiquidOrder>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShipmentTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShipmentTokensCommand.csindex b6f816ee5..fa6fa4887 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShipmentTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShipmentTokensCommand.cs@@ -1,11 +1,11 @@-using Grand.Domain.Localization;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Localization;using Grand.Domain.Orders;using Grand.Domain.Shipping;using Grand.Domain.Stores;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetShipmentTokensCommand : IRequest<LiquidShipment>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShoppingCartTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShoppingCartTokensCommand.csindex 93b77b9d5..d134ef983 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShoppingCartTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetShoppingCartTokensCommand.cs@@ -4,7 +4,7 @@ using Grand.Domain.Localization;using Grand.Domain.Stores;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetShoppingCartTokensCommand : IRequest<LiquidShoppingCart>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetStoreTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetStoreTokensCommand.csindex 9de82b34b..a002d8c86 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetStoreTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetStoreTokensCommand.cs@@ -1,10 +1,10 @@-using Grand.Domain.Localization;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Localization;using Grand.Domain.Messages;using Grand.Domain.Stores;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetStoreTokensCommand : IRequest<LiquidStore>{diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetVendorTokensCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetVendorTokensCommand.csindex dc5dda436..ea91ade59 100644--- a/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetVendorTokensCommand.cs+++ b/src/Business/Grand.Business.Core/Commands/Messages/Tokens/GetVendorTokensCommand.cs@@ -1,9 +1,9 @@-using Grand.Domain.Localization;+using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Domain.Localization;using Grand.Domain.Vendors;-using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;-namespace Grand.Business.Core.Commands.Messages+namespace Grand.Business.Core.Commands.Messages.Tokens{public class GetVendorTokensCommand : IRequest<LiquidVendor>{diff --git a/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs b/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.csindex 8140ae925..6de040eb6 100644--- a/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs+++ b/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Enums.Checkout/// <summary>/// Shipment status event/// </summary>- public partial class ShipmentStatusEvent+ public class ShipmentStatusEvent{/// <summary>/// Event namediff --git a/src/Business/Grand.Business.Core/Events/Catalog/UpdateProductOnCartEvent.cs b/src/Business/Grand.Business.Core/Events/Catalog/UpdateProductOnCartEvent.csindex ac9d434ef..6fb1a54e9 100644--- a/src/Business/Grand.Business.Core/Events/Catalog/UpdateProductOnCartEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Catalog/UpdateProductOnCartEvent.cs@@ -12,7 +12,6 @@ namespace Grand.Business.Core.Events.Catalog_product = product;}- public Product Product { get { return _product; } }-+ public Product Product => _product;}}diff --git a/src/Business/Grand.Business.Core/Events/Catalog/UpdateStockEvent.cs b/src/Business/Grand.Business.Core/Events/Catalog/UpdateStockEvent.csindex 3cbbfade2..14ade6380 100644--- a/src/Business/Grand.Business.Core/Events/Catalog/UpdateStockEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Catalog/UpdateStockEvent.cs@@ -12,6 +12,6 @@ namespace Grand.Business.Core.Events.Catalog_product = product;}- public Product Result { get { return _product; } }+ public Product Result => _product;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/Orders/CapturePaymentTransactionDetailsEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/Orders/CapturePaymentTransactionDetailsEvent.csindex be0157ed4..2f1b98d25 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/Orders/CapturePaymentTransactionDetailsEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/Orders/CapturePaymentTransactionDetailsEvent.cs@@ -7,16 +7,15 @@ namespace Grand.Business.Core.Events.Checkout.Orderspublic class CapturePaymentTransactionDetailsEvent<R, C> : INotification where R : CapturePaymentResult where C : PaymentTransaction{private readonly R _result;- private readonly C _containter;+ private readonly C _container;- public CapturePaymentTransactionDetailsEvent(R result, C containter)+ public CapturePaymentTransactionDetailsEvent(R result, C container){_result = result;- _containter = containter;+ _container = container;}- public R Result { get { return _result; } }- public C Containter { get { return _containter; } }-+ public R Result => _result;+ public C Container => _container;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/Orders/PlaceOrderDetailsEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/Orders/PlaceOrderDetailsEvent.csindex be74f0477..05e0e30e4 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/Orders/PlaceOrderDetailsEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/Orders/PlaceOrderDetailsEvent.cs@@ -3,19 +3,18 @@ using MediatR;namespace Grand.Business.Core.Events.Checkout.Orders{- public class PlaceOrderDetailsEvent<R, O> : INotification where R : PlaceOrderResult where O : PlaceOrderContainter+ public class PlaceOrderDetailsEvent<R, O> : INotification where R : PlaceOrderResult where O : PlaceOrderContainer{private readonly R _result;- private readonly O _containter;+ private readonly O _container;- public PlaceOrderDetailsEvent(R result, O containter)+ public PlaceOrderDetailsEvent(R result, O container){_result = result;- _containter = containter;+ _container = container;}- public R Result { get { return _result; } }- public O Containter { get { return _containter; } }-+ public R Result => _result;+ public O Container => _container;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/Orders/VoidPaymentTransactionDetailsEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/Orders/VoidPaymentTransactionDetailsEvent.csindex e875f1a0b..cecb56268 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/Orders/VoidPaymentTransactionDetailsEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/Orders/VoidPaymentTransactionDetailsEvent.cs@@ -7,16 +7,15 @@ namespace Grand.Business.Core.Events.Checkout.Orderspublic class VoidPaymentTransactionDetailsEvent<R, C> : INotification where R : VoidPaymentResult where C : PaymentTransaction{private readonly R _result;- private readonly C _containter;+ private readonly C _container;- public VoidPaymentTransactionDetailsEvent(R result, C containter)+ public VoidPaymentTransactionDetailsEvent(R result, C container){_result = result;- _containter = containter;+ _container = container;}- public R Result { get { return _result; } }- public C Containter { get { return _containter; } }-+ public R Result => _result;+ public C Container => _container;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/AddToCartEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/AddToCartEvent.csindex 62de3a097..5f46b4f8c 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/AddToCartEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/AddToCartEvent.cs@@ -18,9 +18,8 @@ namespace Grand.Business.Core.Events.Checkout.ShoppingCart_product = product;}- public Customer Customer { get { return _customer; } }- public ShoppingCartItem ShoppingCartItem { get { return _shoppingCartItem; } }- public Product Product { get { return _product; } }-+ public Customer Customer => _customer;+ public ShoppingCartItem ShoppingCartItem => _shoppingCartItem;+ public Product Product => _product;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartItemWarningsEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartItemWarningsEvent.csindex 44da336ad..880d5f168 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartItemWarningsEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartItemWarningsEvent.cs@@ -19,10 +19,9 @@ namespace Grand.Business.Core.Events.Checkout.ShoppingCart_shoppingCartItem = shoppingCartItem;_product = product;}- public IList<string> Warnings { get { return _warnings; } }- public C Customer { get { return _customer; } }- public S ShoppingCartItem { get { return _shoppingCartItem; } }- public P Product { get { return _product; } }-+ public IList<string> Warnings => _warnings;+ public C Customer => _customer;+ public S ShoppingCartItem => _shoppingCartItem;+ public P Product => _product;}}diff --git a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartWarningsEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartWarningsEvent.csindex bedab7e70..197d49e0e 100644--- a/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartWarningsEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Checkout/ShoppingCart/ShoppingCartWarningsEvent.cs@@ -18,12 +18,11 @@ namespace Grand.Business.Core.Events.Checkout.ShoppingCart_checkoutAttributes = checkoutAttributes;_validateCheckoutAttributes = validateCheckoutAttributes;}- public IList<T> Warnings { get { return _warnings; } }- public IList<U> ShoppingCartItems { get { return _shoppingCartItems; } }+ public IList<T> Warnings => _warnings;+ public IList<U> ShoppingCartItems => _shoppingCartItems;- public IList<CustomAttribute> CheckoutAttributes { get { return _checkoutAttributes; } }-- public bool ValidateCheckoutAttributes { get { return _validateCheckoutAttributes; } }+ public IList<CustomAttribute> CheckoutAttributes => _checkoutAttributes;+ public bool ValidateCheckoutAttributes => _validateCheckoutAttributes;}}diff --git a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.csindex b8114a257..e4a72a290 100644--- a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs@@ -13,8 +13,7 @@ namespace Grand.Business.Core.Events.Customers_result = result;_request = request;}- public C Result { get { return _result; } }- public R Request { get { return _request; } }-+ public C Result => _result;+ public R Request => _request;}}diff --git a/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs b/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.csindex 7612073a0..7ec9441a2 100644--- a/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs@@ -11,17 +11,13 @@ namespace Grand.Business.Core.Events.Marketing_email = email;}- public string Email {- get { return _email; }- }+ public string Email => _email;public bool Equals(EmailSubscribedEvent other){if (ReferenceEquals(null, other))return false;- if (ReferenceEquals(this, other))- return true;- return Equals(other._email, _email);+ return ReferenceEquals(this, other) || Equals(other._email, _email);}public override bool Equals(object obj)@@ -30,14 +26,12 @@ namespace Grand.Business.Core.Events.Marketingreturn false;if (ReferenceEquals(this, obj))return true;- if (obj.GetType() != typeof(EmailSubscribedEvent))- return false;- return Equals((EmailSubscribedEvent)obj);+ return obj.GetType() == typeof(EmailSubscribedEvent) && Equals((EmailSubscribedEvent)obj);}public override int GetHashCode(){- return (_email != null ? _email.GetHashCode() : 0);+ return _email != null ? _email.GetHashCode() : 0;}}}diff --git a/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs b/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.csindex e18858655..cd7d6553e 100644--- a/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs@@ -11,17 +11,13 @@ namespace Grand.Business.Core.Events.Marketing_email = email;}- public string Email {- get { return _email; }- }+ public string Email => _email;public bool Equals(EmailUnsubscribedEvent other){if (ReferenceEquals(null, other))return false;- if (ReferenceEquals(this, other))- return true;- return Equals(other._email, _email);+ return ReferenceEquals(this, other) || Equals(other._email, _email);}public override bool Equals(object obj)@@ -30,14 +26,12 @@ namespace Grand.Business.Core.Events.Marketingreturn false;if (ReferenceEquals(this, obj))return true;- if (obj.GetType() != typeof(EmailUnsubscribedEvent))- return false;- return Equals((EmailUnsubscribedEvent)obj);+ return obj.GetType() == typeof(EmailUnsubscribedEvent) && Equals((EmailUnsubscribedEvent)obj);}public override int GetHashCode(){- return (_email != null ? _email.GetHashCode() : 0);+ return _email != null ? _email.GetHashCode() : 0;}}diff --git a/src/Business/Grand.Business.Core/Events/Messages/EntityTokensAddedEvent.cs b/src/Business/Grand.Business.Core/Events/Messages/EntityTokensAddedEvent.csindex 926ff304a..088a7957e 100644--- a/src/Business/Grand.Business.Core/Events/Messages/EntityTokensAddedEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Messages/EntityTokensAddedEvent.cs@@ -9,8 +9,6 @@ namespace Grand.Business.Core.Events.Messages/// A container for tokens that are added./// </summary>/// <typeparam name="T">Entity type</typeparam>- /// <param name="liquidDrop">DotLiquid Drop, e.g. LiquidOrder</param>- /// <param name="liquidObject">An object that acumulates all DotLiquid Drops</param>public class EntityTokensAddedEvent<T> : INotification where T : ParentEntity{private readonly T _entity;@@ -24,8 +22,8 @@ namespace Grand.Business.Core.Events.Messages_liquidObject = liquidObject;}- public T Entity { get { return _entity; } }- public Drop LiquidDrop { get { return _liquidDrop; } }- public LiquidObject LiquidObject { get { return _liquidObject; } }+ public T Entity => _entity;+ public Drop LiquidDrop => _liquidDrop;+ public LiquidObject LiquidObject => _liquidObject;}}diff --git a/src/Business/Grand.Business.Core/Events/Messages/MessageTokensAddedEvent.cs b/src/Business/Grand.Business.Core/Events/Messages/MessageTokensAddedEvent.csindex 637a3e951..fe6384ce3 100644--- a/src/Business/Grand.Business.Core/Events/Messages/MessageTokensAddedEvent.cs+++ b/src/Business/Grand.Business.Core/Events/Messages/MessageTokensAddedEvent.cs@@ -6,7 +6,6 @@ namespace Grand.Business.Core.Events.Messages/// <summary>/// A container for tokens that are added./// </summary>- /// <typeparam name="U"></typeparam>public class MessageTokensAddedEvent : INotification{private readonly MessageTemplate _message;@@ -18,7 +17,7 @@ namespace Grand.Business.Core.Events.Messages_liquidObject = liquidObject;}- public MessageTemplate Message { get { return _message; } }- public LiquidObject LiquidObject { get { return _liquidObject; } }+ public MessageTemplate Message => _message;+ public LiquidObject LiquidObject => _liquidObject;}}diff --git a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.csindex 09fab33af..30f9b85ed 100644--- a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs@@ -21,15 +21,15 @@ namespace Grand.Business.Core.Extensionsvar firstName = affiliate.Address.FirstName;var lastName = affiliate.Address.LastName;- string fullName = "";- if (!String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName))- fullName = string.Format("{0} {1}", firstName, lastName);+ var fullName = "";+ if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName))+ fullName = $"{firstName} {lastName}";else{- if (!String.IsNullOrWhiteSpace(firstName))+ if (!string.IsNullOrWhiteSpace(firstName))fullName = firstName;- if (!String.IsNullOrWhiteSpace(lastName))+ if (!string.IsNullOrWhiteSpace(lastName))fullName = lastName;}return fullName;@@ -37,11 +37,11 @@ namespace Grand.Business.Core.Extensions/// <summary>- /// Generate affilaite URL+ /// Generate affiliate URL/// </summary>/// <param name="affiliate">Affiliate</param>/// <param name="host">Host</param>- /// <returns>Generated affilaite URL</returns>+ /// <returns>Generated affiliate URL</returns>public static string GenerateUrl(this Affiliate affiliate, string host){if (affiliate == null)@@ -61,7 +61,10 @@ namespace Grand.Business.Core.Extensions/// Validate friendly URL name/// </summary>/// <param name="affiliate">Affiliate</param>+ /// <param name="seoSettings"></param>/// <param name="friendlyUrlName">Friendly URL name</param>+ /// <param name="affiliateService"></param>+ /// <param name="name"></param>/// <returns>Valid friendly name</returns>public static async Task<string> ValidateFriendlyUrlName(this Affiliate affiliate, IAffiliateService affiliateService, SeoSettings seoSettings, string friendlyUrlName, string name){@@ -77,19 +80,19 @@ namespace Grand.Business.Core.Extensions//max lengthfriendlyUrlName = CommonHelper.EnsureMaximumLength(friendlyUrlName, 200);- if (String.IsNullOrEmpty(friendlyUrlName))+ if (string.IsNullOrEmpty(friendlyUrlName))return friendlyUrlName;//check whether such friendly URL name already exists (and that is not the current affiliate)- int i = 2;+ var i = 2;var tempName = friendlyUrlName;while (true){var affiliateByFriendlyUrlName = await affiliateService.GetAffiliateByFriendlyUrlName(tempName);- bool reserved = affiliateByFriendlyUrlName != null && affiliateByFriendlyUrlName.Id != affiliate.Id;+ var reserved = affiliateByFriendlyUrlName != null && affiliateByFriendlyUrlName.Id != affiliate.Id;if (!reserved)break;- tempName = string.Format("{0}-{1}", friendlyUrlName, i);+ tempName = $"{friendlyUrlName}-{i}";i++;}friendlyUrlName = tempName;diff --git a/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.csindex 5059b5e94..af0626e57 100644--- a/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs@@ -22,14 +22,7 @@ namespace Grand.Business.Core.Extensionsif (settings == null)throw new ArgumentNullException(nameof(settings));- if (settings.ActiveAuthenticationMethodSystemNames == null)- return false;-- foreach (string activeMethodSystemName in settings.ActiveAuthenticationMethodSystemNames)- if (method.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase))- return true;-- return false;+ return settings.ActiveAuthenticationMethodSystemNames != null && settings.ActiveAuthenticationMethodSystemNames.Any(activeMethodSystemName => method.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase));}}}diff --git a/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs b/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.csindex 40a9e27ac..66d8a3095 100644--- a/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs@@ -10,6 +10,7 @@ namespace Grand.Business.Core.Extensions/// Save an entity/// </summary>/// <param name="entity">Entity</param>+ /// <param name="historyService"></param>public static async Task SaveHistory<T>(this BaseEntity entity, IHistoryService historyService) where T : BaseEntity, IHistory{if (entity == null)diff --git a/src/Business/Grand.Business.Core/Extensions/OrderEventPublisherExtensions.cs b/src/Business/Grand.Business.Core/Extensions/OrderEventPublisherExtensions.csindex d2ce8142c..e5c0de644 100644--- a/src/Business/Grand.Business.Core/Extensions/OrderEventPublisherExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/OrderEventPublisherExtensions.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Extensions{public static class OrderEventPublisherExtensions{- public static async Task PlaceOrderDetailsEvent<R, O>(this IMediator eventPublisher, R result, O order) where R : PlaceOrderResult where O : PlaceOrderContainter+ public static async Task PlaceOrderDetailsEvent<R, O>(this IMediator eventPublisher, R result, O order) where R : PlaceOrderResult where O : PlaceOrderContainer{await eventPublisher.Publish(new PlaceOrderDetailsEvent<R, O>(result, order));}diff --git a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.csindex 046a359b5..db19c3d75 100644--- a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs@@ -25,12 +25,7 @@ namespace Grand.Business.Core.Extensionsif (paymentSettings == null)throw new ArgumentNullException(nameof(paymentSettings));- if (paymentSettings.ActivePaymentProviderSystemNames == null)- return false;- foreach (var activeMethodSystemName in paymentSettings.ActivePaymentProviderSystemNames)- if (paymentMethod.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase))- return true;- return false;+ return paymentSettings.ActivePaymentProviderSystemNames != null && paymentSettings.ActivePaymentProviderSystemNames.Any(activeMethodSystemName => paymentMethod.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase));}/// <summary>@@ -56,7 +51,7 @@ namespace Grand.Business.Core.Extensions{//percentagevar shoppingCartSubTotal = await orderTotalCalculationService.GetShoppingCartSubTotal(cart, true);- result = (double)((((float)shoppingCartSubTotal.subTotalWithDiscount) * ((float)fee)) / 100f);+ result = (float)shoppingCartSubTotal.subTotalWithDiscount * (float)fee / 100f;}else{diff --git a/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs b/src/Business/Grand.Business.Core/Extensions/RoundingHelper.csindex 8b8047e27..f9057fc2e 100644--- a/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs+++ b/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs@@ -13,17 +13,16 @@ namespace Grand.Business.Core.Extensions/// <returns>Rounded value</returns>public static double RoundPrice(double value, Currency currency){- if (currency != null)- return value.Round(currency.NumberDecimal, currency.RoundingTypeId, currency.MidpointRoundId);- else- return value;+ return currency != null ? value.Round(currency.NumberDecimal, currency.RoundingTypeId, currency.MidpointRoundId) : value;}/// <summary>/// Round/// </summary>/// <param name="value">Value to round</param>+ /// <param name="doubles">Doubles</param>/// <param name="roundingType">The rounding type</param>+ /// <param name="midpointRounding">Mid point rounding</param>/// <returns>Rounded value</returns>public static double Round(this double value, int doubles, RoundingType roundingType, MidpointRounding midpointRounding){@@ -43,7 +42,7 @@ namespace Grand.Business.Core.Extensionscase RoundingType.Rounding005Up:case RoundingType.Rounding005Down:fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10;- if (fractionPart == 5 || fractionPart == 0)+ if (fractionPart is 5 or 0)break;if (roundingType == RoundingType.Rounding005Down)fractionPart = fractionPart > 5 ? 5 - fractionPart : fractionPart * -1;diff --git a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.csindex a22359180..e54ee971e 100644--- a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Core.Extensions#region Fieldsprivate static Dictionary<string, string> _seoCharacterTable;- private static readonly object s_lock = new object();+ private static readonly object SLock = new object();#endregion@@ -54,7 +54,7 @@ namespace Grand.Business.Core.Extensionsvar seName = string.Empty;if (!string.IsNullOrEmpty(languageId)){- var value = entity.Locales.Where(x => x.LanguageId == languageId && x.LocaleKey == "SeName").FirstOrDefault();+ var value = entity.Locales.FirstOrDefault(x => x.LanguageId == languageId && x.LocaleKey == "SeName");if (value != null)if (!string.IsNullOrEmpty(value.LocaleValue))seName = value.LocaleValue;@@ -74,9 +74,12 @@ namespace Grand.Business.Core.Extensions/// </summary>/// <param name="entity">Entity</param>/// <param name="seName">Search engine name to validate</param>- /// <param name="name">User-friendly name used to generate sename</param>- /// <param name="ensureNotEmpty">Ensreu that sename is not empty</param>- /// <returns>Valid sename</returns>+ /// <param name="name">User-friendly name used to generate se-name</param>+ /// <param name="ensureNotEmpty">Ensure that se-name is not empty</param>+ /// <param name="seoSettings"></param>+ /// <param name="slugService"></param>+ /// <param name="languageService"></param>+ /// <returns>Valid se-name</returns>public static async Task<string> ValidateSeName<T>(this T entity, string seName, string name, bool ensureNotEmpty,SeoSettings seoSettings, ISlugService slugService, ILanguageService languageService)where T : BaseEntity, ISlugEntity@@ -84,7 +87,7 @@ namespace Grand.Business.Core.Extensionsif (entity == null)throw new ArgumentNullException(nameof(entity));- //use name if sename is not specified+ //use name if se-name is not specifiedif (string.IsNullOrWhiteSpace(seName) && !string.IsNullOrWhiteSpace(name))seName = name;@@ -101,8 +104,8 @@ namespace Grand.Business.Core.Extensions{if (ensureNotEmpty){- //use entity identifier as sename if empty- seName = entity.Id.ToString();+ //use entity identifier as se-name if empty+ seName = entity.Id;}else{@@ -111,7 +114,7 @@ namespace Grand.Business.Core.Extensions}}- //ensure this sename is not reserved yet+ //ensure this se-name is not reserved yetvar entityName = typeof(T).Name;var i = 1;var tempSeName = seName;@@ -126,13 +129,11 @@ namespace Grand.Business.Core.Extensionsif (!reserved1 && !reserved2 && !reserved3)break;- tempSeName = string.Format("{0}-{1}", seName, i);+ tempSeName = $"{seName}-{i}";i++;- if(i > 4)- {- tempSeName = string.Format("{0}-{1}", seName, Guid.NewGuid());- break;- }+ if (i <= 4) continue;+ tempSeName = $"{seName}-{Guid.NewGuid()}";+ break;}seName = tempSeName;@@ -144,6 +145,7 @@ namespace Grand.Business.Core.Extensions/// Get SE name/// </summary>/// <param name="name">Name</param>+ /// <param name="seoSettings">SeoSettings</param>/// <returns>Result</returns>public static string GetSeName(string name, SeoSettings seoSettings){@@ -154,25 +156,31 @@ namespace Grand.Business.Core.Extensions/// Get SE name/// </summary>/// <param name="name">Name</param>+ /// <param name="convertNonWesternChars"></param>+ /// <param name="allowUnicodeCharsInUrls"></param>+ /// <param name="charConversions"></param>/// <returns>Result</returns>public static string GetSeName(string name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, string charConversions = null){return GenerateSlug(name, convertNonWesternChars, allowUnicodeCharsInUrls, false, charConversions);}+/// <summary>/// Get SE name/// </summary>/// <param name="name">Name</param>/// <param name="convertNonWesternChars">A value indicating whether non western chars should be converted</param>/// <param name="allowUnicodeCharsInUrls">A value indicating whether Unicode chars are allowed</param>+ /// <param name="allowSlashChar"></param>+ /// <param name="charConversions"></param>/// <returns>Result</returns>- public static string GenerateSlug(string name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, bool allowslashChar, string charConversions = null)+ public static string GenerateSlug(string name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, bool allowSlashChar, string charConversions = null){if (string.IsNullOrEmpty(name))return name;var okChars = "abcdefghijklmnopqrstuvwxyz1234567890 _-";- if (allowslashChar)+ if (allowSlashChar)okChars += '/';name = name.Trim().ToLowerInvariant();@@ -214,20 +222,18 @@ namespace Grand.Business.Core.Extensionsprivate static void InitializeSeoCharacterTable(string charConversions){- lock (s_lock)+ lock (SLock){- if (_seoCharacterTable == null)- {- _seoCharacterTable = new Dictionary<string, string>();+ if (_seoCharacterTable != null) return;+ _seoCharacterTable = new Dictionary<string, string>();- foreach (var conversion in charConversions.Split(";"))+ foreach (var conversion in charConversions.Split(";"))+ {+ var strLeft = conversion.Split(":").FirstOrDefault();+ var strRight = conversion.Split(":").LastOrDefault();+ if (!string.IsNullOrEmpty(strLeft) && !_seoCharacterTable.ContainsKey(strLeft)){- var strLeft = conversion.Split(":").FirstOrDefault();- var strRight = conversion.Split(":").LastOrDefault();- if (!string.IsNullOrEmpty(strLeft) && !_seoCharacterTable.ContainsKey(strLeft))- {- _seoCharacterTable.Add(strLeft.Trim(), strRight.Trim());- }+ _seoCharacterTable.Add(strLeft.Trim(), strRight?.Trim());}}}diff --git a/src/Business/Grand.Business.Core/Extensions/ShippingEventPublisherExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ShippingEventPublisherExtensions.csindex 140b1106d..9565d5435 100644--- a/src/Business/Grand.Business.Core/Extensions/ShippingEventPublisherExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/ShippingEventPublisherExtensions.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Extensions/// <summary>/// Publishes the shipment sent event./// </summary>- /// <param name="eventPublisher">The event publisher.</param>+ /// <param name="mediator">The event publisher.</param>/// <param name="shipment">The shipment.</param>public static async Task PublishShipmentSent(this IMediator mediator, Shipment shipment){@@ -18,7 +18,7 @@ namespace Grand.Business.Core.Extensions/// <summary>/// Publishes the shipment delivered event./// </summary>- /// <param name="eventPublisher">The event publisher.</param>+ /// <param name="mediator">The event publisher.</param>/// <param name="shipment">The shipment.</param>public static async Task PublishShipmentDelivered(this IMediator mediator, Shipment shipment){diff --git a/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.csindex 0ef281180..eec154019 100644--- a/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs@@ -14,12 +14,7 @@ namespace Grand.Business.Core.Extensionsif (shippingProviderSettings == null)throw new ArgumentNullException(nameof(shippingProviderSettings));- if (shippingProviderSettings.ActiveSystemNames == null)- return false;- foreach (string activeMethodSystemName in shippingProviderSettings.ActiveSystemNames)- if (srcm.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase))- return true;- return false;+ return shippingProviderSettings.ActiveSystemNames != null && shippingProviderSettings.ActiveSystemNames.Any(activeMethodSystemName => srcm.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase));}public static bool CountryRestrictionExists(this ShippingMethod shippingMethod,@@ -28,7 +23,7 @@ namespace Grand.Business.Core.Extensionsif (shippingMethod == null)throw new ArgumentNullException(nameof(shippingMethod));- bool result = shippingMethod.RestrictedCountries.ToList().Find(c => c.Id == countryId) != null;+ var result = shippingMethod.RestrictedCountries.ToList().Find(c => c.Id == countryId) != null;return result;}public static bool CustomerGroupRestrictionExists(this ShippingMethod shippingMethod,@@ -37,7 +32,7 @@ namespace Grand.Business.Core.Extensionsif (shippingMethod == null)throw new ArgumentNullException(nameof(shippingMethod));- bool result = shippingMethod.RestrictedGroups.ToList().Find(c => c == roleId) != null;+ var result = shippingMethod.RestrictedGroups.ToList().Find(c => c == roleId) != null;return result;}@@ -47,7 +42,7 @@ namespace Grand.Business.Core.Extensionsif (shippingMethod == null)throw new ArgumentNullException(nameof(shippingMethod));- bool result = shippingMethod.RestrictedGroups.ToList().Find(c => roleIds.Contains(c)) != null;+ var result = shippingMethod.RestrictedGroups.ToList().Find(roleIds.Contains) != null;return result;}}diff --git a/src/Business/Grand.Business.Core/Extensions/ShoppingCartEventPublisherExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ShoppingCartEventPublisherExtensions.csindex 0e8c71554..b20df6832 100644--- a/src/Business/Grand.Business.Core/Extensions/ShoppingCartEventPublisherExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/ShoppingCartEventPublisherExtensions.cs@@ -14,9 +14,9 @@ namespace Grand.Business.Core.Extensionsawait eventPublisher.Publish(new ShoppingCartWarningsEvent<T, U>(warnings, shoppingCartItems, checkoutAttributes, validateCheckoutAttributes));}- public static async Task ShoppingCartItemWarningsAdded<C, S, P>(this IMediator eventPublisher, IList<string> warnings, C customer, S shoppingcartItem, P product) where C : Customer where S : ShoppingCartItem where P : Product+ public static async Task ShoppingCartItemWarningsAdded<C, S, P>(this IMediator eventPublisher, IList<string> warnings, C customer, S shoppingCartItem, P product) where C : Customer where S : ShoppingCartItem where P : Product{- await eventPublisher.Publish(new ShoppingCartItemWarningsEvent<C, S, P>(warnings, customer, shoppingcartItem, product));+ await eventPublisher.Publish(new ShoppingCartItemWarningsEvent<C, S, P>(warnings, customer, shoppingCartItem, product));}}diff --git a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.csindex bff53f479..76055b730 100644--- a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs@@ -30,8 +30,7 @@ namespace Grand.Business.Core.Extensionsif (entity == null)throw new ArgumentNullException(nameof(entity));- var member = keySelector.Body as MemberExpression;- if (member == null)+ if (keySelector.Body is not MemberExpression member)throw new ArgumentException($"Expression '{keySelector}' refers to a method, not a property.");var propInfo = member.Member as PropertyInfo;@@ -39,12 +38,11 @@ namespace Grand.Business.Core.Extensionsthrow new ArgumentException($"Expression '{keySelector}' refers to a field, not a property.");string result = default;- string resultStr = string.Empty;+ var resultStr = string.Empty;- string localeKeyGroup = typeof(T).Name;- string localeKey = propInfo.Name;+ var localeKey = propInfo.Name;- if (!String.IsNullOrEmpty(languageId))+ if (!string.IsNullOrEmpty(languageId)){if (entity.Locales.Any()){@@ -52,16 +50,16 @@ namespace Grand.Business.Core.Extensionsif (en != null){resultStr = en.LocaleValue;- if (!String.IsNullOrEmpty(resultStr))+ if (!string.IsNullOrEmpty(resultStr))result = resultStr;}}}//set default value if required- if (String.IsNullOrEmpty(resultStr) && returnDefaultValue)+ if (string.IsNullOrEmpty(resultStr) && returnDefaultValue){- result = (string)(propInfo.GetValue(entity));+ result = (string)propInfo.GetValue(entity);}return result;}@@ -102,13 +100,11 @@ namespace Grand.Business.Core.Extensionsif (!typeof(T).GetTypeInfo().IsEnum) throw new ArgumentException("T must be enum type");//Translation value- string resourceName = string.Format("Enums.{0}.{1}",- typeof(T),- enumValue.ToString());- string result = translationService.GetResource(resourceName, languageId, "", true);+ var resourceName = $"Enums.{typeof(T)}.{enumValue.ToString()}";+ var result = translationService.GetResource(resourceName, languageId, "", true);//set default value if required- if (String.IsNullOrEmpty(result))+ if (string.IsNullOrEmpty(result))result = CommonHelper.ConvertEnum(enumValue);return result;@@ -149,11 +145,11 @@ namespace Grand.Business.Core.Extensionsthrow new ArgumentNullException(nameof(translationService));//Translation value- string name = $"Permission.{permissionRecord.SystemName}";- string result = translationService.GetResource(name, languageId, "", true);+ var name = $"Permission.{permissionRecord.SystemName}";+ var result = translationService.GetResource(name, languageId, "", true);//set default value if required- if (String.IsNullOrEmpty(result))+ if (string.IsNullOrEmpty(result))result = permissionRecord.Name;return result;@@ -175,8 +171,8 @@ namespace Grand.Business.Core.Extensionsif (languageService == null)throw new ArgumentNullException(nameof(languageService));- string name = $"Permission.{permissionRecord.SystemName}";- string value = permissionRecord.Name;+ var name = $"Permission.{permissionRecord.SystemName}";+ var value = permissionRecord.Name;foreach (var lang in await languageService.GetAllLanguages(true)){@@ -214,7 +210,7 @@ namespace Grand.Business.Core.Extensionsif (languageService == null)throw new ArgumentNullException(nameof(languageService));- string name = $"Permission.{permissionRecord.SystemName}";+ var name = $"Permission.{permissionRecord.SystemName}";foreach (var lang in await languageService.GetAllLanguages(true)){var lsr = await translationService.GetTranslateResourceByName(name, lang.Id);@@ -275,7 +271,7 @@ namespace Grand.Business.Core.Extensionsname = name.ToLowerInvariant();foreach (var lang in await languageService.GetAllLanguages(true)){- if (!String.IsNullOrEmpty(languageCulture) && !languageCulture.Equals(lang.LanguageCulture))+ if (!string.IsNullOrEmpty(languageCulture) && !languageCulture.Equals(lang.LanguageCulture))continue;var lsr = await translationService.GetTranslateResourceByName(name, lang.Id);diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.csindex 830cf3dd5..e218e33f1 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Authentication{- public partial interface IApiAuthenticationService+ public interface IApiAuthenticationService{/// <summary>/// Get authenticated customerdiff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IAuthenticationBuilder.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IAuthenticationBuilder.csindex e1a4c02ba..fb3262a42 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IAuthenticationBuilder.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IAuthenticationBuilder.cs@@ -12,6 +12,7 @@ namespace Grand.Business.Core.Interfaces.Authentication/// Add Authentication/// </summary>/// <param name="builder">Add Authentication builder</param>+ /// <param name="configuration">Configuration</param>void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration);/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationProvider.csindex d340f3dc4..51324c2c5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationProvider.cs@@ -5,12 +5,11 @@ namespace Grand.Business.Core.Interfaces.Authentication/// <summary>/// Represents method for the external authentication/// </summary>- public partial interface IExternalAuthenticationProvider : IProvider+ public interface IExternalAuthenticationProvider : IProvider{/// <summary>/// Gets a view component for displaying plugin in public store/// </summary>- /// <param name="viewComponentName">View component name</param>Task<string> GetPublicViewComponentName();}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.csindex fafb5a085..1ebde72cb 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Authentication/// <summary>/// External authentication service/// </summary>- public partial interface IExternalAuthenticationService+ public interface IExternalAuthenticationService{#region External authentication methods@@ -76,7 +76,7 @@ namespace Grand.Business.Core.Interfaces.Authentication/// <summary>/// Delete the external authentication/// </summary>- /// <param name="externalAuthenticationRecord">External authentication</param>+ /// <param name="externalAuthentication">External authentication</param>Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication);}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IGrandAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IGrandAuthenticationService.csindex aa89b70f0..51d2372b7 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IGrandAuthenticationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IGrandAuthenticationService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Authentication/// <summary>/// Authentication service interface/// </summary>- public partial interface IGrandAuthenticationService+ public interface IGrandAuthenticationService{/// <summary>/// Sign indiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.csindex cc72da63b..eea11ce26 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs@@ -2,7 +2,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Interfaces.Catalog.Brands{- public partial interface IBrandLayoutService+ public interface IBrandLayoutService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.csindex eda627b1b..c263240c1 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs@@ -6,13 +6,13 @@ namespace Grand.Business.Core.Interfaces.Catalog.Brands/// <summary>/// Brand service/// </summary>- public partial interface IBrandService+ public interface IBrandService{-/// <summary>/// Gets all brands/// </summary>/// <param name="brandName">Brand name</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>@@ -49,7 +49,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.BrandsTask DeleteBrand(Brand brand);/// <summary>- /// Gets all manfucaturers by discount id+ /// Gets all brands by discount id/// </summary>/// <param name="discountId">Discount id </param>/// <returns>Product brand mapping</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.csindex 79b8b8498..a1e653118 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs@@ -2,7 +2,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Interfaces.Catalog.Categories{- public partial interface ICategoryLayoutService+ public interface ICategoryLayoutService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.csindex 4c587b419..8e776a785 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Interfaces.Catalog.Categories{- public partial interface ICategoryService+ public interface ICategoryService{/// <summary>/// Gets all categories@@ -50,7 +50,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Categories/// <summary>/// Gets all categories that should be displayed in search box/// </summary>- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>/// <returns>Categories</returns>Task<IList<Category>> GetAllCategoriesSearchBox();diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.csindex b440cc64f..467172e8f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs@@ -2,7 +2,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Interfaces.Catalog.Collections{- public partial interface ICollectionLayoutService+ public interface ICollectionLayoutService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.csindex 3464de6c8..d612c1ade 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs@@ -6,13 +6,13 @@ namespace Grand.Business.Core.Interfaces.Catalog.Collections/// <summary>/// Collection service/// </summary>- public partial interface ICollectionService+ public interface ICollectionService{-/// <summary>/// Gets all collections/// </summary>/// <param name="collectionName">Collection name</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>@@ -24,7 +24,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Collectionsbool showHidden = false);/// <summary>- /// Gets all collections featired products displayed on the home page+ /// Gets all collections products displayed on the home page/// </summary>/// <param name="showHidden">A value that indicates if it should shows hidden records</param>/// <returns>Collections</returns>@@ -56,7 +56,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.CollectionsTask DeleteCollection(Collection collection);/// <summary>- /// Gets all manfucaturers by discount id+ /// Gets all brands by discount id/// </summary>/// <param name="discountId">Discount id </param>/// <returns>Product collection mapping</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IGeoLookupService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IGeoLookupService.csindex f833f09d3..1271145f7 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IGeoLookupService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IGeoLookupService.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Directory/// <summary>/// GEO lookup service/// </summary>- public partial interface IGeoLookupService+ public interface IGeoLookupService{/// <summary>/// Get country namediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.csindex ba878ff87..ad0adadc6 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Directory/// <summary>/// Measure dimension service interface/// </summary>- public partial interface IMeasureService+ public interface IMeasureService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.csindex f051aac36..eabbb9368 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs@@ -5,9 +5,9 @@ using Grand.Domain.Common;namespace Grand.Business.Core.Interfaces.Catalog.Directory{/// <summary>- /// Search term service interafce+ /// Search term service interface/// </summary>- public partial interface ISearchTermService+ public interface ISearchTermService{/// <summary>/// Deletes a search term recorddiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.csindex 3ef0cc2c4..9c13c0ab9 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs@@ -5,7 +5,7 @@ using Grand.Infrastructure.Plugins;namespace Grand.Business.Core.Interfaces.Catalog.Discounts{- public partial interface IDiscountAmountProvider : IProvider+ public interface IDiscountAmountProvider : IProvider{Task<double> DiscountAmount(Discount discount, Customer customer, Product product, double amount);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProvider.csindex c933351a2..df911452c 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProvider.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Catalog.Discounts{- public partial interface IDiscountProvider : IProvider+ public interface IDiscountProvider : IProvider{IList<IDiscountRule> GetRequirementRules();}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountRule.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountRule.csindex c46dd35e2..496a2cfb8 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountRule.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountRule.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Catalog.Discounts{- public partial interface IDiscountRule+ public interface IDiscountRule{/// <summary>/// Check discount requirementsdiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.csindex df51cd09e..b839aa1ee 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// <summary>/// Discount service interface/// </summary>- public partial interface IDiscountService+ public interface IDiscountService{/// <summary>@@ -48,9 +48,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// <summary>/// Loads existing discount provider by rule system name/// </summary>- /// <param name="rulesystemName">Rule system name</param>+ /// <param name="ruleSystemName">Rule system name</param>/// <returns>Discount provider</returns>- IDiscountProvider LoadDiscountProviderByRuleSystemName(string rulesystemName);+ IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName);/// <summary>/// Loads all available discount providers@@ -72,6 +72,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// </summary>/// <param name="couponCode"></param>/// <param name="discountId"></param>+ /// <param name="used"></param>/// <returns></returns>Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used);@@ -118,6 +119,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// <param name="discountId">Discount id; use null to load all existing discounts</param>/// <param name="customerId">Customer id; use null to load all existing customers</param>/// <param name="orderId">Order id; use null to load all existing orders</param>+ /// <param name="canceled">Canceled</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Discount usage history records</returns>@@ -176,7 +178,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// Updates discount code - defines it as used or not/// </summary>/// <param name="couponCode"></param>- /// <param name="discountId"></param>/// <param name="used"></param>Task DiscountCouponSetAsUsed(string couponCode, bool used);diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.csindex 69e45712a..31305d2d3 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs@@ -4,7 +4,7 @@ using Grand.Domain.Localization;namespace Grand.Business.Core.Interfaces.Catalog.Prices{- public partial interface IPriceFormatter+ public interface IPriceFormatter{/// <summary>/// Formats pricediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.csindex 399a2b714..54dc4913b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// <summary>/// Price calculation service/// </summary>- public partial interface IPricingService+ public interface IPricingService{/// <summary>/// Gets the final price@@ -72,7 +72,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// <param name="currency">The currency</param>/// <param name="shoppingCartType">Shopping cart type</param>/// <param name="quantity">Quantity</param>- /// <param name="attributes">Product atrributes</param>+ /// <param name="attributes">Product attributes</param>/// <param name="customerEnteredPrice">Customer entered price (if specified)</param>/// <param name="rentalStartDate">Rental start date (null for not rental products)</param>/// <param name="rentalEndDate">Rental end date (null for not rental products)</param>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.csindex 125973514..db3ddac54 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Auction service interface/// </summary>- public partial interface IAuctionService+ public interface IAuctionService{/// <summary>@@ -34,6 +34,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Gets bids for product Id/// </summary>/// <param name="productId">Product Id</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Bids</returns>Task<IPagedList<Bid>> GetBidsByProductId(string productId, int pageIndex = 0, int pageSize = int.MaxValue);@@ -41,15 +43,17 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Gets bids for Customer Id/// </summary>/// <param name="customerId">Customer Id</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Bids</returns>Task<IPagedList<Bid>> GetBidsByCustomerId(string customerId, int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>/// Gets bid for specified Id/// </summary>- /// <param name="Id">Id</param>+ /// <param name="id">Id</param>/// <returns>Bid</returns>- Task<Bid> GetBid(string Id);+ Task<Bid> GetBid(string id);/// <summary>/// Get latest bid for product Id@@ -71,8 +75,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// </summary>/// <param name="product"></param>/// <param name="ended"></param>- /// <param name="enddate"></param>- Task UpdateAuctionEnded(Product product, bool ended, bool enddate = false);+ /// <param name="endDate"></param>+ Task UpdateAuctionEnded(Product product, bool ended, bool endDate = false);/// <summary>/// Gets auctions that have to be endeddiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICopyProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICopyProductService.csindex 50ee61abc..aecad5242 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICopyProductService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICopyProductService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Copy product service/// </summary>- public partial interface ICopyProductService+ public interface ICopyProductService{/// <summary>/// Create a copy of product with all depended datadiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.csindex 0c66b40f3..27fbeeafa 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs@@ -22,7 +22,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Gets customer groups product/// </summary>- /// <param name="Id">id</param>+ /// <param name="id">id</param>/// <returns>Customer group product</returns>Task<CustomerGroupProduct> GetCustomerGroupProductById(string id);diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.csindex f6c994cc4..ef3d987f1 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs@@ -19,8 +19,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Adjust reserved inventory/// </summary>/// <param name="product">Product</param>- /// <param name="quantityToChange">Quantity to increase or descrease</param>+ /// <param name="quantityToChange">Quantity to increase or decrease</param>/// <param name="attributes">Attributes</param>+ /// <param name="warehouseId">Warehouse ident</param>Task AdjustReserved(Product product, int quantityToChange, IList<CustomAttribute> attributes = null, string warehouseId = "");diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.csindex d029dbf2c..029ac2d3a 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Out of stock subscription service interface/// </summary>- public partial interface IOutOfStockSubscriptionService+ public interface IOutOfStockSubscriptionService{/// <summary>/// Gets all subscriptionsdiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.csindex d94c4c1ae..7be138c77 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product attribute formatter interface/// </summary>- public partial interface IProductAttributeFormatter+ public interface IProductAttributeFormatter{/// <summary>/// Formats attributes@@ -23,15 +23,16 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <param name="product">Product</param>/// <param name="customAttributes">Attributes</param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>/// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>/// <param name="renderGiftVoucherAttributes">A value indicating whether to render gift voucher attributes</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>+ /// <param name="showInAdmin">Show in admin</param>/// <returns>Attributes</returns>Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes,- Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true,+ Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true,bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true,bool allowHyperlinks = true, bool showInAdmin = false);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.csindex 951e470f0..d8254bcb2 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product attribute service interface/// </summary>- public partial interface IProductAttributeService+ public interface IProductAttributeService{#region Product attributesdiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.csindex d116b2eb8..b23fb7145 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product layout interface/// </summary>- public partial interface IProductLayoutService+ public interface IProductLayoutService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.csindex 116053cf0..daa54ad19 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product reservation service interface/// </summary>- public partial interface IProductReservationService+ public interface IProductReservationService{/// <summary>@@ -31,6 +31,10 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Gets product reservations for product Id/// </summary>/// <param name="productId">Product Id</param>+ /// <param name="showVacant">Show vacant</param>+ /// <param name="date">Date</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>/// <returns>Product reservations</returns>Task<IPagedList<ProductReservation>> GetProductReservationsByProductId(string productId, bool? showVacant, DateTime? date,int pageIndex = 0, int pageSize = int.MaxValue);@@ -38,9 +42,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Gets product reservation for specified Id/// </summary>- /// <param name="Id">Product Id</param>+ /// <param name="id">Product Id</param>/// <returns>Product reservation</returns>- Task<ProductReservation> GetProductReservation(string Id);+ Task<ProductReservation> GetProductReservation(string id);/// <summary>/// Adds customer reservations helper@@ -63,22 +67,22 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Gets customer reservations helper by id/// </summary>- /// <param name="Id"></param>+ /// <param name="id"></param>/// <returns>CustomerReservationsHelper</returns>- Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string Id);+ Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string id);/// <summary>/// Gets customer reservations helpers/// </summary>/// <param name="customerId">Customer ident</param>- /// <returns>List<CustomerReservationsHelper></returns>+ /// <returns>List<CustomerReservationsHelper />+ /// </returns>Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelpers(string customerId);/// <summary>/// Gets customer reservations helper by Shopping Cart Item id/// </summary>- /// <param name="Id"></param>- /// <returns>List<CustomerReservationsHelper></returns>+ /// <param name="sciId">Sci ident</param>Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelperBySciId(string sciId);}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.csindex f0c0021c7..257245fb4 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs@@ -6,19 +6,19 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product review service/// </summary>- public partial interface IProductReviewService+ public interface IProductReviewService{/// <summary>/// Insert product review/// </summary>- /// <param name="productreview">Product review</param>- Task InsertProductReview(ProductReview productreview);+ /// <param name="productReview">Product review</param>+ Task InsertProductReview(ProductReview productReview);/// <summary>/// Update product review/// </summary>- /// <param name="productreview">Product review</param>- Task UpdateProductReview(ProductReview productreview);+ /// <param name="productReview">Product review</param>+ Task UpdateProductReview(ProductReview productReview);/// <summary>/// Deletes a product review@@ -36,6 +36,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <param name="message">Search title or review text; null to load all records</param>/// <param name="storeId">Store identifier; "" to load all records</param>/// <param name="productId">Product identifier; "" to load all records</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Reviews</returns>Task<IPagedList<ProductReview>> GetAllProductReviews(string customerId, bool? approved = null,DateTime? fromUtc = null, DateTime? toUtc = null,diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.csindex df35b4684..745472cac 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product service/// </summary>- public partial interface IProductService+ public interface IProductService{#region Products@@ -29,9 +29,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Gets product/// </summary>/// <param name="productId">Product identifier</param>- /// <param name="fromDB">get data from db (not from cache)</param>+ /// <param name="fromDb">get data from db (not from cache)</param>/// <returns>Product</returns>- Task<Product> GetProductById(string productId, bool fromDB = false);+ Task<Product> GetProductById(string productId, bool fromDb = false);/// <summary>/// Gets product from product or product deleted@@ -52,6 +52,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Gets products by discount/// </summary>/// <param name="discountId">Product identifiers</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Products</returns>Task<IPagedList<Product>> GetProductsByDiscount(string discountId, int pageIndex = 0, int pageSize = int.MaxValue);@@ -77,12 +79,14 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Set product as unpublished/// </summary>/// <param name="product"></param>- Task UnpublishProduct(Product product);+ Task UnPublishProduct(Product product);/// <summary>/// Updates the product field/// </summary>/// <param name="product">Product</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>Task UpdateProductField<T>(Product product,Expression<Func<Product, T>> expression, T value);@@ -91,6 +95,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Increment the product field/// </summary>/// <param name="product">Product</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>Task IncrementProductField<T>(Product product,Expression<Func<Product, T>> expression, T value);@@ -108,7 +114,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Search products/// </summary>- /// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param>/// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>@@ -120,6 +125,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <param name="warehouseId">Warehouse identifier; "" to load all records</param>/// <param name="productType">Product type; "" to load all records</param>/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>+ /// <param name="markedAsNewOnly">Marked as new</param>/// <param name="showOnHomePage">A value indicating whether loaded products show on homepage</param>/// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and collections). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>/// <param name="priceMin">Minimum price; null to load all records</param>@@ -176,7 +182,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Products</returns>- Task<IPagedList<Product>> GetProductsByProductAtributeId(string productAttributeId,+ Task<IPagedList<Product>> GetProductsByProductAttributeId(string productAttributeId,int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>@@ -279,15 +285,13 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products#region Recommmended products/// <summary>- /// Inserts a recommended product+ /// Insert a recommended product/// </summary>- /// <param name="recommendedProduct">Recommended product</param>Task InsertRecommendedProduct(string productId, string recommendedProductId);/// <summary>- /// Deletes a recommended product+ /// Delete a recommended product/// </summary>- /// <param name="recommendedProduct">Recommended identifier</param>Task DeleteRecommendedProduct(string productId, string recommendedProductId);#endregion@@ -377,6 +381,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// Updates a product picture/// </summary>/// <param name="productPicture">Product picture</param>+ /// <param name="productId">Product ident</param>Task UpdateProductPicture(ProductPicture productPicture, string productId);/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.csindex 0233d492e..ef64d89e5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Product tag service interface/// </summary>- public partial interface IProductTagService+ public interface IProductTagService{/// <summary>@@ -29,9 +29,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.ProductsTask<ProductTag> GetProductTagByName(string name);/// <summary>- /// Gets product tag by sename+ /// Gets product tag by se-name/// </summary>- /// <param name="sename">Product tag sename</param>+ /// <param name="sename">Product tag se-name</param>/// <returns>Product tag</returns>Task<ProductTag> GetProductTagBySeName(string sename);diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IRecentlyViewedProductsService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IRecentlyViewedProductsService.csindex 699bb4a50..0263d1b8e 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IRecentlyViewedProductsService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IRecentlyViewedProductsService.cs@@ -5,11 +5,12 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Recently viewed products service/// </summary>- public partial interface IRecentlyViewedProductsService+ public interface IRecentlyViewedProductsService{/// <summary>/// Gets a "recently viewed products" list/// </summary>+ /// <param name="customerId">Customer ident</param>/// <param name="number">Number of products to load</param>/// <returns>"recently viewed products" list</returns>Task<IList<Product>> GetRecentlyViewedProducts(string customerId, int number);@@ -17,6 +18,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Adds a product to a recently viewed products list/// </summary>+ /// <param name="customerId">Customer ident</param>/// <param name="productId">Product identifier</param>Task AddProductToRecentlyViewedList(string customerId, string productId);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.csindex 8c5dfbd53..8cd71684b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products/// <summary>/// Specification attribute service interface/// </summary>- public partial interface ISpecificationAttributeService+ public interface ISpecificationAttributeService{#region Specification attribute@@ -18,9 +18,9 @@ namespace Grand.Business.Core.Interfaces.Catalog.ProductsTask<SpecificationAttribute> GetSpecificationAttributeById(string specificationAttributeId);/// <summary>- /// Gets a specification attribute by sename+ /// Gets a specification attribute by se-name/// </summary>- /// <param name="sename">Sename</param>+ /// <param name="sename">Se-name</param>/// <returns>Specification attribute</returns>Task<SpecificationAttribute> GetSpecificationAttributeBySeName(string sename);diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.csindex ac7b03299..6a9d4b2da 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// <summary>/// Tax category service interface/// </summary>- public partial interface ITaxCategoryService+ public interface ITaxCategoryService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxProvider.csindex d8d62114b..3d51be814 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxProvider.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// <summary>/// Provides an interface for creating tax providers/// </summary>- public partial interface ITaxProvider : IProvider+ public interface ITaxProvider : IProvider{/// <summary>/// Gets tax ratediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.csindex fb55a348b..041572ebe 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// <summary>/// Tax service/// </summary>- public partial interface ITaxService+ public interface ITaxService{/// <summary>/// Load active tax provider@@ -38,7 +38,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// </summary>/// <param name="product">Product</param>/// <param name="price">Price</param>- /// <param name="taxRate">Tax rate</param>/// <returns>Price</returns>Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price);@@ -80,7 +79,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// <param name="product">Product</param>/// <param name="customer">Customer</param>/// <param name="unitPrice">Unit Price</param>- /// <param name="unitPricewithoutDisc">Unit price without discount</param>+ /// <param name="unitPriceWithoutDisc">Unit price without discount</param>/// <param name="quantity">Quantity</param>/// <param name="subTotal">Sub-Total</param>/// <param name="discountAmount">Discount amount</param>@@ -90,7 +89,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.TaxProduct product,Customer customer,double unitPrice,- double unitPricewithoutDisc,+ double unitPriceWithoutDisc,int quantity,double subTotal,double discountAmount,diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.csindex 2b73d726a..0a9d51dac 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs@@ -26,9 +26,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Tax/// </summary>/// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>/// <param name="vatNumber">VAT number</param>- /// <param name="name">Company name</param>- /// <param name="address">Address</param>- /// <param name="exception">Exception</param>/// <returns>VAT number status</returns>Task<(VatNumberStatus status, string name, string address, Exception exception)> DoVatCheck(string twoLetterIsoCode, string vatNumber);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.csindex 4b2194c8c..098bfa9bd 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs@@ -6,21 +6,21 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// <summary>/// Checkout attribute helper/// </summary>- public partial interface ICheckoutAttributeFormatter+ public interface ICheckoutAttributeFormatter{/// <summary>/// Formats attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>/// <returns>Attributes</returns>Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,Customer customer,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true,bool renderPrices = true,bool allowHyperlinks = true);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.csindex 0d20be2a0..7ee874c7b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// <summary>/// Checkout attribute parser interface/// </summary>- public partial interface ICheckoutAttributeParser+ public interface ICheckoutAttributeParser{/// <summary>/// Gets selected checkout attributes@@ -25,7 +25,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// <summary>/// Get checkout attribute values with checkout attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Checkout attribute values with checkout attribute </returns>Task<IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>> ParseCheckoutAttributeValue(IList<CustomAttribute> customAttributes);@@ -50,14 +50,14 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified/// </summary>/// <param name="attribute">Checkout attribute</param>- /// <param name="selectedAttributes">Selected attributes</param>+ /// <param name="customAttributes">Selected attributes</param>/// <returns>Result</returns>Task<bool?> IsConditionMet(CheckoutAttribute attribute, IList<CustomAttribute> customAttributes);/// <summary>/// Remove an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="attribute">Checkout attribute</param>/// <returns>Updated result</returns>IList<CustomAttribute> RemoveCheckoutAttribute(IList<CustomAttribute> customAttributes, CheckoutAttribute attribute);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.csindex 159146164..732c52a5b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// <summary>/// Checkout attribute service/// </summary>- public partial interface ICheckoutAttributeService+ public interface ICheckoutAttributeService{#region Checkout attributes@@ -13,9 +13,10 @@ namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes/// Gets all checkout attributes/// </summary>/// <param name="storeId">Store identifier</param>- /// <param name="excludeShippableAttributes">A value indicating whether we should exlude shippable attributes</param>+ /// <param name="excludeShippableAttributes">A value indicating whether we should exclude shippable attributes</param>+ /// <param name="ignoreAcl"></param>/// <returns>Checkout attributes</returns>- Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "", bool excludeShippableAttributes = false, bool ignorAcl = false);+ Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "", bool excludeShippableAttributes = false, bool ignoreAcl = false);/// <summary>/// Gets a checkout attributediff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.csindex 148bfe20d..c74842df6 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.GiftVouchers/// <summary>/// Gift voucher service interface/// </summary>- public partial interface IGiftVoucherService+ public interface IGiftVoucherService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.csindex 4c2aab69e..6ccd9db9f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// LoyaltyPoints service interface/// </summary>- public partial interface ILoyaltyPointsService+ public interface ILoyaltyPointsService{/// <summary>@@ -19,11 +19,11 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Add loyalty points history record/// </summary>- /// <param name="customer">Customer</param>+ /// <param name="customerId">Customer ident</param>/// <param name="points">Number of points to add</param>/// <param name="storeId">Store identifier</param>/// <param name="message">Message</param>- /// <param name="usedWithOrder">the order for which points were redeemed as a payment</param>+ /// <param name="usedWithOrderId">the order for which points were redeemed as a payment</param>/// <param name="usedAmount">Used amount</param>Task<LoyaltyPointsHistory> AddLoyaltyPointsHistory(string customerId, int points, string storeId, string message = "",string usedWithOrderId = "", double usedAmount = 0);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.csindex eea57ba8e..5ecc6c8fe 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Merchandise return service interface/// </summary>- public partial interface IMerchandiseReturnService+ public interface IMerchandiseReturnService{/// <summary>@@ -89,31 +89,31 @@ namespace Grand.Business.Core.Interfaces.Checkout.OrdersTask UpdateMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction);/// <summary>- /// Gets all merchandise return reaspns+ /// Gets all merchandise return reasons/// </summary>- /// <returns>Merchandise return reaspns</returns>+ /// <returns>Merchandise return reasons</returns>Task<IList<MerchandiseReturnReason>> GetAllMerchandiseReturnReasons();/// <summary>- /// Gets a merchandise return reaspn+ /// Gets a merchandise return reasons/// </summary>/// <param name="merchandiseReturnReasonId">Merchandise return reason identifier</param>- /// <returns>Merchandise return reaspn</returns>+ /// <returns>Merchandise return reasons</returns>Task<MerchandiseReturnReason> GetMerchandiseReturnReasonById(string merchandiseReturnReasonId);/// <summary>- /// Inserts a merchandise return reaspn+ /// Inserts a merchandise return reasons/// </summary>/// <param name="merchandiseReturnReason">Merchandise return reason</param>Task InsertMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason);/// <summary>- /// Updates the merchandise return reaspn+ /// Updates the merchandise return reasons/// </summary>/// <param name="merchandiseReturnReason">Merchandise return reason</param>Task UpdateMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason);/// <summary>- /// Delete a merchandise return reaspn+ /// Delete a merchandise return reasons/// </summary>/// <param name="merchandiseReturnReason">Merchandise return reason</param>Task DeleteMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderCalculationService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderCalculationService.csindex 5add013a2..9bcfa4275 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderCalculationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderCalculationService.cs@@ -7,18 +7,13 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Order service interface/// </summary>- public partial interface IOrderCalculationService+ public interface IOrderCalculationService{/// <summary>/// Gets shopping cart subtotal/// </summary>/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>- /// <param name="discountAmount">Applied discount amount</param>- /// <param name="appliedDiscount">Applied discount</param>- /// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>- /// <param name="subTotalWithDiscount">Sub total (with discount)</param>- /// <param name="taxRates">Tax rates (of order sub total)</param>Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts, double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>GetShoppingCartSubTotal(IList<ShoppingCartItem> cart,bool includingTax);@@ -28,7 +23,6 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// </summary>/// <param name="shippingRate">Shipping rate to adjust</param>/// <param name="cart">Cart</param>- /// <param name="appliedDiscount">Applied discount</param>/// <returns>Adjusted shipping rate</returns>Task<(double shippingRate, List<ApplyDiscount> appliedDiscounts)> AdjustShippingRate(double shippingRate, IList<ShoppingCartItem> cart);@@ -58,8 +52,6 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// </summary>/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>- /// <param name="taxRate">Applied tax rate</param>- /// <param name="appliedDiscount">Applied discount</param>/// <returns>Shipping total</returns>Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)> GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax);@@ -68,7 +60,6 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// Gets tax/// </summary>/// <param name="cart">Shopping cart</param>- /// <param name="taxRates">Tax rates</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param>/// <returns>Tax total</returns>Task<(double taxtotal, SortedDictionary<double, double> taxRates)> GetTaxTotal(IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true);@@ -77,11 +68,6 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// Gets shopping cart total/// </summary>/// <param name="cart">Cart</param>- /// <param name="appliedGiftVouchers">Applied gift vouchers</param>- /// <param name="discountAmount">Applied discount amount</param>- /// <param name="appliedDiscount">Applied discount</param>- /// <param name="redeemedLoyaltyPoints">Loyalty points to redeem</param>- /// <param name="redeemedLoyaltyPointsAmount">Loyalty points amount in primary store currency to redeem</param>/// <param name="useLoyaltyPoints">A value indicating loyalty points should be used; null to detect current choice of the customer</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param>/// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.csindex bd970dd57..f289944c6 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Order service interface/// </summary>- public partial interface IOrderService+ public interface IOrderService{#region Orders@@ -65,7 +65,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <param name="warehouseId">Warehouse identifier, only orders with products from a specified warehouse will be loaded; 0 to load all orders</param>/// <param name="billingCountryId">Billing country identifier; 0 to load all orders</param>/// <param name="ownerId">Owner identifier</param>- /// <param name="salesemployeeId">Sales employee identifier</param>+ /// <param name="salesEmployeeId">Sales ident</param>/// <param name="paymentMethodSystemName">Payment method system name; null to load all records</param>/// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>@@ -73,6 +73,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <param name="ps">Order payment status; null to load all orders</param>/// <param name="ss">Order shipment status; null to load all orders</param>/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>+ /// <param name="billingLastName"></param>/// <param name="orderGuid">Search by order GUID (Global unique identifier) or part of GUID. Leave empty to load all records.</param>/// <param name="orderCode">Search by order code.</param>/// <param name="pageIndex">Page index</param>@@ -135,25 +136,25 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>- /// Get ordernotes for order+ /// Get order notes for order/// </summary>/// <param name="orderId">Order identifier</param>/// <returns>OrderNote</returns>Task<IList<OrderNote>> GetOrderNotes(string orderId);/// <summary>- /// Get ordernote by id+ /// Get order note by id/// </summary>- /// <param name="ordernoteId">Order note identifier</param>+ /// <param name="orderNoteId">Order note identifier</param>/// <returns>OrderNote</returns>- Task<OrderNote> GetOrderNote(string ordernoteId);+ Task<OrderNote> GetOrderNote(string orderNoteId);/// <summary>/// Cancel Expired UnPaid Orders/// </summary>- /// <param name="expirationDateUTC">Date at which all unPaid orders and has pending status Would be Canceled</param>- Task CancelExpiredOrders(DateTime expirationDateUTC);+ /// <param name="expirationDateUtc">Date at which all unPaid orders and has pending status Would be Canceled</param>+ Task CancelExpiredOrders(DateTime expirationDateUtc);#endregiondiff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.csindex 574b1ff49..3bd1e54a4 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Order's tag service interface/// </summary>- public partial interface IOrderTagService+ public interface IOrderTagService{/// <summary>@@ -44,16 +44,19 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// </summary>/// <param name="orderTag">Order's tag</param>Task DeleteOrderTag(OrderTag orderTag);+/// <summary>/// Assign a tag to the order/// </summary>- /// <param name="orderTag">order Tag</param>+ /// <param name="orderTagId">order Tag</param>+ /// <param name="orderId"></param>Task AttachOrderTag(string orderTagId, string orderId);/// <summary>/// Detach a tag from the order/// </summary>- /// <param name="orderTag">order Tag</param>+ /// <param name="orderTagId">order Tag</param>+ /// <param name="orderId"></param>Task DetachOrderTag(string orderTagId, string orderId);/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.csindex 9ef5117c0..d4fb9bdea 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Shopping cart service/// </summary>- public partial interface IShoppingCartService+ public interface IShoppingCartService{/// <summary>@@ -24,7 +24,8 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// </summary>/// <param name="shoppingCart">Shopping cart</param>/// <param name="shoppingCartType">Shopping cart type</param>- /// <param name="product">Product</param>+ /// <param name="productId">Product ident</param>+ /// <param name="warehouseId">Warehouse ident</param>/// <param name="attributes">Attributes</param>/// <param name="customerEnteredPrice">Price entered by a customer</param>/// <param name="rentalStartDate">Rental start date</param>@@ -71,12 +72,15 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// </summary>/// <param name="customer">Customer</param>/// <param name="shoppingCartItemId">Shopping cart item identifier</param>+ /// <param name="warehouseId">Warehouse ident</param>/// <param name="attributes">Attributes</param>/// <param name="customerEnteredPrice">New customer entered price</param>/// <param name="rentalStartDate">Rental start date</param>/// <param name="rentalEndDate">Rental end date</param>/// <param name="quantity">New shopping cart item quantity</param>/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>+ /// <param name="reservationId">Reservation ident</param>+ /// <param name="sciId"></param>/// <returns>Warnings</returns>Task<IList<string>> UpdateShoppingCartItem(Customer customer,string shoppingCartItemId, string warehouseId, IList<CustomAttribute> attributes,@@ -87,6 +91,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// <summary>/// Delete shopping cart item/// </summary>+ /// <param name="customer">Customer</param>/// <param name="shoppingCartItem">Shopping cart item</param>/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>/// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.csindex c7fb2687c..e62552c74 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs@@ -73,7 +73,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// Validates shopping cart item for reservation products/// </summary>/// <param name="customer">Customer</param>- /// <param name="Product">product</param>+ /// <param name="product">product</param>/// <param name="shoppingCartItem">ShoppingCartItem</param>/// <returns>Warnings</returns>Task<IList<string>> GetReservationProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem);@@ -106,7 +106,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders/// Validates required products (products which require some other products to be added to the cart)/// </summary>/// <param name="customer">Customer</param>- /// <param name="shoppingCartType">Shopping cart type</param>+ /// <param name="shoppingCartItem">Shopping cart type</param>/// <param name="product">Product</param>/// <param name="storeId">Store identifier</param>/// <returns>Warnings</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.csindex 9edfe511a..1d0a358ef 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Provides an interface for creating payment gateways & methods/// </summary>- public partial interface IPaymentProvider : IProvider+ public interface IPaymentProvider : IProvider{#region Methods@@ -42,14 +42,14 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Returns a value indicating whether payment method should be hidden during checkout/// </summary>- /// <param name="cart">Shoping cart</param>+ /// <param name="cart">Shopping cart</param>/// <returns>true - hide; false - display.</returns>Task<bool> HidePaymentMethod(IList<ShoppingCartItem> cart);/// <summary>/// Gets additional handling fee/// </summary>- /// <param name="cart">Shoping cart</param>+ /// <param name="cart">Shopping cart</param>/// <returns>Additional handling fee</returns>Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart);@@ -83,7 +83,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)/// </summary>- /// <param name="PaymentTransaction">PaymentTransaction</param>+ /// <param name="paymentTransaction">PaymentTransaction</param>/// <returns>Result</returns>Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.csindex 2c31af918..6aae81030 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Payment service interface/// </summary>- public partial interface IPaymentService+ public interface IPaymentService{/// <summary>/// Load active payment methods@@ -37,7 +37,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.PaymentsIList<IPaymentProvider> LoadAllPaymentMethods(Customer customer = null, string storeId = "", string filterByCountryId = "");/// <summary>- /// Gets a list of coutnry identifiers in which a certain payment method is now allowed+ /// Gets a list of country identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <returns>A list of country identifiers</returns>@@ -55,14 +55,14 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="countryIds">A list of country identifiers</param>- Task SaveRestictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds);+ Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds);/// <summary>/// Saves a list of shipping identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="shippingIds">A list of shipping identifiers</param>- Task SaveRestictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds);+ Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds);/// <summary>/// Process a payment@@ -93,7 +93,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Gets an additional handling fee of a payment method/// </summary>- /// <param name="cart">Shoping cart</param>+ /// <param name="cart">Shopping cart</param>/// <param name="paymentMethodSystemName">Payment method system name</param>/// <returns>Additional handling fee</returns>Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart, string paymentMethodSystemName);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.csindex 05295dcbd..fddaee4e3 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs@@ -40,9 +40,9 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Gets an payment transactions for order guid/// </summary>- /// <param name="orderguid">The order guid</param>+ /// <param name="orderGuid">The order guid</param>/// <returns>PaymentTransaction</returns>- Task<PaymentTransaction> GetByOrdeGuid(Guid orderguid);+ Task<PaymentTransaction> GetOrderByGuid(Guid orderGuid);/// <summary>/// Get an payment transactions by authorization transaction ID and payment method system name@@ -55,7 +55,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <summary>/// Search payment transactions/// </summary>- /// <param name="orderguid">Order ident by guid</param>+ /// <param name="orderGuid">Order ident by guid</param>/// <param name="storeId">Store ident</param>/// <param name="customerEmail">Customer email</param>/// <param name="ts">Transaction status</param>@@ -65,7 +65,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Payments/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>/// <returns>Page list payment transaction</returns>Task<IPagedList<PaymentTransaction>> SearchPaymentTransactions(- Guid? orderguid = null,+ Guid? orderGuid = null,string storeId = "",string customerEmail = "",TransactionStatus? ts = null,diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.csindex df2348b75..d71861bed 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs@@ -27,19 +27,19 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Inserts a pickupPoint/// </summary>- /// <param name="PickupPoint">PickupPoint</param>- Task InsertPickupPoint(PickupPoint pickuppoint);+ /// <param name="pickupPoint">PickupPoint</param>+ Task InsertPickupPoint(PickupPoint pickupPoint);/// <summary>/// Updates the pickupPoint/// </summary>/// <param name="pickupPoint">PickupPoint</param>- Task UpdatePickupPoint(PickupPoint pickuppoint);+ Task UpdatePickupPoint(PickupPoint pickupPoint);/// <summary>/// Deletes a pickupPoint/// </summary>/// <param name="pickupPoint">The pickupPoint</param>- Task DeletePickupPoint(PickupPoint pickuppoint);+ Task DeletePickupPoint(PickupPoint pickupPoint);}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.csindex dfacfea9d..73b37cdfc 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Shipment service interface/// </summary>- public partial interface IShipmentService+ public interface IShipmentService{/// <summary>/// Search shipments@@ -83,18 +83,18 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>- /// Get shipmentnotes for shipment+ /// Get shipment notes for shipment/// </summary>/// <param name="shipmentId">Shipment identifier</param>/// <returns>ShipmentNote</returns>Task<IList<ShipmentNote>> GetShipmentNotes(string shipmentId);/// <summary>- /// Get shipmentnote by id+ /// Get shipment note by id/// </summary>- /// <param name="shipmentnoteId">Shipment note identifier</param>+ /// <param name="shipmentNoteId">Shipment note identifier</param>/// <returns>ShipmentNote</returns>- Task<ShipmentNote> GetShipmentNote(string shipmentnoteId);+ Task<ShipmentNote> GetShipmentNote(string shipmentNoteId);#endregiondiff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentTracker.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentTracker.csindex 672a428ca..480c48401 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentTracker.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentTracker.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Shipment tracker/// </summary>- public partial interface IShipmentTracker+ public interface IShipmentTracker{/// <summary>/// Gets a url for a page to show tracking info (third party tracking page).diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.csindex 838dd8bc2..f3e033a7f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs@@ -16,7 +16,8 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Gets all shipping methods/// </summary>- /// <param name="filterByCountryId">The country indentifier to filter by</param>+ /// <param name="filterByCountryId">The country identifier to filter by</param>+ /// <param name="customer"></param>/// <returns>Shipping methods</returns>Task<IList<ShippingMethod>> GetAllShippingMethods(string filterByCountryId = "", Customer customer = null);diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingRateCalculationProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingRateCalculationProvider.csindex 7b11b0b7f..ecaa8ebcc 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingRateCalculationProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingRateCalculationProvider.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Provides an interface of Shipping rate method/// </summary>- public partial interface IShippingRateCalculationProvider : IProvider+ public interface IShippingRateCalculationProvider : IProvider{/// <summary>/// Gets a Shipping rate method type@@ -26,7 +26,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Returns a value indicating whether shipping methods should be hidden during checkout/// </summary>- /// <param name="cart">Shoping cart</param>+ /// <param name="cart">Shopping cart</param>/// <returns>true - hide; false - display.</returns>Task<bool> HideShipmentMethods(IList<ShoppingCartItem> cart);@@ -48,7 +48,6 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Gets a route name for displaying plugin ("shipping" checkout step)/// </summary>- /// <param name="viewComponentName">View component name</param>Task<string> GetControllerRouteName();}diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.csindex 36b93fe6e..ff0fd6f64 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs@@ -9,13 +9,14 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Shipping service interface/// </summary>- public partial interface IShippingService+ public interface IShippingService{/// <summary>/// Load active Shipping rate providers/// </summary>/// <param name="customer">Customer</param>/// <param name="storeId">Store ident</param>+ /// <param name="cart">Cart</param>/// <returns>Shipping rate methods</returns>Task<IList<IShippingRateCalculationProvider>> LoadActiveShippingRateCalculationProviders(Customer customer = null, string storeId = "", IList<ShoppingCartItem> cart = null);@@ -48,10 +49,11 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping/// <summary>/// Gets available shipping options/// </summary>+ /// <param name="customer"></param>/// <param name="cart">Shopping cart</param>/// <param name="shippingAddress">Shipping address</param>/// <param name="allowedShippingRateMethodSystemName">Filter by Shipping rate method identifier; null to load shipping options of all Shipping rate methods</param>- /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>+ /// <param name="store">Load records allowed only in a specified store; pass "" to load all records</param>/// <returns>Shipping options</returns>Task<GetShippingOptionResponse> GetShippingOptions(Customer customer, IList<ShoppingCartItem> cart, Address shippingAddress,string allowedShippingRateMethodSystemName = "", Store store = null);diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.csindex 6dcb249c0..14755cddf 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// Blog service interface/// </summary>- public partial interface IBlogService+ public interface IBlogService{/// <summary>@@ -25,6 +25,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <param name="showHidden">A value indicating whether to show hidden records</param>+ /// <param name="tag">Tag</param>/// <param name="blogPostName">Blog post name</param>/// <param name="categoryId">Category id</param>/// <returns>Blog posts</returns>@@ -85,19 +86,12 @@ namespace Grand.Business.Core.Interfaces.Cms/// <returns>Blog comment</returns>Task<BlogComment> GetBlogCommentById(string blogCommentId);- /// <summary>- /// Get blog comments by identifiers- /// </summary>- /// <param name="commentIds">Blog comment identifiers</param>- /// <returns>Blog comments</returns>- Task<IList<BlogComment>> GetBlogCommentsByIds(string[] commentIds);-Task<IList<BlogComment>> GetBlogCommentsByBlogPostId(string blogPostId);/// <summary>/// Inserts a blog post comment/// </summary>- /// <param name="blogPost">Blog post comment</param>+ /// <param name="blogComment">Blog post comment</param>Task InsertBlogComment(BlogComment blogComment);Task DeleteBlogComment(BlogComment blogComment);@@ -117,9 +111,9 @@ namespace Grand.Business.Core.Interfaces.CmsTask<IList<BlogCategory>> GetBlogCategoryByPostId(string blogPostId);/// <summary>- /// Get category by sename+ /// Get category by se name/// </summary>- /// <param name="blogCategorySeName">Blog category sename</param>+ /// <param name="blogCategorySeName">Blog category se name</param>/// <returns></returns>Task<BlogCategory> GetBlogCategoryBySeName(string blogCategorySeName);diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.csindex 7a17f99d9..4d65ce08f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs@@ -6,137 +6,137 @@ namespace Grand.Business.Core.Interfaces.Cmspublic interface IKnowledgebaseService{/// <summary>- /// Gets knowledgebase category+ /// Gets knowledge base category/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase category</returns>+ /// <returns>knowledge base category</returns>Task<KnowledgebaseCategory> GetKnowledgebaseCategory(string id);/// <summary>- /// Gets public knowledgebase category+ /// Gets public knowledge base category/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase category</returns>+ /// <returns>knowledge base category</returns>Task<KnowledgebaseCategory> GetPublicKnowledgebaseCategory(string id);/// <summary>- /// Gets knowledgebase categories+ /// Gets knowledge base categories/// </summary>- /// <returns>List of knowledgebase categories</returns>+ /// <returns>List of knowledge base categories</returns>Task<List<KnowledgebaseCategory>> GetKnowledgebaseCategories();/// <summary>- /// Gets public(published etc) knowledgebase categories+ /// Gets public(published etc) knowledge base categories/// </summary>- /// <returns>List of public knowledgebase categories</returns>+ /// <returns>List of public knowledge base categories</returns>Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategories();/// <summary>- /// Inserts knowledgebase category+ /// Inserts knowledge base category/// </summary>/// <param name="kc"></param>Task InsertKnowledgebaseCategory(KnowledgebaseCategory kc);/// <summary>- /// Updates knowledgebase category+ /// Updates knowledge base category/// </summary>/// <param name="kc"></param>Task UpdateKnowledgebaseCategory(KnowledgebaseCategory kc);/// <summary>- /// Deletes knowledgebase category+ /// Deletes knowledge base category/// </summary>/// <param name="kc"></param>Task DeleteKnowledgebaseCategory(KnowledgebaseCategory kc);/// <summary>- /// Gets knowledgebase article+ /// Gets knowledge base article/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase article</returns>+ /// <returns>knowledge base article</returns>Task<KnowledgebaseArticle> GetKnowledgebaseArticle(string id);/// <summary>- /// Gets public knowledgebase article+ /// Gets public knowledge base article/// </summary>/// <param name="id"></param>- /// <returns>knowledgebase article</returns>+ /// <returns>knowledge base article</returns>Task<KnowledgebaseArticle> GetPublicKnowledgebaseArticle(string id);/// <summary>- /// Gets knowledgebase articles+ /// Gets knowledge base articles/// </summary>- /// <returns>List of knowledgebase articles</returns>+ /// <returns>List of knowledge base articles</returns>/// <param name="storeId">Store ident</param>Task<List<KnowledgebaseArticle>> GetKnowledgebaseArticles(string storeId = "");/// <summary>- /// Gets public(published etc) knowledgebase articles+ /// Gets public(published etc) knowledge base articles/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles();/// <summary>- /// Gets homepage knowledgebase articles+ /// Gets homepage knowledge base articles/// </summary>- /// <returns>List of homepage knowledgebase articles</returns>+ /// <returns>List of homepage knowledge base articles</returns>Task<List<KnowledgebaseArticle>> GetHomepageKnowledgebaseArticles();/// <summary>- /// Gets public(published etc) knowledgebase articles for category id+ /// Gets public(published etc) knowledge base articles for category id/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByCategory(string categoryId);/// <summary>- /// Gets public(published etc) knowledgebase articles for keyword+ /// Gets public(published etc) knowledge base articles for keyword/// </summary>- /// <returns>List of public knowledgebase articles</returns>+ /// <returns>List of public knowledge base articles</returns>Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByKeyword(string keyword);/// <summary>- /// Gets public(published etc) knowledgebase categories for keyword+ /// Gets public(published etc) knowledge base categories for keyword/// </summary>- /// <returns>List of public knowledgebase categories</returns>+ /// <returns>List of public knowledge base categories</returns>Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategoriesByKeyword(string keyword);/// <summary>- /// Inserts knowledgebase article+ /// Inserts knowledge base article/// </summary>/// <param name="ka"></param>Task InsertKnowledgebaseArticle(KnowledgebaseArticle ka);/// <summary>- /// Updates knowledgebase article+ /// Updates knowledge base article/// </summary>/// <param name="ka"></param>Task UpdateKnowledgebaseArticle(KnowledgebaseArticle ka);/// <summary>- /// Deletes knowledgebase article+ /// Deletes knowledge base article/// </summary>/// <param name="ka"></param>Task DeleteKnowledgebaseArticle(KnowledgebaseArticle ka);/// <summary>- /// Gets knowledgebase articles by category id+ /// Gets knowledge base articles by category id/// </summary>/// <param name="id"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>Task<IPagedList<KnowledgebaseArticle>> GetKnowledgebaseArticlesByCategoryId(string id, int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>- /// Gets knowledgebase articles by name+ /// Gets knowledge base articles by name/// </summary>/// <param name="name"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>Task<IPagedList<KnowledgebaseArticle>> GetKnowledgebaseArticlesByName(string name, int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>- /// Gets related knowledgebase articles+ /// Gets related knowledge base articles/// </summary>- /// <param name="name"></param>- /// <returns>IPagedList<KnowledgebaseArticle></returns>Task<IPagedList<KnowledgebaseArticle>> GetRelatedKnowledgebaseArticles(string articleId, int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>@@ -145,26 +145,6 @@ namespace Grand.Business.Core.Interfaces.Cms/// <param name="articleComment">Article comment</param>Task InsertArticleComment(KnowledgebaseArticleComment articleComment);- /// <summary>- /// Gets all comments- /// </summary>- /// <param name="customerId">Customer identifier; "" to load all records</param>- /// <returns>Comments</returns>- Task<IList<KnowledgebaseArticleComment>> GetAllComments(string customerId);-- /// <summary>- /// Gets an article comment- /// </summary>- /// <param name="articleId">Article identifier</param>- /// <returns>Article comment</returns>- Task<KnowledgebaseArticleComment> GetArticleCommentById(string articleId);-- /// <summary>- /// Get article comments by identifiers- /// </summary>- /// <param name="commentIds"Article comment identifiers</param>- /// <returns>Article comments</returns>- Task<IList<KnowledgebaseArticleComment>> GetArticleCommentsByIds(string[] commentIds);Task<IList<KnowledgebaseArticleComment>> GetArticleCommentsByArticleId(string articleId);Task DeleteArticleComment(KnowledgebaseArticleComment articleComment);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.csindex 8194a9680..e84f87dd2 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// News service interface/// </summary>- public partial interface INewsService+ public interface INewsService{/// <summary>/// Gets a news@@ -21,11 +21,12 @@ namespace Grand.Business.Core.Interfaces.Cms/// <param name="storeId">Store identifier; 0 if you want to get all records</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>+ /// <param name="ignoreAcl"></param>/// <param name="showHidden">A value indicating whether to show hidden records</param>/// <param name="newsTitle">News title</param>/// <returns>News items</returns>Task<IPagedList<NewsItem>> GetAllNews(string storeId = "",- int pageIndex = 0, int pageSize = int.MaxValue, bool ignorAcl = false, bool showHidden = false, string newsTitle = "");+ int pageIndex = 0, int pageSize = int.MaxValue, bool ignoreAcl = false, bool showHidden = false, string newsTitle = "");/// <summary>/// Inserts a news itemdiff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.csindex 946d0e1f6..f855f297f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// Page layout service interface/// </summary>- public partial interface IPageLayoutService+ public interface IPageLayoutService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.csindex 1db28a7c7..a4fe9f526 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// Page service interface/// </summary>- public partial interface IPageService+ public interface IPageService{/// <summary>@@ -27,8 +27,9 @@ namespace Grand.Business.Core.Interfaces.Cms/// Gets all pages/// </summary>/// <param name="storeId">Store identifier; pass "" to load all records</param>+ /// <param name="ignoreAcl"></param>/// <returns>Pages</returns>- Task<IList<Page>> GetAllPages(string storeId, bool ignorAcl = false);+ Task<IList<Page>> GetAllPages(string storeId, bool ignoreAcl = false);/// <summary>/// Inserts a pagediff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.csindex 64ec1c5f1..311f41561 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Cms{- public partial interface IRobotsTxtService+ public interface IRobotsTxtService{/// <summary>/// Get a robots txtdiff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetProvider.csindex 34efea5a6..0378567f8 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetProvider.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// Provides an interface for creating widgets/// </summary>- public partial interface IWidgetProvider : IProvider+ public interface IWidgetProvider : IProvider{/// <summary>/// Gets widget zones where this widget for rendereddiff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.csindex 8f8339a5a..f0de8664b 100644--- a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Cms/// <summary>/// Widget service interface/// </summary>- public partial interface IWidgetService+ public interface IWidgetService{/// <summary>/// Load active widgetsdiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.csindex b75b7b791..0378aabf2 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs@@ -6,26 +6,26 @@ namespace Grand.Business.Core.Interfaces.Common.Addresses/// <summary>/// Address attribute parser interface/// </summary>- public partial interface IAddressAttributeParser+ public interface IAddressAttributeParser{/// <summary>/// Gets selected address attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Selected address attributes</returns>Task<IList<AddressAttribute>> ParseAddressAttributes(IList<CustomAttribute> customAttributes);/// <summary>/// Get address attribute values/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Address attribute values</returns>Task<IList<AddressAttributeValue>> ParseAddressAttributeValues(IList<CustomAttribute> customAttributes);/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="attribute">Address attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>@@ -34,7 +34,7 @@ namespace Grand.Business.Core.Interfaces.Common.Addresses/// <summary>/// Validates address attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Warnings</returns>Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes);@@ -43,13 +43,13 @@ namespace Grand.Business.Core.Interfaces.Common.Addresses/// </summary>/// <param name="language">Language</param>/// <param name="customAttributes">Attributes</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <returns>Attributes</returns>Task<string> FormatAttributes(Language language,IList<CustomAttribute> customAttributes,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true);}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.csindex c31a35776..59c79f94d 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Addresses/// <summary>/// Address attribute service/// </summary>- public partial interface IAddressAttributeService+ public interface IAddressAttributeService{/// <summary>/// Gets all address attributes@@ -39,13 +39,13 @@ namespace Grand.Business.Core.Interfaces.Common.AddressesTask DeleteAddressAttribute(AddressAttribute addressAttribute);/// <summary>- /// Inserts a ddress attribute value+ /// Inserts a address attribute value/// </summary>/// <param name="addressAttributeValue">Address attribute value</param>Task InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue);/// <summary>- /// Updates the ddress attribute value+ /// Updates the address attribute value/// </summary>/// <param name="addressAttributeValue">Address attribute value</param>Task UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue);diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.csindex 1db94344f..a23fb1a31 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Configuration/// <summary>/// Setting service interface/// </summary>- public partial interface ISettingService+ public interface ISettingService{/// <summary>@@ -66,7 +66,7 @@ namespace Grand.Business.Core.Interfaces.Common.Configuration/// Load settings/// </summary>/// <typeparam name="T">Type</typeparam>- /// <param name="storeId">Store identifier for which settigns should be loaded</param>+ /// <param name="storeId">Store identifier for which settings should be loaded</param>T LoadSetting<T>(string storeId = "") where T : ISettings, new();/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.csindex 8696b48e1..55ece3ff4 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// Country service interface/// </summary>- public partial interface ICountryService+ public interface ICountryService{/// <summary>/// Gets all countriesdiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.csindex 1be515973..2161d8f53 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// Currency service/// </summary>- public partial interface ICurrencyService+ public interface ICurrencyService{/// <summary>/// Gets a currencydiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IDateTimeService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IDateTimeService.csindex eafefe5d1..dbc2f2170 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IDateTimeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IDateTimeService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// Represents a datetime service/// </summary>- public partial interface IDateTimeService+ public interface IDateTimeService{/// <summary>/// Retrieves a System.TimeZoneInfo object from the registry based on its identifier.@@ -23,15 +23,15 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// Converts the date and time to current user date and time/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>DateTime ConvertToUserTime(DateTime dt);/// <summary>/// Converts the date and time to current user date and time/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>- /// <param name="sourceDateTimeKind">The source datetimekind</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>+ /// <param name="sourceDateTimeKind">The source datetime kind</param>/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>DateTime ConvertToUserTime(DateTime dt, DateTimeKind sourceDateTimeKind);@@ -47,15 +47,15 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// Converts the date and time to Coordinated Universal Time (UTC)/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>DateTime ConvertToUtcTime(DateTime dt);/// <summary>/// Converts the date and time to Coordinated Universal Time (UTC)/// </summary>- /// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>- /// <param name="sourceDateTimeKind">The source datetimekind</param>+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>+ /// <param name="sourceDateTimeKind">The source datetime kind</param>/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind);diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.csindex 117b522ef..2fd9e1ff7 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs@@ -34,7 +34,7 @@ namespace Grand.Business.Core.Interfaces.Common.DirectoryTask<bool> IsVendor(Customer customer);/// <summary>- /// Gets a value indicating whether customer is owner subaccount+ /// Gets a value indicating whether customer is owner sub-account/// </summary>/// <param name="customer">Customer</param>/// <returns>Result</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IHistoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IHistoryService.csindex a3790600a..3e5bc5d26 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IHistoryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IHistoryService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// History service interface/// </summary>- public partial interface IHistoryService+ public interface IHistoryService{Task SaveObject<T>(T entity) where T : BaseEntity;Task<IList<T>> GetHistoryForEntity<T>(BaseEntity entity) where T : BaseEntity;diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IUserFieldService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IUserFieldService.csindex 243cfd45a..bba6c5fc4 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IUserFieldService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IUserFieldService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Directory/// <summary>/// User fields service interface/// </summary>- public partial interface IUserFieldService+ public interface IUserFieldService{Task SaveField<TPropType>(BaseEntity entity, string key, TPropType value, string storeId = "");Task<TPropType> GetFieldsForEntity<TPropType>(BaseEntity entity, string key, string storeId = "");diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.csindex 43a2aaafd..ad5cdd315 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Localization/// <summary>/// Language service interface/// </summary>- public partial interface ILanguageService+ public interface ILanguageService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.csindex c4a6bcb77..1f8c4accf 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Localization/// <summary>/// Translation manager interface/// </summary>- public partial interface ITranslationService+ public interface ITranslationService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ICustomerActivityService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ICustomerActivityService.csindex 1a3c16903..4ecf0eec2 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ICustomerActivityService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ICustomerActivityService.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Common.Logging/// <summary>/// Customer activity service interface/// </summary>- public partial interface ICustomerActivityService+ public interface ICustomerActivityService{/// <summary>/// Inserts an activity log type item@@ -68,6 +68,7 @@ namespace Grand.Business.Core.Interfaces.Common.Logging/// <param name="createdOnTo">Log item creation to; null to load all customers</param>/// <param name="customerId">Customer identifier; null to load all customers</param>/// <param name="activityLogTypeId">Activity log type identifier</param>+ /// <param name="ipAddress"></param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>Activity log items</returns>@@ -102,7 +103,7 @@ namespace Grand.Business.Core.Interfaces.Common.LoggingDateTime? createdOnTo = null, string categoryId = "", int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>- /// Gets knowledgebase category activity log items+ /// Gets knowledge base category activity log items/// </summary>/// <param name="createdOnFrom">Log item creation from; null to load all records</param>/// <param name="createdOnTo">Log item creation to; null to load all records</param>@@ -114,7 +115,7 @@ namespace Grand.Business.Core.Interfaces.Common.LoggingDateTime? createdOnTo = null, string categoryId = "", int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>- /// Gets knowledgebase article activity log items+ /// Gets knowledge base article activity log items/// </summary>/// <param name="createdOnFrom">Log item creation from; null to load all records</param>/// <param name="createdOnTo">Log item creation to; null to load all records</param>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.csindex 2490f8a85..1b63a7339 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Common.Logging/// <summary>/// Logger interface/// </summary>- public partial interface ILogger+ public interface ILogger{/// <summary>/// Gets all log items@@ -45,12 +45,12 @@ namespace Grand.Business.Core.Interfaces.Common.Logging/// <param name="fullMessage">The full message</param>/// <param name="customer">The customer to associate log record with</param>/// <param name="ipAddress">Ip address</param>- /// <param name="pageurl">Page url</param>+ /// <param name="pageUrl">Page url</param>/// <param name="referrerUrl">Referrer url</param>/// <returns>A log item</returns>Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null,string ipAddress = default,- string pageurl = default,+ string pageUrl = default,string referrerUrl = default);/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.csindex 01d255207..e22e6a04a 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Common.Pdf/// <summary>/// Customer service interface/// </summary>- public partial interface IPdfService+ public interface IPdfService{/// <summary>/// Print an order to PDFdiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IViewRenderService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IViewRenderService.csindex 5570b3f79..afd17ea16 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IViewRenderService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IViewRenderService.cs@@ -1,7 +1,7 @@namespace Grand.Business.Core.Interfaces.Common.Pdf{/// <summary>- /// Allow render rezor view as string+ /// Allow render razor view as string/// </summary>public interface IViewRenderService{diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Providers/IExchangeRateProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Providers/IExchangeRateProvider.csindex 3e71b8948..53afd1cbb 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Providers/IExchangeRateProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Providers/IExchangeRateProvider.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Common.Providers/// <summary>/// Exchange rate provider interface/// </summary>- public partial interface IExchangeRateProvider : IProvider+ public interface IExchangeRateProvider : IProvider{/// <summary>/// Gets currency live ratesdiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.csindex 4449e2279..469fdad35 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs@@ -6,9 +6,9 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Interfaces.Common.Security{/// <summary>- /// ACL service inerface+ /// ACL service interface/// </summary>- public partial interface IAclService+ public interface IAclService{/// <summary>/// Authorize ACL permissiondiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.csindex 22527a9a6..c929fe83e 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs@@ -14,11 +14,11 @@ namespace Grand.Business.Core.Interfaces.Common.Security/// <summary>/// Create a password hash/// </summary>- /// <param name="password">{assword</param>- /// <param name="saltkey">Salk key</param>+ /// <param name="password">password</param>+ /// <param name="saltKey">Salk key</param>/// <param name="passwordFormat">Hashed Password format (hash algorithm)</param>/// <returns>Password hash</returns>- string CreatePasswordHash(string password, string saltkey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1);+ string CreatePasswordHash(string password, string saltKey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1);/// <summary>/// Encrypt textdiff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.csindex a72c096fb..dc6efe3c5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Common.Security/// <summary>/// Permission service interface/// </summary>- public partial interface IPermissionService+ public interface IPermissionService{/// <summary>@@ -65,14 +65,14 @@ namespace Grand.Business.Core.Interfaces.Common.Security/// <summary>/// Authorize permission/// </summary>- /// <param name="permissionRecordSystemName">Permission system name</param>+ /// <param name="permissionSystemName">Permission system name</param>/// <returns>true - authorized; otherwise, false</returns>Task<bool> Authorize(string permissionSystemName);/// <summary>/// Authorize permission/// </summary>- /// <param name="permissionRecordSystemName">Permission system name</param>+ /// <param name="permissionSystemName">Permission system name</param>/// <param name="customer">Customer</param>/// <returns>true - authorized; otherwise, false</returns>Task<bool> Authorize(string permissionSystemName, Customer customer);@@ -81,26 +81,26 @@ namespace Grand.Business.Core.Interfaces.Common.Security/// Gets a permission actions/// </summary>/// <param name="systemName">Permission system name</param>- /// <param name="customeroleId">Customer group ident</param>+ /// <param name="customerGroupId">Customer group ident</param>/// <returns>Permission action</returns>- Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customeroleId);+ Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customerGroupId);/// <summary>/// Inserts a permission action/// </summary>- /// <param name="permission">Permission</param>+ /// <param name="permissionAction">Permission</param>Task InsertPermissionAction(PermissionAction permissionAction);/// <summary>/// Inserts a permission action record/// </summary>- /// <param name="permission">Permission</param>+ /// <param name="permissionAction">Permission</param>Task DeletePermissionAction(PermissionAction permissionAction);/// <summary>/// Authorize permission for action/// </summary>- /// <param name="permissionRecordSystemName">Permission record system name</param>+ /// <param name="permissionSystemName">Permission record system name</param>/// <param name="permissionActionName">Permission action name</param>/// <returns>true - authorized; otherwise, false</returns>Task<bool> AuthorizeAction(string permissionSystemName, string permissionActionName);diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.csindex 513732533..1207aa7a9 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs@@ -6,20 +6,20 @@ namespace Grand.Business.Core.Interfaces.Common.Seo/// <summary>/// Provides information about URL Entity/// </summary>- public partial interface ISlugService+ public interface ISlugService{/// <summary>/// Gets an entity url/// </summary>- /// <param name="entityUrlId">URL entity identifier</param>+ /// <param name="urlEntityId">URL entity identifier</param>/// <returns>URL Entity</returns>Task<EntityUrl> GetEntityUrlById(string urlEntityId);/// <summary>/// Inserts an URL Entity/// </summary>- /// <param name="entityUrl">URL Entity</param>+ /// <param name="urlEntity">URL Entity</param>Task InsertEntityUrl(EntityUrl urlEntity);/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.csindex 525e8f906..a552cb4ac 100644--- a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Common.Stores/// <summary>/// Store service interface/// </summary>- public partial interface IStoreService+ public interface IStoreService{/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.csindex af173fc6b..fb0f9c1a8 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Affiliate service interface/// </summary>- public partial interface IAffiliateService+ public interface IAffiliateService{/// <summary>/// Gets an affiliate by identifierdiff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeParser.csindex 0b3693d01..c770c9dcc 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeParser.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeParser.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Customer attribute parser interface/// </summary>- public partial interface ICustomerAttributeParser+ public interface ICustomerAttributeParser{/// <summary>/// Gets selected customer attributes@@ -26,7 +26,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="ca">Customer attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>@@ -35,7 +35,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Validates customer attributes/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Warnings</returns>Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes);@@ -44,10 +44,10 @@ namespace Grand.Business.Core.Interfaces.Customers/// </summary>/// <param name="language">Language</param>/// <param name="customAttributes">Attributes</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <returns>Attributes</returns>- Task<string> FormatAttributes(Language language, IList<CustomAttribute> customAttributes, string serapator = "<br />", bool htmlEncode = true);+ Task<string> FormatAttributes(Language language, IList<CustomAttribute> customAttributes, string separator = "<br />", bool htmlEncode = true);}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.csindex e6bdbaf0b..e4f0845c8 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Customer attribute service/// </summary>- public partial interface ICustomerAttributeService+ public interface ICustomerAttributeService{/// <summary>/// Gets all customer attributesdiff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.csindex 17917a8a5..c17183c07 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Customer manager interface/// </summary>- public partial interface ICustomerManagerService+ public interface ICustomerManagerService{/// <summary>/// Login customerdiff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.csindex 989762fa2..dd428d2c5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Customers{#region Customer note- // <summary>+ /// <summary>/// Get note for customer/// </summary>/// <param name="id">Note identifier</param>@@ -29,9 +29,9 @@ namespace Grand.Business.Core.Interfaces.Customers/// Get notes for customer/// </summary>/// <param name="customerId">Customer identifier</param>- /// <param name="displaytocustomer">Display to customer</param>+ /// <param name="displayToCustomer">Display to customer</param>/// <returns>OrderNote</returns>- Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displaytocustomer = null);+ Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displayToCustomer = null);#endregion}diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.csindex 92cef172d..f95a6fb7f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Customer service interface/// </summary>- public partial interface ICustomerService+ public interface ICustomerService{#region Customers@@ -25,19 +25,19 @@ namespace Grand.Business.Core.Interfaces.Customers/// <param name="ownerId">Owner identifier</param>/// <param name="salesEmployeeId">Sales employee identifier</param>/// <param name="customerGroupIds">A list of customer group identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param>+ /// <param name="customerTagIds"></param>/// <param name="email">Email; null to load all customers</param>/// <param name="username">Username; null to load all customers</param>/// <param name="firstName">First name; null to load all customers</param>/// <param name="lastName">Last name; null to load all customers</param>- /// <param name="dayOfBirth">Day of birth; 0 to load all customers</param>- /// <param name="monthOfBirth">Month of birth; 0 to load all customers</param>/// <param name="company">Company; null to load all customers</param>/// <param name="phone">Phone; null to load all customers</param>/// <param name="zipPostalCode">Phone; null to load all customers</param>/// <param name="loadOnlyWithShoppingCart">Value indicating whether to load customers only with shopping cart</param>- /// <param name="sct">Value indicating what shopping cart type to filter; userd when 'loadOnlyWithShoppingCart' param is 'true'</param>+ /// <param name="sct">Value indicating what shopping cart type to filter; user when 'loadOnlyWithShoppingCart' param is 'true'</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>+ /// <param name="orderBySelector"></param>/// <returns>Customers</returns>Task<IPagedList<Customer>> GetAllCustomers(DateTime? createdFromUtc = null,DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "", string ownerId = "",@@ -141,6 +141,8 @@ namespace Grand.Business.Core.Interfaces.Customers/// Updates the customer field/// </summary>/// <param name="customer">Customer</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>Task UpdateCustomerField<T>(Customer customer,Expression<Func<Customer, T>> expression, T value);@@ -148,6 +150,8 @@ namespace Grand.Business.Core.Interfaces.Customers/// Updates the customer field/// </summary>/// <param name="customerId">Customer ident</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>Task UpdateCustomerField<T>(string customerId,Expression<Func<Customer, T>> expression, T value);@@ -173,7 +177,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// Updates the customer in admin panel/// </summary>/// <param name="customer">Customer</param>- Task UpdateCustomerinAdminPanel(Customer customer);+ Task UpdateCustomerInAdminPanel(Customer customer);/// <summary>/// Reset data required for checkoutdiff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.csindex ca163ab73..df304b084 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs@@ -32,7 +32,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Deletes a sales employee/// </summary>- /// <param name="warehouse">The sales employee</param>+ /// <param name="salesEmployee">The sales employee</param>Task DeleteSalesEmployee(SalesEmployee salesEmployee);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.csindex c06252754..a3bdb6580 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs@@ -3,7 +3,7 @@ using Grand.Domain.Customers;namespace Grand.Business.Core.Interfaces.Customers{- public partial interface IUserApiService+ public interface IUserApiService{/// <summary>/// Get user api by id@@ -14,7 +14,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Get user api by email/// </summary>- /// <param name="id">id</param>+ /// <param name="email">email</param>Task<UserApi> GetUserByEmail(string email);/// <summary>@@ -41,7 +41,6 @@ namespace Grand.Business.Core.Interfaces.Customers/// <param name="email"></param>/// <param name="pageIndex"></param>/// <param name="pageSize"></param>- /// <returns>PagedList<UserApi></returns>Task<IPagedList<UserApi>> GetUsers(string email = "", int pageIndex = 0, int pageSize = 2147483647);}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.csindex db324e04b..6d84cee4a 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Vendor service interface/// </summary>- public partial interface IVendorService+ public interface IVendorService{/// <summary>/// Gets a vendor by vendor identifier@@ -78,20 +78,20 @@ namespace Grand.Business.Core.Interfaces.Customers/// <summary>/// Update Vendor review totals/// </summary>- /// <param name="Vendor">Vendor</param>- Task UpdateVendorReviewTotals(Vendor Vendor);+ /// <param name="vendor">Vendor</param>+ Task UpdateVendorReviewTotals(Vendor vendor);/// <summary>/// Update Vendor review/// </summary>- /// <param name="Vendorreview">Vendorreview</param>- Task UpdateVendorReview(VendorReview Vendorreview);+ /// <param name="vendorReview">vendor review</param>+ Task UpdateVendorReview(VendorReview vendorReview);/// <summary>/// Insert Vendor review/// </summary>- /// <param name="Vendorreview">Vendorreview</param>- Task InsertVendorReview(VendorReview Vendorreview);+ /// <param name="vendorReview">vendor review</param>+ Task InsertVendorReview(VendorReview vendorReview);/// <summary>/// Gets all vendor reviews@@ -101,8 +101,9 @@ namespace Grand.Business.Core.Interfaces.Customers/// <param name="fromUtc">Item creation from; null to load all records</param>/// <param name="toUtc">Item item creation to; null to load all records</param>/// <param name="message">Search title or review text; null to load all records</param>- /// <param name="storeId">Store identifier; "" to load all records</param>/// <param name="vendorId">Vendor identifier; "" to load all records</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Reviews</returns>Task<IPagedList<VendorReview>> GetAllVendorReviews(string customerId, bool? approved,DateTime? fromUtc = null, DateTime? toUtc = null,diff --git a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IExportManager.cs b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IExportManager.csindex f871e1517..8f71c1e45 100644--- a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IExportManager.cs+++ b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IExportManager.cs@@ -1,6 +1,4 @@-using Grand.Business.Core.Utilities.ExportImport;--namespace Grand.Business.Core.Interfaces.ExportImport+namespace Grand.Business.Core.Interfaces.ExportImport{public interface IExportManager<T>{diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.csindex b75f8652b..241e748ff 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs@@ -3,7 +3,7 @@ using Grand.Domain.Messages;namespace Grand.Business.Core.Interfaces.Marketing.Campaigns{- public partial interface ICampaignService+ public interface ICampaignService{/// <summary>/// Inserts a campaign@@ -14,8 +14,8 @@ namespace Grand.Business.Core.Interfaces.Marketing.Campaigns/// <summary>/// Inserts a campaign history/// </summary>- /// <param name="campaign">Campaign</param>- Task InsertCampaignHistory(CampaignHistory campaignhistory);+ /// <param name="campaignHistory">Campaign history</param>+ Task InsertCampaignHistory(CampaignHistory campaignHistory);/// <summary>/// Updates a campaign/// </summary>@@ -50,7 +50,9 @@ namespace Grand.Business.Core.Interfaces.Marketing.Campaigns/// <summary>/// Gets customer subscriptions/// </summary>- /// <param name="Campaign">Campaign</param>+ /// <param name="campaign">Campaign</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>CampaignCustomerSubscription</returns>Task<IPagedList<NewsLetterSubscription>> CustomerSubscriptions(Campaign campaign, int pageIndex = 0, int pageSize = int.MaxValue);diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeParser.csindex 3e118e49e..554e4b8e5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeParser.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeParser.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <summary>/// Contact attribute parser interface/// </summary>- public partial interface IContactAttributeParser+ public interface IContactAttributeParser{/// <summary>/// Gets selected contact attributes@@ -27,7 +27,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="ca">Contact attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>@@ -37,14 +37,14 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified/// </summary>/// <param name="attribute">Contact attribute</param>- /// <param name="selectedAttributes">Selected attributes</param>+ /// <param name="customAttributes">Selected attributes</param>/// <returns>Result</returns>Task<bool?> IsConditionMet(ContactAttribute attribute, IList<CustomAttribute> customAttributes);/// <summary>/// Remove an attribute/// </summary>- /// <param name="customattributes">Attributes in XML format</param>+ /// <param name="customAttributes">Attributes in XML format</param>/// <param name="attribute">contact attribute</param>/// <returns>Updated result (XML format)</returns>IList<CustomAttribute> RemoveContactAttribute(IList<CustomAttribute> customAttributes, ContactAttribute attribute);@@ -55,15 +55,15 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <param name="language">Language</param>/// <param name="customAttributes">Attributes </param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>/// <returns>Attributes</returns>Task<string> FormatAttributes(Language language,IList<CustomAttribute> customAttributes,Customer customer,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true,bool allowHyperlinks = true);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.csindex 13f103fb9..a85cf5aca 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <summary>/// Contact attribute service/// </summary>- public partial interface IContactAttributeService+ public interface IContactAttributeService{#region Contact attributes@@ -19,8 +19,9 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// Gets all Contact attributes/// </summary>/// <param name="storeId">Store identifier</param>+ /// <param name="ignoreAcl">Ignore acl</param>/// <returns>Contact attributes</returns>- Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "", bool ignorAcl = false);+ Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "", bool ignoreAcl = false);/// <summary>/// Gets a Contact attributediff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.csindex 877f9995d..afbe25ffe 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <summary>/// ContactUs interface/// </summary>- public partial interface IContactUsService+ public interface IContactUsService{/// <summary>/// Deletes a contactus item@@ -27,6 +27,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Contacts/// <param name="email">email</param>/// <param name="vendorId">vendorId; null to load all records</param>/// <param name="customerId">customerId; null to load all records</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>ContactUs items</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.csindex 93c11ab49..19e7447de 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Customers/// <summary>/// Customer product service interface/// </summary>- public partial interface ICustomerProductService+ public interface ICustomerProductService{#region Customer Product Price@@ -59,11 +59,12 @@ namespace Grand.Business.Core.Interfaces.Marketing.CustomersTask DeleteCustomerProductPrice(CustomerProductPrice customerProductPrice);-/// <summary>/// Gets products price for customer/// </summary>/// <param name="customerId">Customer id</param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Customer products price</returns>Task<IPagedList<CustomerProductPrice>> GetProductsPriceByCustomer(string customerId, int pageIndex = 0, int pageSize = int.MaxValue);diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.csindex b928c02de..2a4733c40 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs@@ -6,12 +6,12 @@ namespace Grand.Business.Core.Interfaces.Marketing.Customers/// <summary>/// Product tag service interface/// </summary>- public partial interface ICustomerTagService+ public interface ICustomerTagService{/// <summary>/// Delete a customer tag/// </summary>- /// <param name="productTag">Customer tag</param>+ /// <param name="customerTag">Customer tag</param>Task DeleteCustomerTag(CustomerTag customerTag);/// <summary>@@ -65,7 +65,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Customers/// <summary>/// Updates the customer tag/// </summary>- /// <param name="productTag">Product tag</param>+ /// <param name="customerTag">Customer tag</param>Task UpdateCustomerTag(CustomerTag customerTag);/// <summary>@@ -93,7 +93,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Customers/// <summary>/// Gets customer tag product/// </summary>- /// <param name="Id">id</param>+ /// <param name="id">id</param>/// <returns>Customer tag product</returns>Task<CustomerTagProduct> GetCustomerTagProductById(string id);diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.csindex 45e5f96ac..d68932d62 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs@@ -4,7 +4,7 @@ using Grand.Domain.Documents;namespace Grand.Business.Core.Interfaces.Marketing.Documents{- public partial interface IDocumentService+ public interface IDocumentService{/// <summary>/// Gets a documentdiff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.csindex 4adea25ba..8dda60564 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Marketing.Documents{- public partial interface IDocumentTypeService+ public interface IDocumentTypeService{/// <summary>/// Gets a document typediff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.csindex 75bb55bd2..86aac1f60 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Newsletters/// <summary>/// Newsletter subscription service interface/// </summary>- public partial interface INewsLetterSubscriptionService+ public interface INewsLetterSubscriptionService{/// <summary>/// Inserts a newsletter subscriptiondiff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.csindex eb18ff75d..ea3f32e2f 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs@@ -2,32 +2,32 @@namespace Grand.Business.Core.Interfaces.Marketing.Newsletters{- public partial interface INewsletterCategoryService+ public interface INewsletterCategoryService{/// <summary>/// Inserts a newsletter category/// </summary>- /// <param name="NewsletterCategory">NewsletterCategory</param>- Task InsertNewsletterCategory(NewsletterCategory newslettercategory);+ /// <param name="newsletterCategory">NewsletterCategory</param>+ Task InsertNewsletterCategory(NewsletterCategory newsletterCategory);/// <summary>/// Updates a newsletter category/// </summary>- /// <param name="NewsletterCategory">NewsletterCategory</param>- Task UpdateNewsletterCategory(NewsletterCategory newslettercategory);+ /// <param name="newsletterCategory">NewsletterCategory</param>+ Task UpdateNewsletterCategory(NewsletterCategory newsletterCategory);/// <summary>/// Deleted a newsletter category/// </summary>- /// <param name="NewsletterCategory">NewsletterCategory</param>- Task DeleteNewsletterCategory(NewsletterCategory newslettercategory);+ /// <param name="newsletterCategory">NewsletterCategory</param>+ Task DeleteNewsletterCategory(NewsletterCategory newsletterCategory);/// <summary>/// Gets a newsletter by category/// </summary>- /// <param name="Id">newsletter category</param>+ /// <param name="id">newsletter category</param>/// <returns>NewsletterCategory</returns>- Task<NewsletterCategory> GetNewsletterCategoryById(string Id);+ Task<NewsletterCategory> GetNewsletterCategoryById(string id);/// <summary>/// Gets all newsletter categoriesdiff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.csindex 0e561ccf1..487716a64 100644--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs@@ -31,8 +31,8 @@ namespace Grand.Business.Core.Interfaces.Marketing.PushNotifications/// <summary>/// Gets all push receivers/// </summary>- /// <param name="Id"></param>- Task<PushRegistration> GetPushReceiver(string Id);+ /// <param name="id"></param>+ Task<PushRegistration> GetPushReceiver(string id);/// <summary>/// Gets number of customers that accepted push notifications permission popupdiff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.csindex 55130752d..dc9c8f0fb 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Interfaces.Messages{- public partial interface IEmailAccountService+ public interface IEmailAccountService{/// <summary>/// Inserts an email accountdiff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.csindex 160d67558..d2fe69cc9 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <summary>/// Email sender/// </summary>- public partial interface IEmailSender+ public interface IEmailSender{/// <summary>/// Sends an email@@ -23,7 +23,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <param name="cc">CC addresses ist</param>/// <param name="attachmentFilePath">Attachment file path</param>/// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>- /// <param name="attachedDownloads">Attachments download ID (another attachedments)</param>+ /// <param name="attachedDownloads">Attachments download ID (another attachments)</param>Task SendEmail(EmailAccount emailAccount, string subject, string body,string fromAddress, string fromName, string toAddress, string toName,string replyToAddress = null, string replyToName = null,diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.csindex bc97d6830..64bf76c1d 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs@@ -12,7 +12,7 @@ using Grand.Domain.Vendors;namespace Grand.Business.Core.Interfaces.Messages{- public partial interface IMessageProviderService+ public interface IMessageProviderService{#region Customer messages@@ -386,6 +386,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <summary>/// Sends a "quantity below" notification to a store owner/// </summary>+ /// <param name="product">Product</param>/// <param name="combination">Attribute combination</param>/// <param name="languageId">Message language identifier</param>/// <returns>Queued email identifier</returns>@@ -408,6 +409,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <summary>/// Sends an article comment notification message to a store owner/// </summary>+ /// <param name="article">Article</param>/// <param name="articleComment">Article comment</param>/// <param name="languageId">Message language identifier</param>/// <returns>Queued email identifier</returns>@@ -416,6 +418,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <summary>/// Sends a news comment notification message to a store owner/// </summary>+ /// <param name="newsItem">News item</param>/// <param name="newsComment">News comment</param>/// <param name="languageId">Message language identifier</param>/// <returns>Queued email identifier</returns>@@ -429,7 +432,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <param name="subscription">Subscription</param>/// <param name="languageId">Message language identifier</param>/// <returns>Queued email identifier</returns>- Task<int> SendBackinStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, string languageId);+ Task<int> SendBackInStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, string languageId);/// <summary>@@ -468,7 +471,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// </summary>/// <param name="product">Auction</param>/// <param name="languageId">Message language identifier</param>- /// <param name="Bid">Bid</param>+ /// <param name="bid">Bid</param>/// <returns>Queued email identifier</returns>Task<int> SendAuctionWinEndedCustomerMessage(Product product, string languageId, Bid bid);@@ -477,7 +480,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// </summary>/// <param name="product">Auction</param>/// <param name="languageId">Message language identifier</param>- /// <param name="Bid">Bid</param>+ /// <param name="bid"></param>/// <returns>Queued email identifier</returns>Task<int> SendAuctionEndedLostCustomerMessage(Product product, string languageId, Bid bid);@@ -496,7 +499,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// </summary>/// <param name="languageId">Message language identifier</param>/// <param name="product">Auction</param>- /// <param name="Bid">Bid</param>+ /// <param name="bid">Bid</param>/// <returns>Queued email identifier</returns>Task<int> SendAuctionEndedStoreOwnerMessage(Product product, string languageId, Bid bid);@@ -505,7 +508,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// </summary>/// <param name="languageId">Message language identifier</param>/// <param name="product">Product</param>- /// <param name="Bid">Bid</param>+ /// <param name="bid">Bid</param>/// <returns>Queued email identifier</returns>Task<int> SendOutBidCustomerMessage(Product product, string languageId, Bid bid);@@ -516,7 +519,6 @@ namespace Grand.Business.Core.Interfaces.Messages/// <param name="emailAccount">Email account</param>/// <param name="languageId">Language identifier</param>/// <param name="liquidObject">LiquidObject</param>- /// <param name="tokens">Tokens</param>/// <param name="toEmailAddress">Recipient email address</param>/// <param name="toName">Recipient name</param>/// <param name="attachmentFilePath">Attachment file path</param>diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.csindex 92ad81496..f03c9bfa5 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Messages/// <summary>/// Message template service/// </summary>- public partial interface IMessageTemplateService+ public interface IMessageTemplateService{/// <summary>/// Inserts a message templatediff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTokenProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTokenProvider.csindex a96aad36d..a98587cad 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTokenProvider.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTokenProvider.cs@@ -1,6 +1,6 @@namespace Grand.Business.Core.Interfaces.Messages{- public partial interface IMessageTokenProvider+ public interface IMessageTokenProvider{string[] GetListOfCampaignAllowedTokens();string[] GetListOfAllowedTokens();diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMimeMappingService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMimeMappingService.csindex b28bc1255..3b50859d9 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMimeMappingService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMimeMappingService.cs@@ -1,6 +1,6 @@namespace Grand.Business.Core.Interfaces.Messages{- public partial interface IMimeMappingService+ public interface IMimeMappingService{string Map(string fName);}diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.csindex 5aed2a226..803df65ef 100644--- a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs@@ -3,7 +3,7 @@ using Grand.Domain.Messages;namespace Grand.Business.Core.Interfaces.Messages{- public partial interface IQueuedEmailService+ public interface IQueuedEmailService{/// <summary>/// Inserts a queued emaildiff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.csindex d6f7ac151..369431224 100644--- a/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Storage/// <summary>/// Download service interface/// </summary>- public partial interface IDownloadService+ public interface IDownloadService{/// <summary>/// Gets a downloaddiff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.csindex c228d8b21..4b391ddca 100644--- a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs@@ -26,9 +26,8 @@ namespace Grand.Business.Core.Interfaces.Storage/// <summary>/// Retrieves information about the given directory within the file store./// </summary>- /// <param name="path">The path within the file store.</param>/// <returns>A <see cref="PhysicalDirectoryInfo"/> object representing the directory, or <c>null</c> if the directory does not exist.</returns>- Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directorypath);+ Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath);/// <summary>/// Enumerates the content (files and directories) in a given directory within the file store.@@ -169,10 +168,7 @@ namespace Grand.Business.Core.Interfaces.Storage/// </remarks>public static string NormalizePath(this IFileStore fileStore, string path){- if (path == null)- return null;-- return path.Replace('\\', '/').Trim('/', ' ');+ return path?.Replace('\\', '/').Trim('/', ' ');}}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.csindex 5c87dd3ba..3555bee53 100644--- a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Storage/// <summary>/// Picture service interface/// </summary>- public partial interface IPictureService+ public interface IPictureService{/// <summary>/// Gets the loaded picture binary depending on picture storage settings@@ -142,13 +142,13 @@ namespace Grand.Business.Core.Interfaces.Storage/// <param name="altAttribute">"alt" attribute for "img" HTML element</param>/// <param name="titleAttribute">"title" attribute for "img" HTML element</param>/// <param name="style">style attribute for "img" HTML element</param>- /// <param name="extrafield">Extra field</param>+ /// <param name="extraField">Extra field</param>/// <param name="isNew">A value indicating whether the picture is new</param>/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>/// <returns>Picture</returns>Task<Picture> UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType,string seoFilename, string altAttribute = null, string titleAttribute = null,- string style = null, string extrafield = null,+ string style = null, string extraField = null,bool isNew = true, bool validateBinary = true);/// <summary>@@ -162,6 +162,8 @@ namespace Grand.Business.Core.Interfaces.Storage/// Updates the picture field/// </summary>/// <param name="picture">Picture</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>Task UpdatePictureField<T>(Picture picture,Expression<Func<Picture, T>> expression, T value);diff --git a/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationLocalizedService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationLocalizedService.csindex fbbbdd8c3..15a1b9aed 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationLocalizedService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationLocalizedService.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.System.Installation/// <summary>/// Translation service for installation process/// </summary>- public partial interface IInstallationLocalizedService+ public interface IInstallationLocalizedService{/// <summary>/// Get locale resource valuediff --git a/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationService.csindex 9463fb7c8..43b3afc8b 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Installation/IInstallationService.cs@@ -2,7 +2,7 @@ using Microsoft.AspNetCore.Http;namespace Grand.Business.Core.Interfaces.System.Installation{- public partial interface IInstallationService+ public interface IInstallationService{Task InstallData(string httpscheme, HostString host,diff --git a/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.csindex 380cae8c1..d3b88cbb0 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Reports/ICustomerReportService.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <summary>/// Customer report service interface/// </summary>- public partial interface ICustomerReportService+ public interface ICustomerReportService{/// <summary>/// Get best customers@@ -36,6 +36,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <summary>/// Get "customer by time" report/// </summary>+ /// <param name="storeId">Store ident</param>/// <param name="startTimeUtc">Start date</param>/// <param name="endTimeUtc">End date</param>/// <returns>Result</returns>diff --git a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.csindex cf495bfb3..357aa334b 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <summary>/// Order report service interface/// </summary>- public partial interface IOrderReportService+ public interface IOrderReportService{/// <summary>/// Get "order by country" report@@ -42,7 +42,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <param name="storeId">Store identifier</param>/// <param name="customerId">Customer identifier</param>/// <param name="vendorId">Vendor identifier</param>- /// <param name="SalesEmployeeId">Sales employee identifier</param>+ /// <param name="salesEmployeeId">Sales employee identifier</param>/// <param name="billingCountryId">Billing country identifier</param>/// <param name="orderId">Order identifier</param>/// <param name="paymentMethodSystemName">Payment method system name; null to load all records</param>@@ -54,7 +54,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>/// <param name="billingLastName">Billing last name. Leave empty to load all records.</param>/// <param name="ignoreCancelledOrders">A value indicating whether to ignore cancelled orders</param>- /// <param name="tagid">Tag ident</param>+ /// <param name="tagId">Tag ident</param>/// <returns>Result</returns>Task<OrderAverageReportLine> GetOrderAverageReportLine(string storeId = "",string customerId = "", string vendorId = "", string salesEmployeeId = "",@@ -63,7 +63,7 @@ namespace Grand.Business.Core.Interfaces.System.ReportsDateTime? startTimeUtc = null, DateTime? endTimeUtc = null,string billingEmail = null, string billingLastName = "",bool ignoreCancelledOrders = false,- string tagid = null);+ string tagId = null);/// <summary>@@ -73,14 +73,12 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <param name="os">Order status</param>/// <returns>Result</returns>Task<OrderAverageReportLineSummary> OrderAverageReport(string storeId, int os);-+/// <summary>/// Get best sellers report/// </summary>/// <param name="storeId">Store identifier; "" to load all records</param>/// <param name="vendorId">Vendor identifier; "" to load all records</param>- /// <param name="categoryId">Category identifier; "" to load all records</param>- /// <param name="collectionId">Collection identifier; "" to load all records</param>/// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>/// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>/// <param name="os">Order status; null to load all records</param>diff --git a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IProductsReportService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IProductsReportService.csindex c0c2b0230..1c1bda533 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IProductsReportService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IProductsReportService.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.System.Reports/// <summary>/// Product report service interface/// </summary>- public partial interface IProductsReportService+ public interface IProductsReportService{/// <summary>/// Get "low stock products" reportdiff --git a/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs b/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.csindex f72720cd1..1ee9b1365 100644--- a/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs@@ -2,7 +2,7 @@ using Grand.Domain.Tasks;namespace Grand.Business.Core.Interfaces.System.ScheduleTasks{- public partial interface IScheduleTaskService+ public interface IScheduleTaskService{/// <summary>/// Gets a taskdiff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.csindex 05dc2124d..9f66ce93e 100644--- a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs+++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Authentication/// <summary>/// External auth param/// </summary>- public partial class ExternalAuthParam+ public class ExternalAuthParam{public ExternalAuthParam(){diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/GrandCookieAuthenticationDefaults.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/GrandCookieAuthenticationDefaults.csindex 294cb5e07..a7be6aa6b 100644--- a/src/Business/Grand.Business.Core/Utilities/Authentication/GrandCookieAuthenticationDefaults.cs+++ b/src/Business/Grand.Business.Core/Utilities/Authentication/GrandCookieAuthenticationDefaults.cs@@ -19,19 +19,9 @@ namespace Grand.Business.Core.Utilities.Authentication/// </summary>public static readonly PathString LoginPath = new PathString("/login");- /// <summary>- /// The default value used for the logout path- /// </summary>- public static readonly PathString LogoutPath = new PathString("/logout");-/// <summary>/// The default value for the access denied path/// </summary>public static readonly PathString AccessDeniedPath = new PathString("/access-denied");-- /// <summary>- /// The default value of the return url parameter- /// </summary>- public static readonly string ReturnUrlParameter = "";}}diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorCodeSetup.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorCodeSetup.csindex 840a4e2d4..a2157772a 100644--- a/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorCodeSetup.cs+++ b/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorCodeSetup.cs@@ -1,6 +1,6 @@namespace Grand.Business.Core.Utilities.Authentication{- public partial class TwoFactorCodeSetup+ public class TwoFactorCodeSetup{public TwoFactorCodeSetup(){diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.csindex 43c8f4afb..5e836a764 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs@@ -7,7 +7,7 @@ namespace Grand.Business.Core.Utilities.Catalog/// <summary>/// Represents a discount requirement validation request/// </summary>- public partial class DiscountRuleValidationRequest+ public class DiscountRuleValidationRequest{/// <summary>/// Gets or sets the discountdiff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.csindex 9204f2bda..cac8a893a 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs@@ -3,7 +3,7 @@/// <summary>/// Represents a result of discount requirement validation/// </summary>- public partial class DiscountRuleValidationResult+ public class DiscountRuleValidationResult{/// <summary>/// Gets or sets a value that indicates if discount is valid or notdiff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.csindex e9792b33d..5a12582cf 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs@@ -3,7 +3,7 @@/// <summary>/// Represents a result of discount validation/// </summary>- public partial class DiscountValidationResult+ public class DiscountValidationResult{/// <summary>/// Gets or sets a value that indicates if discount is validdiff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxProductPrice.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxProductPrice.csindex aae46d5c5..3c006bae9 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxProductPrice.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxProductPrice.cs@@ -2,15 +2,15 @@{public class TaxProductPrice{- public double UnitPriceWihoutDiscInclTax { get; set; }- public double UnitPriceWihoutDiscExclTax { get; set; }+ public double UnitPriceWithoutDiscInclTax { get; set; }+ public double UnitPriceWithoutDiscExclTax { get; set; }public double UnitPriceInclTax { get; set; }public double UnitPriceExclTax { get; set; }public int Quantity { get; set; }public double SubTotalInclTax { get; set; }public double SubTotalExclTax { get; set; }- public double discountAmountInclTax { get; set; }- public double discountAmountExclTax { get; set; }- public double taxRate { get; set; }+ public double DiscountAmountInclTax { get; set; }+ public double DiscountAmountExclTax { get; set; }+ public double TaxRate { get; set; }}}diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.csindex 00275eccc..368315522 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs@@ -7,9 +7,9 @@ namespace Grand.Business.Core.Utilities.Catalog/// <summary>/// Represents a request for tax calculation/// </summary>- public partial class TaxRequest+ public class TaxRequest{- // <summary>+ /// <summary>/// Gets or sets a product/// </summary>public Product Product { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxResult.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxResult.csindex 7bad425f5..f4968e4ec 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxResult.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Utilities.Catalog/// <summary>/// Represents a result of tax calculation/// </summary>- public partial class TaxResult+ public class TaxResult{/// <summary>/// Ctor@@ -26,13 +26,7 @@ namespace Grand.Business.Core.Utilities.Catalog/// <summary>/// Gets a value that indicates if request has been completed successfully/// </summary>- public bool Success- {- get- {- return Errors.Count == 0;- }- }+ public bool Success => Errors.Count == 0;/// <summary>/// Add errordiff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.csindex 6bc3ebf21..35bcea698 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Capture payment result/// </summary>- public partial class CapturePaymentResult+ public class CapturePaymentResult{private TransactionStatus _newTransactionStatus = TransactionStatus.Pending;@@ -20,10 +20,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (Errors.Count == 0); }- }+ public bool Success => Errors.Count == 0;/// <summary>/// Add error@@ -54,14 +51,8 @@ namespace Grand.Business.Core.Utilities.Checkout/// </summary>public TransactionStatus NewPaymentStatus{- get- {- return _newTransactionStatus;- }- set- {- _newTransactionStatus = value;- }+ get => _newTransactionStatus;+ set => _newTransactionStatus = value;}}}diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.csindex b8c03c4a0..33c9e7264 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs@@ -8,7 +8,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Represents a request for getting shipping rate options/// </summary>- public partial class GetShippingOptionRequest+ public class GetShippingOptionRequest{#region Ctor@@ -90,10 +90,7 @@ namespace Grand.Business.Core.Utilities.Checkoutpublic int GetQuantity(){- if (OverriddenQuantity.HasValue)- return OverriddenQuantity.Value;-- return ShoppingCartItem.Quantity;+ return OverriddenQuantity ?? ShoppingCartItem.Quantity;}}diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionResponse.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionResponse.csindex 0754fbcf5..231974abe 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionResponse.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionResponse.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Represents a response of getting shipping rate options/// </summary>- public partial class GetShippingOptionResponse+ public class GetShippingOptionResponse{/// <summary>/// Ctor@@ -29,13 +29,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get- {- return Errors.Count == 0;- }- }+ public bool Success => Errors.Count == 0;/// <summary>/// Add errordiff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainter.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cssimilarity index 97%rename from src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainter.csrename to src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.csindex 5bf9e1e0c..33b66e034 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainter.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs@@ -10,9 +10,9 @@ using Grand.Domain.Tax;namespace Grand.Business.Core.Utilities.Checkout{- public class PlaceOrderContainter+ public class PlaceOrderContainer{- public PlaceOrderContainter()+ public PlaceOrderContainer(){Cart = new List<ShoppingCartItem>();Taxes = new List<OrderTax>();diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.csindex d6d5fbc37..b850e8894 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Place order result/// </summary>- public partial class PlaceOrderResult+ public class PlaceOrderResult{/// <summary>/// Ctor@@ -19,10 +19,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (Errors.Count == 0); }- }+ public bool Success => Errors.Count == 0;/// <summary>/// Add errordiff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/ProcessPaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/ProcessPaymentResult.csindex b3c49884a..fb7bc226e 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/ProcessPaymentResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/ProcessPaymentResult.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Process payment result/// </summary>- public partial class ProcessPaymentResult+ public class ProcessPaymentResult{private TransactionStatus _newPaymentTransactionStatus = TransactionStatus.Pending;@@ -20,10 +20,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (this.Errors.Count == 0); }- }+ public bool Success => this.Errors.Count == 0;/// <summary>/// Add error@@ -45,14 +42,8 @@ namespace Grand.Business.Core.Utilities.Checkout/// </summary>public TransactionStatus NewPaymentTransactionStatus{- get- {- return _newPaymentTransactionStatus;- }- set- {- _newPaymentTransactionStatus = value;- }+ get => _newPaymentTransactionStatus;+ set => _newPaymentTransactionStatus = value;}/// <summary>diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.csindex 8efb1effe..00821d017 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Represents a RefundPaymentResult/// </summary>- public partial class RefundPaymentRequest+ public class RefundPaymentRequest{/// <summary>/// Gets or sets an payment transaction@@ -18,7 +18,7 @@ namespace Grand.Business.Core.Utilities.Checkoutpublic double AmountToRefund { get; set; }/// <summary>- /// Gets or sets a value indicating whether it's a partial refund; otherwize, full refund+ /// Gets or sets a value indicating whether it's a partial refund; otherwise, full refund/// </summary>public bool IsPartialRefund { get; set; }}diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentResult.csindex 7f8d6fd7a..35cd5e525 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentResult.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Refund payment result/// </summary>- public partial class RefundPaymentResult+ public class RefundPaymentResult{private TransactionStatus _newTransactionStatus = TransactionStatus.Pending;@@ -20,10 +20,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (this.Errors.Count == 0); }- }+ public bool Success => this.Errors.Count == 0;/// <summary>/// Add error@@ -44,14 +41,8 @@ namespace Grand.Business.Core.Utilities.Checkout/// </summary>public TransactionStatus NewTransactionStatus{- get- {- return _newTransactionStatus;- }- set- {- _newTransactionStatus = value;- }+ get => _newTransactionStatus;+ set => _newTransactionStatus = value;}}}diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/ShoppingCartValidatorOptions.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/ShoppingCartValidatorOptions.csindex 958c083a5..23b55984d 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/ShoppingCartValidatorOptions.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/ShoppingCartValidatorOptions.cs@@ -7,7 +7,6 @@public bool GetInventoryWarnings = true;public bool GetGiftVoucherWarnings = true;public bool GetRequiredProductWarnings = true;- public bool GetRentalWarnings = true;public bool GetReservationWarnings = true;}}diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/VoidPaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/VoidPaymentResult.csindex 63b85b634..a204aaef0 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/VoidPaymentResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/VoidPaymentResult.cs@@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Represents a VoidPaymentResult/// </summary>- public partial class VoidPaymentResult+ public class VoidPaymentResult{private TransactionStatus _newTransactionStatus = TransactionStatus.Pending;@@ -20,10 +20,7 @@ namespace Grand.Business.Core.Utilities.Checkout/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (Errors.Count == 0); }- }+ public bool Success => Errors.Count == 0;/// <summary>/// Add error@@ -44,14 +41,8 @@ namespace Grand.Business.Core.Utilities.Checkout/// </summary>public TransactionStatus NewTransactionStatus{- get- {- return _newTransactionStatus;- }- set- {- _newTransactionStatus = value;- }+ get => _newTransactionStatus;+ set => _newTransactionStatus = value;}}}diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionConfiguration.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionConfiguration.csindex afb9f26da..56a895050 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionConfiguration.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionConfiguration.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryConfiguration => "Configuration";- public static readonly Permission ManageCountries = new Permission+ public static readonly Permission ManageCountries = new(){Name = "Manage Countries",SystemName = PermissionSystemName.Countries,@@ -15,7 +15,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityActions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export, PermissionActionName.Import }};- public static readonly Permission ManageLanguages = new Permission+ public static readonly Permission ManageLanguages = new(){Name = "Manage Languages",SystemName = PermissionSystemName.Languages,@@ -23,41 +23,41 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryConfiguration,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export, PermissionActionName.Import }};- public static readonly Permission ManageSettings = new Permission+ public static readonly Permission ManageSettings = new(){Name = "Manage Settings",SystemName = PermissionSystemName.Settings,Area = "Admin area",Category = CategoryConfiguration};- public static readonly Permission ManagePaymentMethods = new Permission+ public static readonly Permission ManagePaymentMethods = new(){Name = "Manage Payment Methods",SystemName = PermissionSystemName.PaymentMethods,Area = "Admin area",Category = CategoryConfiguration};- public static readonly Permission ManageExternalAuthenticationMethods = new Permission+ public static readonly Permission ManageExternalAuthenticationMethods = new(){Name = "Manage External Authentication Methods",SystemName = PermissionSystemName.ExternalAuthenticationMethods,Area = "Admin area",Category = CategoryConfiguration};- public static readonly Permission ManageTaxSettings = new Permission+ public static readonly Permission ManageTaxSettings = new(){Name = "Manage Tax Settings",SystemName = PermissionSystemName.TaxSettings,Area = "Admin area",Category = CategoryConfiguration};- public static readonly Permission ManageShippingSettings = new Permission+ public static readonly Permission ManageShippingSettings = new(){Name = "Manage Shipping Settings",SystemName = PermissionSystemName.ShippingSettings,Category = CategoryConfiguration};- public static readonly Permission ManageCurrencies = new Permission+ public static readonly Permission ManageCurrencies = new(){Name = "Manage Currencies",SystemName = PermissionSystemName.Currencies,@@ -65,7 +65,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryConfiguration,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageMeasures = new Permission+ public static readonly Permission ManageMeasures = new(){Name = "Manage Measures",SystemName = PermissionSystemName.Measures,@@ -77,7 +77,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityPermissionActionName.Dimensions_List, PermissionActionName.Dimensions_Add, PermissionActionName.Dimensions_Edit, PermissionActionName.Dimensions_Delete,}};- public static readonly Permission ManageActivityLog = new Permission+ public static readonly Permission ManageActivityLog = new(){Name = "Manage Activity Log",SystemName = PermissionSystemName.ActivityLog,@@ -85,14 +85,14 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryConfiguration,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Delete }};- public static readonly Permission ManageAcl = new Permission+ public static readonly Permission ManageAcl = new(){Name = "Manage ACL",SystemName = PermissionSystemName.Acl,Area = "Admin area",Category = CategoryConfiguration};- public static readonly Permission ManageEmailAccounts = new Permission+ public static readonly Permission ManageEmailAccounts = new(){Name = "Manage Email Accounts",SystemName = PermissionSystemName.EmailAccounts,@@ -100,7 +100,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryConfiguration,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Create, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageStores = new Permission+ public static readonly Permission ManageStores = new(){Name = "Manage Stores",SystemName = PermissionSystemName.Stores,@@ -108,7 +108,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryConfiguration,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Create, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManagePlugins = new Permission+ public static readonly Permission ManagePlugins = new(){Name = "Manage Plugins",SystemName = PermissionSystemName.Plugins,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionContent.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionContent.csindex b0c9c68a8..e850ea7e5 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionContent.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionContent.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryContent => "Content";- public static readonly Permission ManageNews = new Permission+ public static readonly Permission ManageNews = new(){Name = "Manage News",SystemName = PermissionSystemName.News,@@ -14,7 +14,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageBlog = new Permission+ public static readonly Permission ManageBlog = new(){Name = "Manage Blog",SystemName = PermissionSystemName.Blog,@@ -22,7 +22,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageWidgets = new Permission+ public static readonly Permission ManageWidgets = new(){Name = "Manage Widgets",SystemName = PermissionSystemName.Widgets,@@ -30,7 +30,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit }};- public static readonly Permission ManagePages = new Permission+ public static readonly Permission ManagePages = new(){Name = "Manage Pages",SystemName = PermissionSystemName.Pages,@@ -38,7 +38,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageKnowledgebase = new Permission+ public static readonly Permission ManageKnowledgebase = new(){Name = "Manage Knowledgebase",SystemName = PermissionSystemName.Knowledgebase,@@ -46,7 +46,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageCourses = new Permission+ public static readonly Permission ManageCourses = new(){Name = "Manage Courses",SystemName = PermissionSystemName.Courses,@@ -54,7 +54,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryContent,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageMessageTemplates = new Permission+ public static readonly Permission ManageMessageTemplates = new(){Name = "Manage Message Templates",SystemName = PermissionSystemName.MessageTemplates,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionCustomer.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionCustomer.csindex 09502b560..a1686151e 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionCustomer.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionCustomer.cs@@ -6,14 +6,14 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryCustomer => "Customers";- public static readonly Permission AllowCustomerImpersonation = new Permission+ public static readonly Permission AllowCustomerImpersonation = new(){Name = "Allow Customer Impersonation",SystemName = PermissionSystemName.AllowCustomerImpersonation,Area = "Admin area",Category = CategoryCustomer};- public static readonly Permission ManageCustomers = new Permission+ public static readonly Permission ManageCustomers = new(){Name = "Manage Customers",SystemName = PermissionSystemName.Customers,@@ -21,7 +21,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export }};- public static readonly Permission ManageAddressAttribute = new Permission+ public static readonly Permission ManageAddressAttribute = new(){Name = "Manage Address Attributes",SystemName = PermissionSystemName.AddressAttributes,@@ -29,7 +29,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageCustomerAttribute = new Permission+ public static readonly Permission ManageCustomerAttribute = new(){Name = "Manage Customer Attributes",SystemName = PermissionSystemName.CustomerAttributes,@@ -37,7 +37,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageCustomerGroups = new Permission+ public static readonly Permission ManageCustomerGroups = new(){Name = "Manage Customer Groups",SystemName = PermissionSystemName.CustomerGroups,@@ -45,7 +45,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageCustomerTags = new Permission+ public static readonly Permission ManageCustomerTags = new(){Name = "Manage Customer Tags",SystemName = PermissionSystemName.CustomerTags,@@ -53,7 +53,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageSalesEmployees = new Permission+ public static readonly Permission ManageSalesEmployees = new(){Name = "Manage Sales Employees",SystemName = PermissionSystemName.SalesEmployees,@@ -61,7 +61,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Delete }};- public static readonly Permission ManageVendors = new Permission+ public static readonly Permission ManageVendors = new(){Name = "Manage Vendors",SystemName = PermissionSystemName.Vendors,@@ -69,7 +69,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryCustomer,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageVendorReviews = new Permission+ public static readonly Permission ManageVendorReviews = new(){Name = "Manage Vendor Reviews",SystemName = PermissionSystemName.VendorReviews,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionMarketing.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionMarketing.csindex 3fe06a06d..b93d0905c 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionMarketing.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionMarketing.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryMarketing => "Marketing";- public static readonly Permission ManageAffiliates = new Permission+ public static readonly Permission ManageAffiliates = new(){Name = "Manage Affiliates",SystemName = PermissionSystemName.Affiliates,@@ -14,7 +14,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManagePushEvents = new Permission+ public static readonly Permission ManagePushEvents = new(){Name = "Manage Push Events",SystemName = PermissionSystemName.PushNotifications,@@ -22,7 +22,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Delete }};- public static readonly Permission ManageCampaigns = new Permission+ public static readonly Permission ManageCampaigns = new(){Name = "Manage Campaigns",SystemName = PermissionSystemName.Campaigns,@@ -30,7 +30,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export }};- public static readonly Permission ManageDiscounts = new Permission+ public static readonly Permission ManageDiscounts = new(){Name = "Manage Discounts",SystemName = PermissionSystemName.Discounts,@@ -38,7 +38,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Preview, PermissionActionName.Edit, PermissionActionName.Delete }};- public static readonly Permission ManageNewsletterSubscribers = new Permission+ public static readonly Permission ManageNewsletterSubscribers = new(){Name = "Manage Newsletter Subscribers",SystemName = PermissionSystemName.NewsletterSubscribers,@@ -46,7 +46,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Export, PermissionActionName.Import, PermissionActionName.Delete }};- public static readonly Permission ManageNewsletterCategories = new Permission+ public static readonly Permission ManageNewsletterCategories = new(){Name = "Manage Newsletter Categories",SystemName = PermissionSystemName.NewsletterCategories,@@ -54,7 +54,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryMarketing,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Preview, PermissionActionName.Edit, PermissionActionName.Delete }};- public static readonly Permission ManageDocuments = new Permission+ public static readonly Permission ManageDocuments = new(){Name = "Manage Documents",SystemName = PermissionSystemName.Documents,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionOrder.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionOrder.csindex b0c9c0cd3..40e7da70e 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionOrder.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionOrder.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryOrder => "Orders";- public static readonly Permission ManageOrders = new Permission+ public static readonly Permission ManageOrders = new(){Name = "Manage Orders",SystemName = PermissionSystemName.Orders,@@ -14,7 +14,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = "Orders",Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Payments, PermissionActionName.Cancel, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export }};- public static readonly Permission ManageOrderTags = new Permission+ public static readonly Permission ManageOrderTags = new(){Name = "Manage Order Tags",SystemName = PermissionSystemName.OrderTags,@@ -22,14 +22,14 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryOrder,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageOrderStatus = new Permission+ public static readonly Permission ManageOrderStatus = new(){Name = "Manage Order status",SystemName = PermissionSystemName.OrderStatus,Area = "Admin area",Category = CategoryOrder};- public static readonly Permission ManageShipments = new Permission+ public static readonly Permission ManageShipments = new(){Name = "Manage Shipments",SystemName = PermissionSystemName.Shipments,@@ -37,7 +37,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryOrder,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete, PermissionActionName.Export }};- public static readonly Permission ManageGiftVouchers = new Permission+ public static readonly Permission ManageGiftVouchers = new(){Name = "Manage Gift vouchers",SystemName = PermissionSystemName.GiftVouchers,@@ -45,7 +45,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryOrder,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageMerchandiseReturns = new Permission+ public static readonly Permission ManageMerchandiseReturns = new(){Name = "Manage Merchandise Returns",SystemName = PermissionSystemName.MerchandiseReturns,@@ -53,7 +53,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryOrder,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManagePaymentTransactions = new Permission+ public static readonly Permission ManagePaymentTransactions = new(){Name = "Manage Payment Transaction",SystemName = PermissionSystemName.PaymentTransactions,@@ -61,14 +61,14 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryOrder,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageCurrentCarts = new Permission+ public static readonly Permission ManageCurrentCarts = new(){Name = "Manage Current Carts",SystemName = PermissionSystemName.CurrentCarts,Area = "Admin area",Category = CategoryOrder};- public static readonly Permission ManageCheckoutAttribute = new Permission+ public static readonly Permission ManageCheckoutAttribute = new(){Name = "Manage Checkout Attributes",SystemName = PermissionSystemName.CheckoutAttributes,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionPublicStore.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionPublicStore.csindex 276869a3b..8c1770541 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionPublicStore.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionPublicStore.cs@@ -6,35 +6,35 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryPublicStore => "PublicStore";- public static readonly Permission DisplayPrices = new Permission+ public static readonly Permission DisplayPrices = new(){Name = "Display Prices",SystemName = PermissionSystemName.DisplayPrices,Area = "Public store",Category = CategoryPublicStore};- public static readonly Permission EnableShoppingCart = new Permission+ public static readonly Permission EnableShoppingCart = new(){Name = "Enable shopping cart",SystemName = PermissionSystemName.EnableShoppingCart,Area = "Public store",Category = CategoryPublicStore};- public static readonly Permission EnableWishlist = new Permission+ public static readonly Permission EnableWishlist = new(){Name = "Enable wishlist",SystemName = PermissionSystemName.EnableWishlist,Area = "Public store",Category = CategoryPublicStore};- public static readonly Permission PublicStoreAllowNavigation = new Permission+ public static readonly Permission PublicStoreAllowNavigation = new(){Name = "Allow navigation",SystemName = PermissionSystemName.PublicStoreAllowNavigation,Area = "Public store",Category = CategoryPublicStore};- public static readonly Permission AccessClosedStore = new Permission+ public static readonly Permission AccessClosedStore = new(){Name = "Access a closed store",SystemName = PermissionSystemName.AccessClosedStore,@@ -42,7 +42,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategoryPublicStore};- public static readonly Permission AllowUseApi = new Permission {+ public static readonly Permission AllowUseApi = new() {Name = "Allow to use api for web",SystemName = PermissionSystemName.AllowUseApi,Area = "Public store",diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionReport.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionReport.csindex 3977fc034..f3575dfaf 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionReport.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionReport.cs@@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategoryReport => "Reports";- public static readonly Permission ManageReports = new Permission+ public static readonly Permission ManageReports = new(){Name = "Manage Reports",SystemName = PermissionSystemName.Reports,diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.csindex 80b6d3221..8c22fcdde 100644--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs@@ -6,14 +6,14 @@ namespace Grand.Business.Core.Utilities.Common.Security{private static string CategorySystem => "System";- public static readonly Permission ManageSystemLog = new Permission+ public static readonly Permission ManageSystemLog = new(){Name = "Manage System Log",SystemName = PermissionSystemName.SystemLog,Area = "Admin area",Category = CategorySystem};- public static readonly Permission ManageMessageQueue = new Permission+ public static readonly Permission ManageMessageQueue = new(){Name = "Manage Message Queue",SystemName = PermissionSystemName.MessageQueue,@@ -21,7 +21,7 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategorySystem,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Create, PermissionActionName.Edit, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageMessageContactForm = new Permission+ public static readonly Permission ManageMessageContactForm = new(){Name = "Manage Message Contact form",SystemName = PermissionSystemName.MessageContactForm,@@ -29,41 +29,41 @@ namespace Grand.Business.Core.Utilities.Common.SecurityCategory = CategorySystem,Actions = new List<string> { PermissionActionName.List, PermissionActionName.Preview, PermissionActionName.Delete }};- public static readonly Permission ManageMaintenance = new Permission+ public static readonly Permission ManageMaintenance = new(){Name = "Manage Maintenance",SystemName = PermissionSystemName.Maintenance,Area = "Admin area",Category = CategorySystem};- public static readonly Permission ManageSystem = new Permission {+ public static readonly Permission ManageSystem = new() {Name = "Manage System",SystemName = PermissionSystemName.System,Area = "Admin area",Category = CategorySystem};- public static readonly Permission ManageFiles = new Permission+ public static readonly Permission ManageFiles = new(){Name = "Manage Files",SystemName = PermissionSystemName.Files,Area = "Admin area",Category = CategorySystem};- public static readonly Permission ManagePictures = new Permission+ public static readonly Permission ManagePictures = new(){Name = "Manage Pictures",SystemName = PermissionSystemName.Pictures,Area = "Admin area",Category = CategorySystem};- public static readonly Permission HtmlEditorManagePictures = new Permission+ public static readonly Permission HtmlEditorManagePictures = new(){Name = "HTML Editor. Manage pictures",SystemName = PermissionSystemName.HtmlEditor,Area = "Admin area",Category = "Configuration"};- public static readonly Permission ManageScheduleTasks = new Permission+ public static readonly Permission ManageScheduleTasks = new(){Name = "Manage Schedule Tasks",SystemName = PermissionSystemName.ScheduleTasks,diff --git a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.csindex 95ed0c68e..3fa6a1cdb 100644--- a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs@@ -3,7 +3,7 @@namespace Grand.Business.Core.Utilities.Customers{/// <summary>- /// Change password requst+ /// Change password request/// </summary>public class ChangePasswordRequest{diff --git a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.csindex 7044fe2c4..6d3b226f2 100644--- a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs@@ -16,10 +16,7 @@/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return (this.Errors.Count == 0); }- }+ public bool Success => this.Errors.Count == 0;/// <summary>/// Add errordiff --git a/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs b/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.csindex 2687767fa..f50ca6a3b 100644--- a/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs@@ -1,7 +1,7 @@namespace Grand.Business.Core.Utilities.Customers{/// <summary>- /// Customerregistration result+ /// Customer Registration result/// </summary>public class RegistrationResult{@@ -16,10 +16,7 @@/// <summary>/// Gets a value indicating whether request has been completed successfully/// </summary>- public bool Success- {- get { return this.Errors.Count == 0; }- }+ public bool Success => this.Errors.Count == 0;/// <summary>/// Add errordiff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.csindex 26cbb80f6..7abe2c23c 100644--- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs+++ b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs@@ -14,7 +14,7 @@/// <summary>/// Ctor/// </summary>- /// <param name="properties">All acsess properties</param>+ /// <param name="properties">All access properties</param>public PropertyManager(PropertyByName<T>[] properties){_properties = new Dictionary<string, PropertyByName<T>>();diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAskQuestion.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAskQuestion.csindex e4d5146df..3360c1297 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAskQuestion.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAskQuestion.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidAskQuestion : Drop+ public class LiquidAskQuestion : Drop{private readonly string message;private readonly string email;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAttributeCombination.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAttributeCombination.csindex fbad24fb0..5de215623 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAttributeCombination.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAttributeCombination.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidAttributeCombination : Drop+ public class LiquidAttributeCombination : Drop{private readonly ProductAttributeCombination _combination;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAuctions.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAuctions.csindex 9b4af3633..85b90db15 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAuctions.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidAuctions.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidAuctions : Drop+ public class LiquidAuctions : Drop{private readonly Product _product;private readonly Bid _bid;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidBlogComment.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidBlogComment.csindex 95f51421e..a82648675 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidBlogComment.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidBlogComment.cs@@ -5,7 +5,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidBlogComment : Drop+ public class LiquidBlogComment : Drop{private readonly BlogComment _blogComment;private readonly BlogPost _blogPost;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidContactUs.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidContactUs.csindex f583f1f63..c8d261e8e 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidContactUs.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidContactUs.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidContactUs : Drop+ public class LiquidContactUs : Drop{private readonly string senderEmail;private readonly string senderName;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidCustomer.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidCustomer.csindex 2ca97b3a9..51371009b 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidCustomer.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidCustomer.cs@@ -8,7 +8,7 @@ using System.Net;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidCustomer : Drop+ public class LiquidCustomer : Drop{private readonly Customer _customer;private readonly CustomerNote _customerNote;@@ -112,7 +112,7 @@ namespace Grand.Business.Core.Utilities.Messages.DotLiquidDropspublic string AccountActivationURL{- get { return string.Format("{0}/account/activation?token={1}&email={2}", url, _customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AccountActivationToken), WebUtility.UrlEncode(_customer.Email)); ; }+ get { return string.Format("{0}/account/activation?token={1}&email={2}", url, _customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AccountActivationToken), WebUtility.UrlEncode(_customer.Email)); }}public string WishlistURLForCustomerdiff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmail.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmail.csindex 4fd7efabe..98b1f51dc 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmail.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmail.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidEmail : Drop+ public class LiquidEmail : Drop{private readonly string _emailId;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmailAFriend.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmailAFriend.csindex d9b31c27f..167611bd8 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmailAFriend.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidEmailAFriend.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidEmailAFriend : Drop+ public class LiquidEmailAFriend : Drop{private readonly string _personalMessage;private readonly string _customerEmail;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidGiftVoucher.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidGiftVoucher.csindex bb91f0a5b..31f0a123c 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidGiftVoucher.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidGiftVoucher.cs@@ -4,7 +4,7 @@ using Grand.SharedKernel.Extensions;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidGiftVoucher : Drop+ public class LiquidGiftVoucher : Drop{private readonly GiftVoucher _giftVoucher;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidKnowledgebase.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidKnowledgebase.csindex 2659eb3e7..4bca8892c 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidKnowledgebase.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidKnowledgebase.cs@@ -5,7 +5,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidKnowledgebase : Drop+ public class LiquidKnowledgebase : Drop{private readonly KnowledgebaseArticle _article;private readonly KnowledgebaseArticleComment _articleComment;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturn.csindex fe136ec33..ded0d4fd3 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs@@ -5,7 +5,7 @@ using Grand.SharedKernel.Extensions;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidMerchandiseReturn : Drop+ public class LiquidMerchandiseReturn : Drop{private readonly MerchandiseReturn _merchandiseReturn;private readonly Order _order;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.csindex bb9d49034..50430609d 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs@@ -5,7 +5,7 @@ using System.Net;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidMerchandiseReturnItem : Drop+ public class LiquidMerchandiseReturnItem : Drop{private readonly MerchandiseReturnItem _item;private readonly Product _product;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsComment.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsComment.csindex 0608d5440..c68b17843 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsComment.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsComment.cs@@ -5,7 +5,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidNewsComment : Drop+ public class LiquidNewsComment : Drop{private readonly NewsComment _newsComment;private readonly NewsItem _newsItem;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsLetterSubscription.csindex 5cae9e9c9..b7caace68 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs@@ -4,7 +4,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidNewsLetterSubscription : Drop+ public class LiquidNewsLetterSubscription : Drop{private readonly NewsLetterSubscription _subscription;private readonly Store _store;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidObjectBuilder.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidObjectBuilder.csindex bae78b5e3..dd0dbbe1b 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidObjectBuilder.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidObjectBuilder.cs@@ -1,4 +1,5 @@using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Extensions;using Grand.Domain.Blogs;using Grand.Domain.Catalog;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrder.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrder.csindex e6e154b16..ba5b724de 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrder.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrder.cs@@ -10,7 +10,7 @@ using Grand.SharedKernel.Extensions;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidOrder : Drop+ public class LiquidOrder : Drop{private readonly Order _order;private readonly Language _language;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrderItem.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrderItem.csindex 9753968b4..1ee44bbac 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrderItem.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOrderItem.cs@@ -9,7 +9,7 @@ using System.Net;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidOrderItem : Drop+ public class LiquidOrderItem : Drop{private readonly OrderItem _orderItem;private readonly Product _product;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOutOfStockSubscription.csindex 4d5c5435a..96c1c65fb 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs@@ -5,7 +5,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidOutOfStockSubscription : Drop+ public class LiquidOutOfStockSubscription : Drop{private readonly OutOfStockSubscription _outOfStockSubscription;private readonly Product _product;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProduct.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProduct.csindex 6efe10599..b89d02b1d 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProduct.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProduct.cs@@ -6,7 +6,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidProduct : Drop+ public class LiquidProduct : Drop{private readonly Product _product;private readonly Language _language;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProductReview.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProductReview.csindex b5151d42a..3b12546e4 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProductReview.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidProductReview.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidProductReview : Drop+ public class LiquidProductReview : Drop{private readonly ProductReview _productReview;private readonly Product _product;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipment.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipment.csindex 11d72424c..7ce37edd1 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipment.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipment.cs@@ -6,7 +6,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidShipment : Drop+ public class LiquidShipment : Drop{private readonly Shipment _shipment;private readonly Order _order;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipmentItem.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipmentItem.csindex e52acffdd..68e86009e 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipmentItem.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShipmentItem.cs@@ -7,7 +7,7 @@ using System.Net;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidShipmentItem : Drop+ public class LiquidShipmentItem : Drop{private readonly ShipmentItem _shipmentItem;private readonly Shipment _shipment;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCart.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCart.csindex e4b6373df..9ebb1d86e 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCart.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCart.cs@@ -4,7 +4,7 @@ using Grand.Domain.Customers;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidShoppingCart : Drop+ public class LiquidShoppingCart : Drop{private ICollection<LiquidShoppingCartItem> _items;private readonly Customer _customer;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCartItem.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCartItem.csindex 5c25ccb04..983628b0d 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCartItem.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidShoppingCartItem.cs@@ -7,7 +7,7 @@ using System.Net;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidShoppingCartItem : Drop+ public class LiquidShoppingCartItem : Drop{private readonly Product _product;private readonly Language _language;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidStore.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidStore.csindex 0623afbaf..b4df7e0b1 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidStore.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidStore.cs@@ -5,7 +5,7 @@ using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidStore : Drop+ public class LiquidStore : Drop{private readonly Store _store;private readonly EmailAccount _emailAccount;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVatValidationResult.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVatValidationResult.csindex ca8a1bc5e..fc74fd262 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVatValidationResult.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVatValidationResult.cs@@ -2,7 +2,7 @@namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidVatValidationResult : Drop+ public class LiquidVatValidationResult : Drop{private readonly string name;private readonly string address;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendor.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendor.csindex 5503cda78..d37e7d204 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendor.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendor.cs@@ -3,7 +3,7 @@ using Grand.Domain.Vendors;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidVendor : Drop+ public class LiquidVendor : Drop{private readonly Vendor _vendor;diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendorReview.cs b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendorReview.csindex b530f848b..cc3a92126 100644--- a/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendorReview.cs+++ b/src/Business/Grand.Business.Core/Utilities/Messages/DotLiquidDrops/LiquidVendorReview.cs@@ -3,7 +3,7 @@ using Grand.Domain.Vendors;namespace Grand.Business.Core.Utilities.Messages.DotLiquidDrops{- public partial class LiquidVendorReview : Drop+ public class LiquidVendorReview : Drop{private readonly VendorReview _vendorReview;private readonly Vendor _vendor;diff --git a/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.csindex 8149f7700..d981edeab 100644--- a/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs@@ -4,7 +4,7 @@ namespace Grand.Business.Core.Utilities.System/// <summary>/// Represents a best customer report line/// </summary>- public partial class BestCustomerReportLine+ public class BestCustomerReportLine{/// <summary>/// Gets or sets the customer identifierdiff --git a/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.csindex 9ddf7583a..ce5e48f81 100644--- a/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs@@ -4,7 +4,7 @@ namespace Grand.Business.Core.Utilities.System/// Represents a best sellers report line/// </summary>[Serializable]- public partial class BestsellersReportLine+ public class BestsellersReportLine{/// <summary>/// Gets or sets the product identifierdiff --git a/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.csindex 14fcb1c30..9fade6398 100644--- a/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs@@ -1,6 +1,6 @@namespace Grand.Business.Core.Utilities.System{- public partial class CustomerByTimeReportLine+ public class CustomerByTimeReportLine{public string Time { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/System/DownloadUrl.cs b/src/Business/Grand.Business.Core/Utilities/System/DownloadUrl.csindex b04740484..cb979aff1 100644--- a/src/Business/Grand.Business.Core/Utilities/System/DownloadUrl.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/DownloadUrl.cs@@ -6,16 +6,13 @@ namespace Grand.Business.Core.Utilities.System{public static async Task<byte[]> DownloadFile(string url){- using (var client = new HttpClient())+ using var client = new HttpClient();+ using var result = await client.GetAsync(url);+ if (result.IsSuccessStatusCode){- using (var result = await client.GetAsync(url))- {- if (result.IsSuccessStatusCode)- {- return await result.Content.ReadAsByteArrayAsync();- }- }+ return await result.Content.ReadAsByteArrayAsync();}+return null;}}diff --git a/src/Business/Grand.Business.Core/Utilities/System/InstallationLanguage.cs b/src/Business/Grand.Business.Core/Utilities/System/InstallationLanguage.csindex b1df6b8ed..d91e0c8fe 100644--- a/src/Business/Grand.Business.Core/Utilities/System/InstallationLanguage.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/InstallationLanguage.cs@@ -3,7 +3,7 @@/// <summary>/// Language class for installation process/// </summary>- public partial class InstallationLanguage+ public class InstallationLanguage{public InstallationLanguage(){@@ -17,13 +17,13 @@public List<InstallationLocaleResource> Resources { get; protected set; }}- public partial class InstallationLocaleResource+ public class InstallationLocaleResource{public string Name { get; set; }public string Value { get; set; }}- public partial class InstallationCollation+ public class InstallationCollation{public string Name { get; set; }public string Value { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLine.csindex 8cef1ec43..8c2a7d39f 100644--- a/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLine.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Utilities.System/// <summary>/// Represents an order average report line/// </summary>- public partial class OrderAverageReportLine+ public class OrderAverageReportLine{/// <summary>/// Gets or sets the countdiff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLineSummary.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLineSummary.csindex f50f2dbb2..18b4bbfc0 100644--- a/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLineSummary.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/OrderAverageReportLineSummary.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Utilities.System/// <summary>/// Represents an order average report line summary/// </summary>- public partial class OrderAverageReportLineSummary+ public class OrderAverageReportLineSummary{/// <summary>/// Gets or sets the order statusdiff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.csindex 8a32b822f..1f7ec95b0 100644--- a/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs@@ -3,10 +3,10 @@ namespace Grand.Business.Core.Utilities.System/// <summary>/// Represents an "order by country" report line/// </summary>- public partial class OrderByCountryReportLine+ public class OrderByCountryReportLine{/// <summary>- /// Country identifier; null for unknow country+ /// Country identifier; null for un know country/// </summary>public string CountryId { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.csindex ae851f431..e1b4736c6 100644--- a/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs@@ -3,7 +3,7 @@ namespace Grand.Business.Core.Utilities.System/// <summary>/// Represents an "order by country" report line/// </summary>- public partial class OrderByTimeReportLine+ public class OrderByTimeReportLine{public string Time { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/System/ReportPeriodOrder.cs b/src/Business/Grand.Business.Core/Utilities/System/ReportPeriodOrder.csindex 31c4c4db1..ef81690af 100644--- a/src/Business/Grand.Business.Core/Utilities/System/ReportPeriodOrder.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/ReportPeriodOrder.cs@@ -1,6 +1,6 @@namespace Grand.Business.Core.Utilities.System{- public partial class ReportPeriodOrder+ public class ReportPeriodOrder{public DateTime Date { get; set; }public int Count { get; set; }diff --git a/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs b/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.csindex 0de863561..9c5677e75 100644--- a/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs+++ b/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs@@ -6,16 +6,16 @@ namespace Grand.Business.Core.Utilities.Systempublic static class StandardAdminSiteMap{public static readonly List<AdminSiteMap> SiteMap =- new List<AdminSiteMap>() {- new AdminSiteMap {+ new List<AdminSiteMap> {+ new () {SystemName = "Dashboard",ResourceName = "Admin.Dashboard",ControllerName = "Home",ActionName = "Index",IconClass = "icon-home",DisplayOrder = 0,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Dashboard",ResourceName = "Admin.Dashboard",ControllerName = "Home",@@ -23,7 +23,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "icon-bar-chart"},- new AdminSiteMap {+ new () {SystemName = "Dashboard",ResourceName = "Admin.Dashboard.Statistics",ControllerName = "Home",@@ -32,7 +32,7 @@ namespace Grand.Business.Core.Utilities.SystemPermissionNames = new List<string> { PermissionSystemName.Reports },IconClass = "icon-bulb"},- new AdminSiteMap {+ new () {SystemName = "Shopping carts and wishlists",ResourceName = "Admin.Dashboards.CurrentCartWishlists",PermissionNames = new List<string> { PermissionSystemName.CurrentCarts },@@ -41,7 +41,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Online customers",ResourceName = "Admin.Dashboards.OnlineCustomers",PermissionNames = new List<string> { PermissionSystemName.Customers },@@ -52,15 +52,15 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Catalog",ResourceName = "Admin.Catalog",PermissionNames = new List<string> { PermissionSystemName.Products, PermissionSystemName.Categories, PermissionSystemName.Brands, PermissionSystemName.Collections, PermissionSystemName.ProductReviews, PermissionSystemName.ProductTags,PermissionSystemName.ProductAttributes, PermissionSystemName.SpecificationAttributes },IconClass = "fa fa-sitemap",DisplayOrder = 1,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Products",ResourceName = "Admin.Catalog.Products.Manage",PermissionNames = new List<string> { PermissionSystemName.Products },@@ -69,7 +69,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Categories",ResourceName = "Admin.Catalog.Categories",ControllerName = "Category",@@ -78,7 +78,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Brands",ResourceName = "Admin.Catalog.Brands",ControllerName = "Brand",@@ -87,7 +87,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Collections",ResourceName = "Admin.Catalog.Collections",PermissionNames = new List<string> { PermissionSystemName.Collections },@@ -96,7 +96,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Product tags",ResourceName = "Admin.Catalog.ProductTags",PermissionNames = new List<string> { PermissionSystemName.ProductTags },@@ -105,7 +105,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Bulk edit products",ResourceName = "Admin.Catalog.BulkEdit",PermissionNames = new List<string> { PermissionSystemName.Products },@@ -114,7 +114,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Product reviews",ResourceName = "Admin.Catalog.ProductReviews",PermissionNames = new List<string> { PermissionSystemName.ProductReviews },@@ -123,7 +123,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 6,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Products attributes",ResourceName = "Admin.Catalog.Attributes.ProductAttributes",ControllerName = "ProductAttribute",@@ -132,7 +132,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 7,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Specification attributes",ResourceName = "Admin.Catalog.Attributes.SpecificationAttributes",ControllerName = "SpecificationAttribute",@@ -140,10 +140,10 @@ namespace Grand.Business.Core.Utilities.SystemPermissionNames = new List<string> { PermissionSystemName.SpecificationAttributes },DisplayOrder = 8,IconClass = "fa fa-dot-circle-o"- },+ }}},- new AdminSiteMap {+ new () {SystemName = "Sales",ResourceName = "Admin.Sales",PermissionNames = new List<string> { PermissionSystemName.Orders, PermissionSystemName.Shipments,@@ -151,8 +151,8 @@ namespace Grand.Business.Core.Utilities.SystemPermissionSystemName.OrderStatus, PermissionSystemName.CheckoutAttributes },IconClass = "icon-basket",DisplayOrder = 2,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Orders",ResourceName = "Admin.Orders",PermissionNames = new List<string> { PermissionSystemName.Orders },@@ -161,7 +161,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Shipments",ResourceName = "Admin.Orders.Shipments.List",PermissionNames = new List<string> { PermissionSystemName.Shipments },@@ -170,7 +170,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Merchandise returns",ResourceName = "Admin.Orders.MerchandiseReturns",PermissionNames = new List<string> { PermissionSystemName.MerchandiseReturns },@@ -179,7 +179,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Payment transaction",ResourceName = "Admin.Orders.PaymentTransaction",PermissionNames = new List<string> { PermissionSystemName.PaymentTransactions },@@ -188,7 +188,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "OrderTags",ResourceName = "Admin.Orders.OrderTags",PermissionNames = new List<string> { PermissionSystemName.OrderTags },@@ -197,7 +197,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Checkout attributes",ResourceName = "Admin.Orders.CheckoutAttributes",ControllerName = "CheckoutAttribute",@@ -206,7 +206,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Order status",ResourceName = "Admin.Orders.OrderStatus",ControllerName = "OrderStatus",@@ -214,19 +214,18 @@ namespace Grand.Business.Core.Utilities.SystemActionName = "Index",DisplayOrder = 6,IconClass = "fa fa-dot-circle-o"- },-+ }}},- new AdminSiteMap {+ new () {SystemName = "Customers",ResourceName = "Admin.Customers",PermissionNames = new List<string> { PermissionSystemName.Customers, PermissionSystemName.Vendors, PermissionSystemName.VendorReviews, PermissionSystemName.ActivityLog,PermissionSystemName.CustomerTags, PermissionSystemName.CustomerGroups, PermissionSystemName.SalesEmployees },IconClass = "icon-users",DisplayOrder = 3,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Customers",ResourceName = "Admin.Customers.Customers",PermissionNames = new List<string> { PermissionSystemName.Customers },@@ -235,7 +234,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Customer groups",ResourceName = "Admin.Customers.CustomerGroups",PermissionNames = new List<string> { PermissionSystemName.CustomerGroups },@@ -244,7 +243,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Customer tags",ResourceName = "Admin.Customers.CustomerTags",PermissionNames = new List<string> { PermissionSystemName.CustomerTags },@@ -253,7 +252,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Vendors",ResourceName = "Admin.Vendors",PermissionNames = new List<string> { PermissionSystemName.Vendors },@@ -262,7 +261,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Vendor reviews",ResourceName = "Admin.VendorReviews",PermissionNames = new List<string> { PermissionSystemName.VendorReviews },@@ -271,7 +270,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Sales employee",ResourceName = "Admin.Customers.SalesEmployees",PermissionNames = new List<string> { PermissionSystemName.SalesEmployees },@@ -280,7 +279,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Customer attributes",ResourceName = "Admin.Customers.Attributes.Customer",ControllerName = "CustomerAttribute",@@ -289,7 +288,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 6,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Address attributes",ResourceName = "Admin.Customers.Attributes.Address",ControllerName = "AddressAttribute",@@ -298,7 +297,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 7,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Activity Log",ResourceName = "Admin.Configuration.ActivityLog",PermissionNames = new List<string> { PermissionSystemName.ActivityLog },@@ -309,7 +308,7 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Marketing",ResourceName = "Admin.Marketing",PermissionNames = new List<string> { PermissionSystemName.Affiliates, PermissionSystemName.NewsletterCategories, PermissionSystemName.NewsletterSubscribers,@@ -318,8 +317,8 @@ namespace Grand.Business.Core.Utilities.SystemPermissionSystemName.ContactAttributes},IconClass = "icon-bulb",DisplayOrder = 4,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Discounts",ResourceName = "Admin.Marketing.Discounts",PermissionNames = new List<string> { PermissionSystemName.Discounts },@@ -328,7 +327,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Gift vouchers",ResourceName = "Admin.GiftVouchers",PermissionNames = new List<string> { PermissionSystemName.GiftVouchers },@@ -337,7 +336,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Affiliates",ResourceName = "Admin.Affiliates",PermissionNames = new List<string> { PermissionSystemName.Affiliates },@@ -346,7 +345,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Contact attributes",ResourceName = "Admin.Catalog.Attributes.ContactAttributes",ControllerName = "ContactAttribute",@@ -355,14 +354,14 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Newsletter",ResourceName = "Admin.Marketing.Newsletter",PermissionNames = new List<string> { PermissionSystemName.Campaigns, PermissionSystemName.NewsletterSubscribers },IconClass = "fa fa-dot-circle-o",DisplayOrder = 5,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Campaigns",ResourceName = "Admin.Marketing.Campaigns",PermissionNames = new List<string> { PermissionSystemName.Campaigns },@@ -371,7 +370,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Newsletter categories",ResourceName = "Admin.Marketing.NewsletterCategory",PermissionNames = new List<string> { PermissionSystemName.NewsletterCategories },@@ -380,7 +379,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Newsletter subscriptions",ResourceName = "Admin.Marketing.NewsletterSubscriptions",PermissionNames = new List<string> { PermissionSystemName.NewsletterSubscribers },@@ -391,15 +390,15 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "PushNotifications",ResourceName = "Admin.PushNotifications",PermissionNames = new List<string> { PermissionSystemName.PushNotifications },ControllerName = "PushNotifications",IconClass = "fa fa-dot-circle-o",DisplayOrder = 7,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "PushNotifications",ResourceName = "Admin.PushNotifications.Send",PermissionNames = new List<string> { PermissionSystemName.PushNotifications },@@ -408,7 +407,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "PushNotifications",ResourceName = "Admin.PushNotifications.Messages",PermissionNames = new List<string> { PermissionSystemName.PushNotifications },@@ -417,7 +416,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "PushNotifications",ResourceName = "Admin.PushNotifications.Receivers",PermissionNames = new List<string> { PermissionSystemName.PushNotifications },@@ -428,14 +427,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Documents",ResourceName = "Admin.Marketing.Documents",PermissionNames = new List<string> { PermissionSystemName.Documents },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 8,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Document types",ResourceName = "Admin.Marketing.Document.Type",ControllerName = "Document",@@ -443,7 +442,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Document list",ResourceName = "Admin.Marketing.Document.List",ControllerName = "Document",@@ -452,10 +451,10 @@ namespace Grand.Business.Core.Utilities.SystemIconClass = "fa fa-dot-circle-o"}}- },+ }}},- new AdminSiteMap {+ new () {SystemName = "Content",ResourceName = "Admin.Content",PermissionNames = new List<string> { PermissionSystemName.News, PermissionSystemName.Blog,@@ -463,8 +462,8 @@ namespace Grand.Business.Core.Utilities.SystemPermissionSystemName.Knowledgebase, PermissionSystemName.Courses },IconClass = "icon-layers",DisplayOrder = 5,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Pages",ResourceName = "Admin.Content.Pages",PermissionNames = new List<string> { PermissionSystemName.Pages },@@ -473,7 +472,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Message templates",ResourceName = "Admin.Content.MessageTemplates",PermissionNames = new List<string> { PermissionSystemName.MessageTemplates },@@ -482,7 +481,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Knowledgebase",ResourceName = "Admin.Content.Knowledgebase",PermissionNames = new List<string> { PermissionSystemName.Knowledgebase },@@ -491,7 +490,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "News",ResourceName = "Admin.Content.News",PermissionNames = new List<string> { PermissionSystemName.News },@@ -500,14 +499,14 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Blog",ResourceName = "Admin.Content.Blog",PermissionNames = new List<string> { PermissionSystemName.Blog },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 4,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Blog categories",ResourceName = "Admin.Content.Blog.BlogCategories",ControllerName = "Blog",@@ -515,7 +514,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Blog posts",ResourceName = "Admin.Content.Blog.BlogPosts",ControllerName = "Blog",@@ -523,7 +522,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Blog comments",ResourceName = "Admin.Content.Blog.Comments",ControllerName = "Blog",@@ -533,14 +532,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Course",ResourceName = "Admin.Content.Course",PermissionNames = new List<string> { PermissionSystemName.Courses },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 5,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Course level",ResourceName = "Admin.Content.Course.Level",ControllerName = "Course",@@ -548,7 +547,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Manage courses",ResourceName = "Admin.Content.Course.Manage",ControllerName = "Course",@@ -560,14 +559,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Reports",ResourceName = "Admin.Reports",PermissionNames = new List<string> { PermissionSystemName.Reports, PermissionSystemName.ActivityLog },IconClass = "icon-bar-chart",DisplayOrder = 6,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Low stock report",ResourceName = "Admin.Reports.LowStockReport",PermissionNames = new List<string> { PermissionSystemName.Reports },@@ -576,7 +575,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Bestsellers",ResourceName = "Admin.Reports.Bestsellers",PermissionNames = new List<string> { PermissionSystemName.Reports },@@ -585,7 +584,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Products never purchased",ResourceName = "Admin.Reports.NeverSold",PermissionNames = new List<string> { PermissionSystemName.Reports },@@ -594,7 +593,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Country report",ResourceName = "Admin.Reports.Country",PermissionNames = new List<string> { PermissionSystemName.Reports },@@ -604,7 +603,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Customer reports",ResourceName = "Admin.Reports.Customers",PermissionNames = new List<string> { PermissionSystemName.Reports },@@ -614,7 +613,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Activity Stats",ResourceName = "Admin.Reports.ActivityLog.ActivityStats",PermissionNames = new List<string> { PermissionSystemName.ActivityLog },@@ -625,7 +624,7 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Configuration",ResourceName = "Admin.Configuration",PermissionNames = new List<string> { PermissionSystemName.Countries, PermissionSystemName.Languages, PermissionSystemName.Settings,@@ -634,8 +633,8 @@ namespace Grand.Business.Core.Utilities.SystemPermissionSystemName.ActivityLog, PermissionSystemName.Acl, PermissionSystemName.EmailAccounts, PermissionSystemName.Plugins, PermissionSystemName.Widgets, PermissionSystemName.Stores, PermissionSystemName.Maintenance },IconClass = "icon-settings",DisplayOrder = 7,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Stores",ResourceName = "Admin.Configuration.Stores",PermissionNames = new List<string> { PermissionSystemName.Stores },@@ -644,7 +643,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Permissions",ResourceName = "Admin.Configuration.Permissions",PermissionNames = new List<string> { PermissionSystemName.Acl },@@ -653,7 +652,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "EmailAccounts",ResourceName = "Admin.Configuration.EmailAccounts",PermissionNames = new List<string> { PermissionSystemName.EmailAccounts },@@ -662,7 +661,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Languages",ResourceName = "Admin.Configuration.Languages",PermissionNames = new List<string> { PermissionSystemName.Languages },@@ -671,7 +670,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Currencies",ResourceName = "Admin.Configuration.Currencies",PermissionNames = new List<string> { PermissionSystemName.Currencies },@@ -680,7 +679,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Countries",ResourceName = "Admin.Configuration.Countries",PermissionNames = new List<string> { PermissionSystemName.Countries },@@ -689,7 +688,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Search engine friendly names",ResourceName = "Admin.Configuration.SeNames",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -698,14 +697,14 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 6,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Payment",ResourceName = "Admin.Configuration.Payment",PermissionNames = new List<string> { PermissionSystemName.PaymentMethods },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 7,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Payment methods",ResourceName = "Admin.Configuration.Payment.Methods",PermissionNames = new List<string> { PermissionSystemName.PaymentMethods },@@ -714,7 +713,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Payment settings",ResourceName = "Admin.Configuration.Payment.Settings",PermissionNames = new List<string> { PermissionSystemName.PaymentMethods },@@ -723,7 +722,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Payment method restrictions",ResourceName = "Admin.Configuration.Payment.MethodRestrictions",PermissionNames = new List<string> { PermissionSystemName.PaymentMethods },@@ -734,14 +733,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Shipping",ResourceName = "Admin.Configuration.Shipping",PermissionNames = new List<string> { PermissionSystemName.ShippingSettings },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 8,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Shipping providers",ResourceName = "Admin.Configuration.Shipping.Providers",ControllerName = "Shipping",@@ -749,7 +748,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Shipping methods",ResourceName = "Admin.Configuration.Shipping.Methods",ControllerName = "Shipping",@@ -757,7 +756,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Shipping method restrictions",ResourceName = "Admin.Configuration.Shipping.Restrictions",ControllerName = "Shipping",@@ -765,7 +764,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Shipping settings",ResourceName = "Admin.Configuration.Shipping.Settings",ControllerName = "Shipping",@@ -773,16 +772,16 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Measures",ResourceName = "Admin.Configuration.Measures",PermissionNames = new List<string> { PermissionSystemName.Measures },ControllerName = "Measure",DisplayOrder = 4,ActionName = "Index",- IconClass = "fa fa-arrow-circle-o-right",+ IconClass = "fa fa-arrow-circle-o-right"},- new AdminSiteMap {+ new () {SystemName = "Delivery dates",ResourceName = "Admin.Configuration.Shipping.DeliveryDates",ControllerName = "Shipping",@@ -790,7 +789,7 @@ namespace Grand.Business.Core.Utilities.SystemActionName = "DeliveryDates",IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Warehouses",ResourceName = "Admin.Configuration.Shipping.Warehouses",ControllerName = "Shipping",@@ -798,7 +797,7 @@ namespace Grand.Business.Core.Utilities.SystemActionName = "Warehouses",IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "PickupPoints",ResourceName = "Admin.Configuration.Shipping.PickupPoints",ControllerName = "Shipping",@@ -808,14 +807,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Tax",ResourceName = "Admin.Configuration.Tax",PermissionNames = new List<string> { PermissionSystemName.TaxSettings },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 9,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Tax providers",ResourceName = "Admin.Configuration.Tax.Providers",ControllerName = "Tax",@@ -823,7 +822,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Tax categories",ResourceName = "Admin.Configuration.Tax.Categories",ControllerName = "Tax",@@ -831,7 +830,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Tax settings",ResourceName = "Admin.Configuration.Tax.Settings",ControllerName = "Tax",@@ -841,14 +840,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Templates",ResourceName = "Admin.Configuration.Layouts",PermissionNames = new List<string> { PermissionSystemName.Maintenance },IconClass = "fa fa-arrow-circle-o-right",DisplayOrder = 10,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Category layouts",ResourceName = "Admin.Configuration.Layouts.Category",ControllerName = "Layout",@@ -856,7 +855,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Brand layouts",ResourceName = "Admin.Configuration.Layouts.Brand",ControllerName = "Layout",@@ -864,7 +863,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Collection layouts",ResourceName = "Admin.Configuration.Layouts.Collection",ControllerName = "Layout",@@ -872,7 +871,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Product layouts",ResourceName = "Admin.Configuration.Layouts.Product",ControllerName = "Layout",@@ -880,7 +879,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Page layouts",ResourceName = "Admin.Configuration.Layouts.Page",ControllerName = "Layout",@@ -892,14 +891,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Settings",PermissionNames = new List<string> { PermissionSystemName.Settings, PermissionSystemName.ActivityLog },ResourceName = "Admin.Settings",IconClass = "icon-wrench",DisplayOrder = 8,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "General and common settings",ResourceName = "Admin.Settings.GeneralCommon",ControllerName = "Setting",@@ -907,7 +906,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Catalog settings",ResourceName = "Admin.Settings.Catalog",ControllerName = "Setting",@@ -915,7 +914,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Customer settings",ResourceName = "Admin.Settings.Customer",ControllerName = "Setting",@@ -923,7 +922,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Sales settings",ResourceName = "Admin.Settings.Sales",ControllerName = "Setting",@@ -931,7 +930,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Media settings",ResourceName = "Admin.Settings.Media",ControllerName = "Setting",@@ -939,7 +938,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Content settings",ResourceName = "Admin.Settings.Content",ControllerName = "Setting",@@ -947,7 +946,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Vendor settings",ResourceName = "Admin.Settings.Vendor",ControllerName = "Setting",@@ -955,7 +954,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 6,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Push notifications settings",ResourceName = "Admin.Settings.PushNotifications",ControllerName = "Setting",@@ -963,7 +962,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 7,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Admin search settings",ResourceName = "Admin.Settings.AdminSearch",ControllerName = "Setting",@@ -971,7 +970,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 8,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "System settings",ResourceName = "Admin.Settings.System",ControllerName = "Setting",@@ -979,7 +978,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 9,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Activity Types",ResourceName = "Admin.Settings.ActivityLog.ActivityLogType",PermissionNames = new List<string> { PermissionSystemName.ActivityLog },@@ -990,14 +989,14 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Plugins",ResourceName = "Admin.Plugins",PermissionNames = new List<string> { PermissionSystemName.Plugins, PermissionSystemName.Widgets, PermissionSystemName.ExternalAuthenticationMethods},IconClass = "icon-puzzle",DisplayOrder = 9,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "External authentication methods",ResourceName = "Admin.Plugins.ExternalAuthenticationMethods",PermissionNames = new List<string> { PermissionSystemName.ExternalAuthenticationMethods },@@ -1006,7 +1005,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Widgets",ResourceName = "Admin.Plugins.Widgets",PermissionNames = new List<string> { PermissionSystemName.Widgets },@@ -1015,7 +1014,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Local plugins",ResourceName = "Admin.Plugins.Local",PermissionNames = new List<string> { PermissionSystemName.Plugins },@@ -1026,15 +1025,15 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "System",ResourceName = "Admin.System",PermissionNames = new List<string> { PermissionSystemName.SystemLog, PermissionSystemName.MessageQueue, PermissionSystemName.MessageContactForm,PermissionSystemName.Maintenance, PermissionSystemName.ScheduleTasks, PermissionSystemName.System },IconClass = "icon-info",DisplayOrder = 10,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Log",ResourceName = "Admin.System.Log",PermissionNames = new List<string> { PermissionSystemName.SystemLog },@@ -1043,7 +1042,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "System information",ResourceName = "Admin.System.SystemInfo",PermissionNames = new List<string> { PermissionSystemName.System },@@ -1052,7 +1051,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Queued emails",ResourceName = "Admin.System.QueuedEmails",PermissionNames = new List<string> { PermissionSystemName.MessageQueue },@@ -1061,7 +1060,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Contact Us form",ResourceName = "Admin.System.ContactForm",PermissionNames = new List<string> { PermissionSystemName.MessageContactForm },@@ -1070,7 +1069,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Maintenance",ResourceName = "Admin.System.Maintenance",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -1079,7 +1078,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 4,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Schedule tasks",ResourceName = "Admin.System.ScheduleTasks",PermissionNames = new List<string> { PermissionSystemName.ScheduleTasks },@@ -1088,14 +1087,14 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 5,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Developer tools",ResourceName = "Admin.System.DeveloperTools",PermissionNames = new List<string> { PermissionSystemName.Maintenance, PermissionSystemName.System },IconClass = "fa fa-dot-circle-o",DisplayOrder = 6,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Manage API Users",ResourceName = "Admin.System.APIUsers",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -1104,7 +1103,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Roslyn compiler",ResourceName = "Admin.System.Roslyn",PermissionNames = new List<string> { PermissionSystemName.System },@@ -1113,7 +1112,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 1,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Custom css",ResourceName = "Admin.System.CustomCss",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -1122,7 +1121,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 2,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Custom JS",ResourceName = "Admin.System.CustomJs",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -1131,7 +1130,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 3,IconClass = "fa fa-dot-circle-o"},- new AdminSiteMap {+ new () {SystemName = "Robot.txt",ResourceName = "Admin.System.RobotsTxt",PermissionNames = new List<string> { PermissionSystemName.Maintenance },@@ -1144,13 +1143,13 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Help",ResourceName = "Admin.Help",IconClass = "icon-question",DisplayOrder = 11,- ChildNodes = new List<AdminSiteMap>() {- new AdminSiteMap {+ ChildNodes = new List<AdminSiteMap> {+ new () {SystemName = "Community forums",ResourceName = "Admin.Help.Forums",Url = "https://grandnode.com/boards?utm_source=web&utm_medium=admin&utm_term=web&utm_campaign=Community",@@ -1158,7 +1157,7 @@ namespace Grand.Business.Core.Utilities.SystemDisplayOrder = 0,OpenUrlInNewTab = true},- new AdminSiteMap {+ new () {SystemName = "Premium support services",ResourceName = "Admin.Help.SupportServices",Url = "https://grandnode.com/premium-support-packages?utm_source=web&utm_medium=admin&utm_term=web&utm_campaign=Support",@@ -1168,12 +1167,12 @@ namespace Grand.Business.Core.Utilities.System}}},- new AdminSiteMap {+ new () {SystemName = "Third party plugins",ResourceName = "Admin.Plugins",- DisplayOrder = 12,+ DisplayOrder = 12}};- };+ }}\ No newline at end of filediff --git a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.csindex a7c15a030..e61cb391b 100644--- a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs+++ b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs@@ -38,28 +38,23 @@ namespace Grand.Business.Customers.Commands.Handlersforeach (var item in request.CustomerIds){var customer = await _customerService.GetCustomerById(item);- if (customer != null && !customer.Deleted && customer.Active && !customer.IsSystemAccount() &&- !await _groupService.IsAdmin(customer)- )+ if (customer is not { Deleted: false, Active: true } || customer.IsSystemAccount() ||+ await _groupService.IsAdmin(customer)) continue;+ if (vendorGroup == null) continue;+ if (request.Active){- if (vendorGroup != null)- {- if (request.Active)- {- if (!await _groupService.IsVendor(customer))- await _customerService.InsertCustomerGroupInCustomer(vendorGroup, item);- }- else- {- if (await _groupService.IsVendor(customer))- await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, item);- }- }+ if (!await _groupService.IsVendor(customer))+ await _customerService.InsertCustomerGroupInCustomer(vendorGroup, item);+ }+ else+ {+ if (await _groupService.IsVendor(customer))+ await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, item);}}//raise event- await _mediator.Publish(new VendorActivationEvent(request.Vendor));+ await _mediator.Publish(new VendorActivationEvent(request.Vendor), cancellationToken);return true;}diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.csindex 7b5a1ab0c..508df354f 100644--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs@@ -35,9 +35,9 @@ namespace Grand.Business.Customers.Queries.Handlersquery = query.Where(c => c.SeId == request.SalesEmployeeId);query = query.Where(c => !c.Deleted);- if (request.CustomerGroupIds != null && request.CustomerGroupIds.Length > 0)+ if (request.CustomerGroupIds is { Length: > 0 })query = query.Where(c => c.Groups.Any(x => request.CustomerGroupIds.Contains(x)));- if (request.CustomerTagIds != null && request.CustomerTagIds.Length > 0)+ if (request.CustomerTagIds is { Length: > 0 }){foreach (var item in request.CustomerTagIds){@@ -79,7 +79,7 @@ namespace Grand.Business.Customers.Queries.Handlers{query = request.Sct.HasValue ?query.Where(c => c.ShoppingCartItems.Any(x => x.ShoppingCartTypeId == request.Sct.Value)) :- query.Where(c => c.ShoppingCartItems.Count() > 0);+ query.Where(c => c.ShoppingCartItems.Any());}if (request.OrderBySelector == null)@@ -95,13 +95,10 @@ namespace Grand.Business.Customers.Queries.Handlersprivate string GetName(Expression<Func<Customer, object>> exp){- var body = exp.Body as MemberExpression;- if (body == null)- {- var ubody = (UnaryExpression)exp.Body;- body = ubody.Operand as MemberExpression;- }- return body.Member.Name;+ if (exp.Body is MemberExpression body) return body.Member.Name;+ var expBody = (UnaryExpression)exp.Body;+ body = expBody.Operand as MemberExpression;+ return body?.Member.Name;}private IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName)diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.csindex 06cc144bb..9b4ed1b8a 100644--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Customers.Queries.Handlerspublic async Task<CustomerGroup> Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken){if (string.IsNullOrEmpty(request.SystemName))- throw new ArgumentNullException("Request.SystemName");+ throw new ArgumentNullException(nameof(request.SystemName));return await _groupService.GetCustomerGroupBySystemName(request.SystemName);}diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.csindex 33c574f70..688cbe153 100644--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs@@ -34,12 +34,8 @@ namespace Grand.Business.Customers.Queries.Handlers//setting disabled for allif (_customerSettings.PasswordLifetime == 0)return false;-- var currentLifetime = 0;- if (!request.Customer.PasswordChangeDateUtc.HasValue)- currentLifetime = int.MaxValue;- else- currentLifetime = (DateTime.UtcNow - request.Customer.PasswordChangeDateUtc.Value).Days;++ var currentLifetime = !request.Customer.PasswordChangeDateUtc.HasValue ? int.MaxValue : (DateTime.UtcNow - request.Customer.PasswordChangeDateUtc.Value).Days;return currentLifetime >= _customerSettings.PasswordLifetime;}diff --git a/src/Business/Grand.Business.Customers/Services/AddressSchemaProperty.cs b/src/Business/Grand.Business.Customers/Services/AddressSchemaProperty.csindex b5e23106b..039b6b37d 100644--- a/src/Business/Grand.Business.Customers/Services/AddressSchemaProperty.cs+++ b/src/Business/Grand.Business.Customers/Services/AddressSchemaProperty.cs@@ -26,7 +26,7 @@ namespace Grand.Business.Customers.Servicesnew PropertyByName<Address>("Address1", p=>p.Address1),new PropertyByName<Address>("Address2", p=>p.Address2),new PropertyByName<Address>("City", p=>p.City),- new PropertyByName<Address>("Country", p=> !string.IsNullOrEmpty(p.CountryId) ? _countryService.GetCountryById(p.CountryId).Result?.Name : ""),+ new PropertyByName<Address>("Country", p=> !string.IsNullOrEmpty(p.CountryId) ? _countryService.GetCountryById(p.CountryId).Result?.Name : "")};return properties;}diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.csindex 7300b94f7..712085ced 100644--- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs+++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Affiliate service/// </summary>- public partial class AffiliateService : IAffiliateService+ public class AffiliateService : IAffiliateService{#region Fields@@ -80,11 +80,11 @@ namespace Grand.Business.Customers.Servicesvar query = from p in _affiliateRepository.Tableselect p;- if (!String.IsNullOrWhiteSpace(friendlyUrlName))+ if (!string.IsNullOrWhiteSpace(friendlyUrlName))query = query.Where(a => a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant()));- if (!String.IsNullOrWhiteSpace(firstName))+ if (!string.IsNullOrWhiteSpace(firstName))query = query.Where(a => a.Address.FirstName != null && a.Address.FirstName.ToLower().Contains(firstName.ToLower()));- if (!String.IsNullOrWhiteSpace(lastName))+ if (!string.IsNullOrWhiteSpace(lastName))query = query.Where(a => a.Address.LastName != null && a.Address.LastName.ToLower().Contains(lastName.ToLower()));if (!showHidden)query = query.Where(a => a.Active);diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.csindex 028d76094..51e3ec1b9 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs@@ -13,7 +13,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Customer attribute parser/// </summary>- public partial class CustomerAttributeParser : ICustomerAttributeParser+ public class CustomerAttributeParser : ICustomerAttributeParser{private readonly ICustomerAttributeService _customerAttributeService;private readonly ITranslationService _translationService;@@ -65,15 +65,7 @@ namespace Grand.Business.Customers.Servicescontinue;var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- foreach (string valueStr in valuesStr)- {- if (!string.IsNullOrEmpty(valueStr))- {- var value = attribute.CustomerAttributeValues.FirstOrDefault(x => x.Id == valueStr);- if (value != null)- values.Add(value);- }- }+ values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr) select attribute.CustomerAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);}return values;}@@ -88,11 +80,8 @@ namespace Grand.Business.Customers.Services/// <returns>Attributes</returns>public virtual IList<CustomAttribute> AddCustomerAttribute(IList<CustomAttribute> customAttributes, CustomerAttribute ca, string value){- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();-- customAttributes.Add(new CustomAttribute() { Key = ca.Id, Value = value });-+ customAttributes ??= new List<CustomAttribute>();+ customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });return customAttributes;}@@ -115,34 +104,24 @@ namespace Grand.Business.Customers.Servicesvar attributes2 = await _customerAttributeService.GetAllCustomerAttributes();foreach (var a2 in attributes2){- if (a2.IsRequired)+ if (!a2.IsRequired) continue;+ var found = false;+ //selected customer attributes+ foreach (var a1 in attributes1){- bool found = false;- //selected customer attributes- foreach (var a1 in attributes1)+ if (a1.Id != a2.Id) continue;+ var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);+ if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))){- if (a1.Id == a2.Id)- {- var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);- foreach (var str1 in valuesStr)- {- if (!string.IsNullOrEmpty(str1.Trim()))- {- found = true;- break;- }- }- }+ found = true;}+ }- //if not found- if (!found)- {- var notFoundWarning = string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetTranslation(a => a.Name, ""));+ //if not found+ if (found) continue;+ var notFoundWarning = string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetTranslation(a => a.Name, ""));- warnings.Add(notFoundWarning);- }- }+ warnings.Add(notFoundWarning);}return warnings;@@ -153,16 +132,16 @@ namespace Grand.Business.Customers.Services/// </summary>/// <param name="language">Language</param>/// <param name="customAttributes">Attributes</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(Language language,- IList<CustomAttribute> customAttributes, string serapator = "<br />", bool htmlEncode = true)+ IList<CustomAttribute> customAttributes, string separator = "<br />", bool htmlEncode = true){var result = new StringBuilder();var attributes = await ParseCustomerAttributes(customAttributes);- for (int i = 0; i < attributes.Count; i++)+ for (var i = 0; i < attributes.Count; i++){var attribute = attributes[i];var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();@@ -175,13 +154,13 @@ namespace Grand.Business.Customers.Services//no valuesif (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox){- //multiline textbox+ //multiline text boxvar attributeName = attribute.GetTranslation(a => a.Name, language.Id);//encode (if required)if (htmlEncode)attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));- //we never encode multiline textbox input+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input}else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload){@@ -190,8 +169,8 @@ namespace Grand.Business.Customers.Services}else{- //other attributes (textbox, datepicker)- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), valueStr);+ //other attributes (text box, datepicker)+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);@@ -200,24 +179,22 @@ namespace Grand.Business.Customers.Serviceselse{- string attributeValueId = valueStr;+ var attributeValueId = valueStr;var attributeValue = attribute.CustomerAttributeValues.FirstOrDefault(x => x.Id == attributeValueId);if (attributeValue != null){- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), attributeValue.GetTranslation(a => a.Name, language.Id));+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";}//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}-- if (!string.IsNullOrEmpty(formattedAttribute))- {- if (i != 0 || j != 0)- result.Append(serapator);- result.Append(formattedAttribute);- }+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}}diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.csindex 82a342812..b155bc0df 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs@@ -11,7 +11,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Customer attribute service/// </summary>- public partial class CustomerAttributeService : ICustomerAttributeService+ public class CustomerAttributeService : ICustomerAttributeService{#region Fields@@ -48,7 +48,7 @@ namespace Grand.Business.Customers.Services/// <returns>Customer attributes</returns>public virtual async Task<IList<CustomerAttribute>> GetAllCustomerAttributes(){- string key = CacheKey.CUSTOMERATTRIBUTES_ALL_KEY;+ var key = CacheKey.CUSTOMERATTRIBUTES_ALL_KEY;return await _cacheBase.GetAsync(key, async () =>{var query = from ca in _customerAttributeRepository.Table@@ -65,7 +65,7 @@ namespace Grand.Business.Customers.Services/// <returns>Customer attribute</returns>public virtual Task<CustomerAttribute> GetCustomerAttributeById(string customerAttributeId){- string key = string.Format(CacheKey.CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId);+ var key = string.Format(CacheKey.CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId);return _cacheBase.GetAsync(key, () => _customerAttributeRepository.GetByIdAsync(customerAttributeId));}diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.csindex 3d7f639ac..3a70903a7 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs@@ -15,7 +15,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Customer manager service/// </summary>- public partial class CustomerManagerService : ICustomerManagerService+ public class CustomerManagerService : ICustomerManagerService{#region Fields@@ -66,13 +66,13 @@ namespace Grand.Business.Customers.Services#region Methods- protected bool PasswordMatch(CustomerHistoryPassword customerPassword, ChangePasswordRequest request)+ private bool PasswordMatch(CustomerHistoryPassword customerPassword, ChangePasswordRequest request){- string newPwd = request.PasswordFormat switch {+ var newPwd = request.PasswordFormat switch {PasswordFormat.Clear => request.NewPassword,PasswordFormat.Encrypted => _encryptionService.EncryptText(request.NewPassword, customerPassword.PasswordSalt),PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(request.NewPassword, customerPassword.PasswordSalt, _customerSettings.HashedPasswordFormat),- _ => throw new Exception("PasswordFormat not supported"),+ _ => throw new Exception("PasswordFormat not supported")};return customerPassword.Password.Equals(newPwd);}@@ -102,11 +102,11 @@ namespace Grand.Business.Customers.Servicesif (string.IsNullOrEmpty(password))return CustomerLoginResults.WrongPassword;- string pwd = customer.PasswordFormatId switch {+ var pwd = customer.PasswordFormatId switch {PasswordFormat.Clear => password,PasswordFormat.Encrypted => _encryptionService.EncryptText(password, customer.PasswordSalt),PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(password, customer.PasswordSalt, _customerSettings.HashedPasswordFormat),- _ => throw new Exception("PasswordFormat not supported"),+ _ => throw new Exception("PasswordFormat not supported")};var isValid = pwd == customer.Password;if (!isValid)@@ -218,7 +218,7 @@ namespace Grand.Business.Customers.Servicesrequest.Customer.Password = _encryptionService.EncryptText(request.Password, request.Customer.PasswordSalt);break;case PasswordFormat.Hashed:- string saltKey = _encryptionService.CreateSaltKey(5);+ var saltKey = _encryptionService.CreateSaltKey(5);request.Customer.PasswordSalt = saltKey;request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);break;@@ -237,12 +237,12 @@ namespace Grand.Business.Customers.Servicesrequest.Customer.Groups.Add(registeredRole.Id);await _customerService.InsertCustomerGroupInCustomer(registeredRole, request.Customer.Id);//remove from 'Guests' role- var guestgroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests);- var guestexists = request.Customer.Groups.FirstOrDefault(cr => cr == guestgroup.Id);- if (guestexists != null)+ var guestGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests);+ var guestExists = request.Customer.Groups.FirstOrDefault(cr => cr == guestGroup?.Id);+ if (guestExists != null){- request.Customer.Groups.Remove(guestgroup.Id);- await _customerService.DeleteCustomerGroupInCustomer(guestgroup, request.Customer.Id);+ request.Customer.Groups.Remove(guestGroup.Id);+ await _customerService.DeleteCustomerGroupInCustomer(guestGroup, request.Customer.Id);}request.Customer.PasswordChangeDateUtc = DateTime.UtcNow;@@ -262,12 +262,12 @@ namespace Grand.Business.Customers.Servicesthrow new ArgumentNullException(nameof(request));var result = new ChangePasswordResult();- if (String.IsNullOrWhiteSpace(request.Email))+ if (string.IsNullOrWhiteSpace(request.Email)){result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.EmailIsNotProvided"));return result;}- if (String.IsNullOrWhiteSpace(request.NewPassword))+ if (string.IsNullOrWhiteSpace(request.NewPassword)){result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.PasswordIsNotProvided"));return result;@@ -282,19 +282,13 @@ namespace Grand.Business.Customers.Servicesif (request.ValidOldPassword){- string oldPwd = "";- switch (customer.PasswordFormatId)- {- case PasswordFormat.Encrypted:- oldPwd = _encryptionService.EncryptText(request.OldPassword, customer.PasswordSalt);- break;- case PasswordFormat.Hashed:- oldPwd = _encryptionService.CreatePasswordHash(request.OldPassword, customer.PasswordSalt, _customerSettings.HashedPasswordFormat);- break;- default:- oldPwd = request.OldPassword;- break;- }+ var oldPwd = customer.PasswordFormatId switch {+ PasswordFormat.Encrypted => _encryptionService.EncryptText(request.OldPassword,+ customer.PasswordSalt),+ PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(request.OldPassword,+ customer.PasswordSalt, _customerSettings.HashedPasswordFormat),+ _ => request.OldPassword+ };if (oldPwd != customer.Password){@@ -332,7 +326,7 @@ namespace Grand.Business.Customers.Servicesbreak;case PasswordFormat.Hashed:{- string saltKey = _encryptionService.CreateSaltKey(5);+ var saltKey = _encryptionService.CreateSaltKey(5);customer.PasswordSalt = saltKey;customer.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey, _customerSettings.HashedPasswordFormat);}diff --git a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.csindex 3682a2dbd..290fd40cb 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs@@ -20,17 +20,14 @@ namespace Grand.Business.Customers.Services#region Customer note- // <summary>+ /// <summary>/// Get note for customer/// </summary>/// <param name="id">Note identifier</param>/// <returns>CustomerNote</returns>public virtual Task<CustomerNote> GetCustomerNote(string id){- if (string.IsNullOrWhiteSpace(id))- return Task.FromResult<CustomerNote>(null);-- return _customerNoteRepository.GetByIdAsync(id);+ return string.IsNullOrWhiteSpace(id) ? Task.FromResult<CustomerNote>(null) : _customerNoteRepository.GetByIdAsync(id);}/// <summary>@@ -67,16 +64,16 @@ namespace Grand.Business.Customers.Services/// Get notes for customer/// </summary>/// <param name="customerId">Customer identifier</param>- /// <param name="displaytocustomer">Display to customer</param>+ /// <param name="displayToCustomer">Display to customer</param>/// <returns>OrderNote</returns>- public virtual async Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displaytocustomer = null)+ public virtual async Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displayToCustomer = null){var query = from customerNote in _customerNoteRepository.Tablewhere customerNote.CustomerId == customerIdselect customerNote;- if (displaytocustomer.HasValue)- query = query.Where(x => x.DisplayToCustomer == displaytocustomer.Value);+ if (displayToCustomer.HasValue)+ query = query.Where(x => x.DisplayToCustomer == displayToCustomer.Value);query = query.OrderByDescending(x => x.CreatedOnUtc);diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.csindex 372cbc261..247db9023 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs@@ -18,7 +18,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Customer service/// </summary>- public partial class CustomerService : ICustomerService+ public class CustomerService : ICustomerService{#region Fields@@ -55,19 +55,19 @@ namespace Grand.Business.Customers.Services/// <param name="ownerId">Owner identifier</param>/// <param name="salesEmployeeId">Sales employee identifier</param>/// <param name="customerGroupIds">A list of customer group identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param>+ /// <param name="customerTagIds">customer tags ids</param>/// <param name="email">Email; null to load all customers</param>/// <param name="username">Username; null to load all customers</param>/// <param name="firstName">First name; null to load all customers</param>/// <param name="lastName">Last name; null to load all customers</param>- /// <param name="dayOfBirth">Day of birth; 0 to load all customers</param>- /// <param name="monthOfBirth">Month of birth; 0 to load all customers</param>/// <param name="company">Company; null to load all customers</param>/// <param name="phone">Phone; null to load all customers</param>/// <param name="zipPostalCode">Phone; null to load all customers</param>/// <param name="loadOnlyWithShoppingCart">Value indicating whether to load customers only with shopping cart</param>- /// <param name="sct">Value indicating what shopping cart type to filter; userd when 'loadOnlyWithShoppingCart' param is 'true'</param>+ /// <param name="sct">Value indicating what shopping cart type to filter; used when 'loadOnlyWithShoppingCart' param is 'true'</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>+ /// <param name="orderBySelector">order by selector</param>/// <returns>Customers</returns>public virtual async Task<IPagedList<Customer>> GetAllCustomers(DateTime? createdFromUtc = null,DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "", string ownerId = "",@@ -77,7 +77,7 @@ namespace Grand.Business.Customers.Servicesbool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null,int pageIndex = 0, int pageSize = 2147483647, Expression<Func<Customer, object>> orderBySelector = null){- var querymodel = new GetCustomerQuery() {+ var queryModel = new GetCustomerQuery {CreatedFromUtc = createdFromUtc,CreatedToUtc = createdToUtc,AffiliateId = affiliateId,@@ -100,7 +100,7 @@ namespace Grand.Business.Customers.ServicesPageSize = pageSize,OrderBySelector = orderBySelector};- var query = await _mediator.Send(querymodel);+ var query = await _mediator.Send(queryModel);return await PagedList<Customer>.Create(query, pageIndex, pageSize);}@@ -124,7 +124,7 @@ namespace Grand.Business.Customers.Servicesquery = query.Where(c => lastActivityFromUtc <= c.LastActivityDateUtc);query = query.Where(c => !c.Deleted);- if (customerGroupIds != null && customerGroupIds.Length > 0)+ if (customerGroupIds is { Length: > 0 })query = query.Where(c => c.Groups.Select(cr => cr).Intersect(customerGroupIds).Any());if (!string.IsNullOrEmpty(storeId))@@ -169,10 +169,7 @@ namespace Grand.Business.Customers.Services/// <returns>A customer</returns>public virtual Task<Customer> GetCustomerById(string customerId){- if (string.IsNullOrWhiteSpace(customerId))- return Task.FromResult<Customer>(null);-- return _customerRepository.GetByIdAsync(customerId);+ return string.IsNullOrWhiteSpace(customerId) ? Task.FromResult<Customer>(null) : _customerRepository.GetByIdAsync(customerId);}/// <summary>@@ -190,13 +187,7 @@ namespace Grand.Business.Customers.Servicesselect c;var customers = query.ToList();//sort by passed identifiers- var sortedCustomers = new List<Customer>();- foreach (var id in customerIds)- {- var customer = customers.Find(x => x.Id == id);- if (customer != null)- sortedCustomers.Add(customer);- }+ var sortedCustomers = customerIds.Select(id => customers.Find(x => x.Id == id)).Where(customer => customer != null).ToList();return await Task.FromResult(sortedCustomers);}@@ -207,7 +198,7 @@ namespace Grand.Business.Customers.Services/// <returns>A customer</returns>public virtual async Task<Customer> GetCustomerByGuid(Guid customerGuid){- return await Task.FromResult(_customerRepository.Table.Where(x => x.CustomerGuid == customerGuid).FirstOrDefault());+ return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.CustomerGuid == customerGuid));}/// <summary>@@ -220,7 +211,7 @@ namespace Grand.Business.Customers.Servicesif (string.IsNullOrWhiteSpace(email))return null;- return await Task.FromResult(_customerRepository.Table.Where(x => x.Email == email.ToLowerInvariant()).FirstOrDefault());+ return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant()));}/// <summary>@@ -233,7 +224,7 @@ namespace Grand.Business.Customers.Servicesif (string.IsNullOrWhiteSpace(systemName))return null;- return await Task.FromResult(_customerRepository.Table.Where(x => x.SystemName == systemName).FirstOrDefault());+ return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.SystemName == systemName));}/// <summary>@@ -246,7 +237,7 @@ namespace Grand.Business.Customers.Servicesif (string.IsNullOrWhiteSpace(username))return null;- return await Task.FromResult(_customerRepository.Table.Where(x => x.Username == username.ToLowerInvariant()).FirstOrDefault());+ return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.Username == username.ToLowerInvariant()));}/// <summary>@@ -260,11 +251,10 @@ namespace Grand.Business.Customers.ServicesActive = true,StoreId = store.Id,CreatedOnUtc = DateTime.UtcNow,- LastActivityDateUtc = DateTime.UtcNow,+ LastActivityDateUtc = DateTime.UtcNow};-//add to 'Guests' group- var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery() { SystemName = SystemCustomerGroupNames.Guests });+ var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery { SystemName = SystemCustomerGroupNames.Guests });if (guestGroup == null)throw new GrandException("'Guests' group could not be loaded");customer.Groups.Add(guestGroup.Id);@@ -302,6 +292,8 @@ namespace Grand.Business.Customers.Services/// Updates the customer field/// </summary>/// <param name="customer">Customer</param>+ /// <param name="expression">expression</param>+ /// <param name="value">value</param>public virtual async Task UpdateCustomerField<T>(Customer customer,Expression<Func<Customer, T>> expression, T value){@@ -316,13 +308,15 @@ namespace Grand.Business.Customers.Services/// Updates the customer field/// </summary>/// <param name="customerId">Customer ident</param>+ /// <param name="expression">Expression</param>+ /// <param name="value">value</param>public virtual async Task UpdateCustomerField<T>(string customerId,Expression<Func<Customer, T>> expression, T value){if (string.IsNullOrEmpty(customerId))throw new ArgumentNullException(nameof(customerId));- await _customerRepository.UpdateField<T>(customerId, expression, value);+ await _customerRepository.UpdateField(customerId, expression, value);}/// <summary>@@ -413,7 +407,7 @@ namespace Grand.Business.Customers.Services}- public virtual async Task UpdateCustomerinAdminPanel(Customer customer)+ public virtual async Task UpdateCustomerInAdminPanel(Customer customer){if (customer == null)throw new ArgumentNullException(nameof(customer));@@ -536,7 +530,7 @@ namespace Grand.Business.Customers.Services/// <returns>Number of deleted customers</returns>public virtual async Task<int> DeleteGuestCustomers(DateTime? createdFromUtc, DateTime? createdToUtc, bool onlyWithoutShoppingCart){- var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery() { SystemName = SystemCustomerGroupNames.Guests });+ var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery { SystemName = SystemCustomerGroupNames.Guests });if (guestGroup == null)throw new GrandException("Guests group could not be loaded");@@ -687,7 +681,7 @@ namespace Grand.Business.Customers.Servicesawait _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, item.Id);}- if (cart.Any(c => c.ShoppingCartTypeId == ShoppingCartType.ShoppingCart || c.ShoppingCartTypeId == ShoppingCartType.Auctions))+ if (cart.Any(c => c.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions))await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);if (cart.Any(c => c.ShoppingCartTypeId == ShoppingCartType.Wishlist))await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);diff --git a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.csindex 8ab2ed2ca..10f77bed6 100644--- a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs+++ b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs@@ -35,7 +35,7 @@ namespace Grand.Business.Customers.Services/// <returns>SalesEmployee</returns>public virtual Task<SalesEmployee> GetSalesEmployeeById(string salesEmployeeId){- string key = string.Format(CacheKey.SALESEMPLOYEE_BY_ID_KEY, salesEmployeeId);+ var key = string.Format(CacheKey.SALESEMPLOYEE_BY_ID_KEY, salesEmployeeId);return _cacheBase.GetAsync(key, () => _salesEmployeeRepository.GetByIdAsync(salesEmployeeId));}@@ -93,7 +93,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Deletes a sales employee/// </summary>- /// <param name="warehouse">The sales employee</param>+ /// <param name="salesEmployee">The sales employee</param>public virtual async Task DeleteSalesEmployee(SalesEmployee salesEmployee){if (salesEmployee == null)diff --git a/src/Business/Grand.Business.Customers/Services/UserApiService.cs b/src/Business/Grand.Business.Customers/Services/UserApiService.csindex 143486f1a..857e0cfe2 100644--- a/src/Business/Grand.Business.Customers/Services/UserApiService.cs+++ b/src/Business/Grand.Business.Customers/Services/UserApiService.cs@@ -7,7 +7,7 @@ using MediatR;namespace Grand.Business.Customers.Services{- public partial class UserApiService : IUserApiService+ public class UserApiService : IUserApiService{#region Fields@@ -33,10 +33,10 @@ namespace Grand.Business.Customers.Services/// <summary>/// Get user api by email/// </summary>- /// <param name="id">id</param>+ /// <param name="email">email</param>public virtual async Task<UserApi> GetUserByEmail(string email){- return await Task.FromResult(_userRepository.Table.Where(x => x.Email == email.ToLowerInvariant()).FirstOrDefault());+ return await Task.FromResult(_userRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant()));}/// <summary>@@ -82,7 +82,6 @@ namespace Grand.Business.Customers.Services/// <param name="email"></param>/// <param name="pageIndex"></param>/// <param name="pageSize"></param>- /// <returns>PagedList<UserApi></returns>public virtual async Task<IPagedList<UserApi>> GetUsers(string email = "", int pageIndex = 0, int pageSize = 2147483647){var query = from p in _userRepository.Tablediff --git a/src/Business/Grand.Business.Customers/Services/VendorService.cs b/src/Business/Grand.Business.Customers/Services/VendorService.csindex cf45a2769..4e95dda4d 100644--- a/src/Business/Grand.Business.Customers/Services/VendorService.cs+++ b/src/Business/Grand.Business.Customers/Services/VendorService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Customers.Services/// <summary>/// Vendor service/// </summary>- public partial class VendorService : IVendorService+ public class VendorService : IVendorService{#region Fields@@ -26,6 +26,7 @@ namespace Grand.Business.Customers.Services/// Ctor/// </summary>/// <param name="vendorRepository">Vendor repository</param>+ /// <param name="vendorReviewRepository">Vendor review repository</param>/// <param name="mediator">Mediator</param>public VendorService(IRepository<Vendor> vendorRepository, IRepository<VendorReview> vendorReviewRepository,IMediator mediator)@@ -63,7 +64,7 @@ namespace Grand.Business.Customers.Servicesvar query = from p in _vendorRepository.Tableselect p;- if (!String.IsNullOrWhiteSpace(name))+ if (!string.IsNullOrWhiteSpace(name))query = query.Where(v => v.Name.ToLower().Contains(name.ToLower()));if (!showHidden)query = query.Where(v => v.Active);@@ -119,17 +120,15 @@ namespace Grand.Business.Customers.Services/// <summary>/// Gets a vendor note note/// </summary>+ /// <param name="vendorId">Vendor ident</param>/// <param name="vendorNoteId">The vendor note identifier</param>/// <returns>Vendor note</returns>public virtual async Task<VendorNote> GetVendorNoteById(string vendorId, string vendorNoteId){- if (String.IsNullOrEmpty(vendorNoteId))+ if (string.IsNullOrEmpty(vendorNoteId))return null;var vendor = await _vendorRepository.GetByIdAsync(vendorId);- if (vendor == null)- return null;-- return vendor.VendorNotes.FirstOrDefault(x => x.Id == vendorNoteId);+ return vendor?.VendorNotes.FirstOrDefault(x => x.Id == vendorNoteId);}/// <summary>/// Insert vendor note@@ -187,6 +186,9 @@ namespace Grand.Business.Customers.Services/// <param name="fromUtc">Item creation from; null to load all records</param>/// <param name="toUtc">Item item creation to; null to load all records</param>/// <param name="message">Search title or review text; null to load all records</param>+ /// <param name="vendorId"></param>+ /// <param name="pageIndex"></param>+ /// <param name="pageSize"></param>/// <returns>Reviews</returns>public virtual async Task<IPagedList<VendorReview>> GetAllVendorReviews(string customerId, bool? approved,DateTime? fromUtc = null, DateTime? toUtc = null,@@ -197,15 +199,15 @@ namespace Grand.Business.Customers.Servicesif (approved.HasValue)query = query.Where(c => c.IsApproved == approved.Value);- if (!String.IsNullOrEmpty(customerId))+ if (!string.IsNullOrEmpty(customerId))query = query.Where(c => c.CustomerId == customerId);if (fromUtc.HasValue)query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);if (toUtc.HasValue)query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);- if (!String.IsNullOrEmpty(message))+ if (!string.IsNullOrEmpty(message))query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));- if (!String.IsNullOrEmpty(vendorId))+ if (!string.IsNullOrEmpty(vendorId))query = query.Where(c => c.VendorId == vendorId);query = query.OrderByDescending(c => c.CreatedOnUtc);return await PagedList<VendorReview>.Create(query, pageIndex, pageSize);@@ -221,10 +223,10 @@ namespace Grand.Business.Customers.Servicesif (vendor == null)throw new ArgumentNullException(nameof(vendor));- int approvedRatingSum = 0;- int notApprovedRatingSum = 0;- int approvedTotalReviews = 0;- int notApprovedTotalReviews = 0;+ var approvedRatingSum = 0;+ var notApprovedRatingSum = 0;+ var approvedTotalReviews = 0;+ var notApprovedTotalReviews = 0;var reviews = _vendorReviewRepository.Table.Where(x => x.VendorId == vendor.Id);foreach (var pr in reviews){@@ -257,22 +259,22 @@ namespace Grand.Business.Customers.Servicesawait _mediator.EntityUpdated(vendor);}- public virtual async Task UpdateVendorReview(VendorReview vendorreview)+ public virtual async Task UpdateVendorReview(VendorReview vendorReview){- if (vendorreview == null)- throw new ArgumentNullException(nameof(vendorreview));+ if (vendorReview == null)+ throw new ArgumentNullException(nameof(vendorReview));var update = UpdateBuilder<VendorReview>.Create()- .Set(x => x.Title, vendorreview.Title)- .Set(x => x.ReviewText, vendorreview.ReviewText)- .Set(x => x.IsApproved, vendorreview.IsApproved)- .Set(x => x.HelpfulYesTotal, vendorreview.HelpfulYesTotal)- .Set(x => x.HelpfulNoTotal, vendorreview.HelpfulNoTotal);+ .Set(x => x.Title, vendorReview.Title)+ .Set(x => x.ReviewText, vendorReview.ReviewText)+ .Set(x => x.IsApproved, vendorReview.IsApproved)+ .Set(x => x.HelpfulYesTotal, vendorReview.HelpfulYesTotal)+ .Set(x => x.HelpfulNoTotal, vendorReview.HelpfulNoTotal);- await _vendorReviewRepository.UpdateOneAsync(x => x.Id == vendorreview.Id, update);+ await _vendorReviewRepository.UpdateOneAsync(x => x.Id == vendorReview.Id, update);//event notification- await _mediator.EntityUpdated(vendorreview);+ await _mediator.EntityUpdated(vendorReview);}/// <summary>diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.csindex c1e3f9ec9..832b0b90d 100644--- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs@@ -13,7 +13,7 @@ using MediatR;namespace Grand.Business.Marketing.Services.Campaigns{- public partial class CampaignService : ICampaignService+ public class CampaignService : ICampaignService{private readonly IRepository<Campaign> _campaignRepository;private readonly IRepository<CampaignHistory> _campaignHistoryRepository;@@ -67,13 +67,13 @@ namespace Grand.Business.Marketing.Services.Campaigns/// <summary>/// Inserts a campaign history/// </summary>- /// <param name="campaign">Campaign</param>- public virtual async Task InsertCampaignHistory(CampaignHistory campaignhistory)+ /// <param name="campaignHistory">Campaign</param>+ public virtual async Task InsertCampaignHistory(CampaignHistory campaignHistory){- if (campaignhistory == null)- throw new ArgumentNullException(nameof(campaignhistory));+ if (campaignHistory == null)+ throw new ArgumentNullException(nameof(campaignHistory));- await _campaignHistoryRepository.InsertAsync(campaignhistory);+ await _campaignHistoryRepository.InsertAsync(campaignHistory);}@@ -147,19 +147,19 @@ namespace Grand.Business.Marketing.Services.Campaignsif (campaign == null)throw new ArgumentNullException(nameof(campaign));- var model = new PagedList<NewsLetterSubscription>();+ PagedList<NewsLetterSubscription> model;if (campaign.CustomerCreatedDateFrom.HasValue || campaign.CustomerCreatedDateTo.HasValue ||- campaign.CustomerHasShoppingCart != CampaignCondition.All || campaign.CustomerHasShoppingCart != CampaignCondition.All ||+ campaign.CustomerHasShoppingCart is not (CampaignCondition.All and CampaignCondition.All) ||campaign.CustomerLastActivityDateFrom.HasValue || campaign.CustomerLastActivityDateTo.HasValue ||campaign.CustomerLastPurchaseDateFrom.HasValue || campaign.CustomerLastPurchaseDateTo.HasValue ||campaign.CustomerTags.Count > 0 || campaign.CustomerGroups.Count > 0){var query = from o in _newsLetterSubscriptionRepository.Table- where o.Active && o.CustomerId != "" && (o.StoreId == campaign.StoreId || String.IsNullOrEmpty(campaign.StoreId))+ where o.Active && o.CustomerId != "" && (o.StoreId == campaign.StoreId || string.IsNullOrEmpty(campaign.StoreId))join c in _customerRepository.Table on o.CustomerId equals c.Id into joinedfrom customers in joined- select new CampaignCustomerHelp() {+ select new CampaignCustomerHelp {CustomerEmail = customers.Email,Email = o.Email,CustomerId = customers.Id,@@ -227,7 +227,7 @@ namespace Grand.Business.Marketing.Services.Campaignsquery = query.Where(x => x.NewsletterCategories.Contains(item));}}- model = await PagedList<NewsLetterSubscription>.Create(query.Select(x => new NewsLetterSubscription() { CustomerId = x.CustomerId, Email = x.Email, NewsLetterSubscriptionGuid = x.NewsLetterSubscriptionGuid }), pageIndex, pageSize);+ model = await PagedList<NewsLetterSubscription>.Create(query.Select(x => new NewsLetterSubscription { CustomerId = x.CustomerId, Email = x.Email, NewsLetterSubscriptionGuid = x.NewsLetterSubscriptionGuid }), pageIndex, pageSize);}else{@@ -284,26 +284,22 @@ namespace Grand.Business.Marketing.Services.Campaignsif (emailAccount == null)throw new ArgumentNullException(nameof(emailAccount));- int totalEmailsSent = 0;- var language = await _languageService.GetLanguageById(campaign.LanguageId);- if (language == null)- language = (await _languageService.GetAllLanguages()).FirstOrDefault();+ var totalEmailsSent = 0;+ var language = await _languageService.GetLanguageById(campaign.LanguageId) ?? (await _languageService.GetAllLanguages()).FirstOrDefault();foreach (var subscription in subscriptions){Customer customer = null;if (!string.IsNullOrEmpty(subscription.CustomerId)) customer = await _customerRepository.GetByIdAsync(subscription.CustomerId);- if (customer == null) customer = _customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant());+ customer ??= _customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant());//ignore deleted or inactive customers when sending newsletter campaignsif (customer != null && (!customer.Active || customer.Deleted))continue;var builder = new LiquidObjectBuilder(_mediator);- var store = await _storeService.GetStoreById(campaign.StoreId);- if (store == null)- store = (await _storeService.GetAllStores()).FirstOrDefault();+ var store = await _storeService.GetStoreById(campaign.StoreId) ?? (await _storeService.GetAllStores()).FirstOrDefault();builder.AddStoreTokens(store, language, emailAccount).AddNewsLetterSubscriptionTokens(subscription, store, _workContext.CurrentHost);@@ -334,7 +330,7 @@ namespace Grand.Business.Marketing.Services.Campaignsemail.ObjectId = campaign.Id;await _queuedEmailService.InsertQueuedEmail(email);- await InsertCampaignHistory(new CampaignHistory() { CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId });+ await InsertCampaignHistory(new CampaignHistory { CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId });totalEmailsSent++;}@@ -355,13 +351,9 @@ namespace Grand.Business.Marketing.Services.Campaignsif (emailAccount == null)throw new ArgumentNullException(nameof(emailAccount));- var language = await _languageService.GetLanguageById(campaign.LanguageId);- if (language == null)- language = (await _languageService.GetAllLanguages()).FirstOrDefault();+ var language = await _languageService.GetLanguageById(campaign.LanguageId) ?? (await _languageService.GetAllLanguages()).FirstOrDefault();- var store = await _storeService.GetStoreById(campaign.StoreId);- if (store == null)- store = (await _storeService.GetAllStores()).FirstOrDefault();+ var store = await _storeService.GetStoreById(campaign.StoreId) ?? (await _storeService.GetAllStores()).FirstOrDefault();var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount);diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.csindex ddd7246f4..cc4c9c391 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <summary>/// Contact attribute parser/// </summary>- public partial class ContactAttributeParser : IContactAttributeParser+ public class ContactAttributeParser : IContactAttributeParser{private readonly IContactAttributeService _contactAttributeService;private readonly IWorkContext _workContext;@@ -53,7 +53,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <summary>/// Get contact attribute values/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <returns>Contact attribute values</returns>public virtual async Task<IList<ContactAttributeValue>> ParseContactAttributeValues(IList<CustomAttribute> customAttributes){@@ -68,32 +68,21 @@ namespace Grand.Business.Marketing.Services.Contactscontinue;var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- foreach (var valueStr in valuesStr)- {- if (!string.IsNullOrEmpty(valueStr))- {- var value = attribute.ContactAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();- if (value != null)- values.Add(value);- }- }+ values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr) select attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);}return values;}/// <summary>/// Adds an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="ca">Contact attribute</param>/// <param name="value">Value</param>/// <returns>Attributes</returns>public virtual IList<CustomAttribute> AddContactAttribute(IList<CustomAttribute> customAttributes, ContactAttribute ca, string value){- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();-+ customAttributes ??= new List<CustomAttribute>();customAttributes.Add(new CustomAttribute() { Key = ca.Id, Value = value });-return customAttributes;}@@ -102,15 +91,14 @@ namespace Grand.Business.Marketing.Services.Contacts/// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified/// </summary>/// <param name="attribute">Contact attribute</param>- /// <param name="selectedAttributes">Selected attributes</param>+ /// <param name="customAttributes">Selected attributes</param>/// <returns>Result</returns>public virtual async Task<bool?> IsConditionMet(ContactAttribute attribute, IList<CustomAttribute> customAttributes){if (attribute == null)throw new ArgumentNullException(nameof(attribute));- if (customAttributes == null)- customAttributes = new List<CustomAttribute>();+ customAttributes ??= new List<CustomAttribute>();var conditionAttribute = attribute.ConditionAttribute;if (!conditionAttribute.Any())@@ -138,10 +126,9 @@ namespace Grand.Business.Marketing.Services.Contactsvar allFound = true;foreach (var t1 in valuesThatShouldBeSelected){- bool found = false;- foreach (var t2 in selectedValues)- if (t1 == t2)- found = true;+ var found = false;+ foreach (var t2 in selectedValues.Where(t2 => t1 == t2))+ found = true;if (!found)allFound = false;}@@ -152,7 +139,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <summary>/// Remove an attribute/// </summary>- /// <param name="attributes">Attributes</param>+ /// <param name="customAttributes">Attributes</param>/// <param name="attribute">Contact attribute</param>/// <returns>Updated result</returns>public virtual IList<CustomAttribute> RemoveContactAttribute(IList<CustomAttribute> customAttributes, ContactAttribute attribute)@@ -166,15 +153,15 @@ namespace Grand.Business.Marketing.Services.Contacts/// <param name="language">Language</param>/// <param name="customAttributes">Attributes </param>/// <param name="customer">Customer</param>- /// <param name="serapator">Serapator</param>+ /// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(Language language,IList<CustomAttribute> customAttributes,Customer customer,- string serapator = "<br />",+ string separator = "<br />",bool htmlEncode = true,bool allowHyperlinks = true){@@ -187,22 +174,22 @@ namespace Grand.Business.Marketing.Services.Contacts{var attribute = attributes[i];var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();- for (int j = 0; j < valuesStr.Count; j++)+ for (var j = 0; j < valuesStr.Count; j++){- string valueStr = valuesStr[j];- string formattedAttribute = "";+ var valueStr = valuesStr[j];+ var formattedAttribute = "";if (!attribute.ShouldHaveValues()){//no valuesif (attribute.AttributeControlType == AttributeControlType.MultilineTextbox){- //multiline textbox+ //multiline text boxvar attributeName = attribute.GetTranslation(a => a.Name, language.Id);//encode (if required)if (htmlEncode)attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));- //we never encode multiline textbox input+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input}else if (attribute.AttributeControlType == AttributeControlType.FileUpload){@@ -213,16 +200,18 @@ namespace Grand.Business.Marketing.Services.Contactsvar attributeName = attribute.GetTranslation(a => a.Name, language.Id);if (allowHyperlinks){- var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentHost.Url.TrimEnd('/'), downloadGuid);- attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, attribute.GetTranslation(a => a.TextPrompt, language.Id));+ var downloadLink =+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";+ attributeText =+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";}- formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);+ formattedAttribute = $"{attributeName}: {attributeText}";}}else{- //other attributes (textbox, datepicker)- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), valueStr);+ //other attributes (text box, datepicker)+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);@@ -230,22 +219,21 @@ namespace Grand.Business.Marketing.Services.Contacts}else{- var attributeValue = attribute.ContactAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();+ var attributeValue = attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr);if (attributeValue != null){- formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, language.Id), attributeValue.GetTranslation(a => a.Name, language.Id));+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";}//encode (if required)if (htmlEncode)formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}- if (!string.IsNullOrEmpty(formattedAttribute))- {- if (i != 0 || j != 0)- result.Append(serapator);- result.Append(formattedAttribute);- }+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}}return result.ToString();diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.csindex cc3502ae1..a3156dc27 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <summary>/// Contact attribute service/// </summary>- public partial class ContactAttributeService : IContactAttributeService+ public class ContactAttributeService : IContactAttributeService{#region Fields@@ -69,10 +69,11 @@ namespace Grand.Business.Marketing.Services.Contacts/// Gets all contact attributes/// </summary>/// <param name="storeId">Store identifier</param>+ /// <param name="ignoreAcl"></param>/// <returns>Contact attributes</returns>- public virtual async Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "", bool ignorAcl = false)+ public virtual async Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "", bool ignoreAcl = false){- string key = string.Format(CacheKey.CONTACTATTRIBUTES_ALL_KEY, storeId, ignorAcl);+ var key = string.Format(CacheKey.CONTACTATTRIBUTES_ALL_KEY, storeId, ignoreAcl);return await _cacheBase.GetAsync(key, async () =>{var query = from p in _contactAttributeRepository.Table@@ -80,23 +81,21 @@ namespace Grand.Business.Marketing.Services.Contactsquery = query.OrderBy(c => c.DisplayOrder);- if ((!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations) ||- (!ignorAcl && !CommonHelper.IgnoreAcl))+ if ((string.IsNullOrEmpty(storeId) || CommonHelper.IgnoreStoreLimitations) &&+ (ignoreAcl || CommonHelper.IgnoreAcl)) return await Task.FromResult(query.ToList());+ if (!ignoreAcl && !CommonHelper.IgnoreAcl){- if (!ignorAcl && !CommonHelper.IgnoreAcl)- {- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();- query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;- }- //Store acl- if (!String.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)- {- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;- }+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();+ query = from p in query+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;+ }+ //Store acl+ if (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)+ {+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ select p;}return await Task.FromResult(query.ToList());@@ -110,7 +109,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <returns>Contact attribute</returns>public virtual Task<ContactAttribute> GetContactAttributeById(string contactAttributeId){- string key = string.Format(CacheKey.CONTACTATTRIBUTES_BY_ID_KEY, contactAttributeId);+ var key = string.Format(CacheKey.CONTACTATTRIBUTES_BY_ID_KEY, contactAttributeId);return _cacheBase.GetAsync(key, () => _contactAttributeRepository.GetByIdAsync(contactAttributeId));}diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.csindex db3393fed..eed432e3a 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <summary>/// ContactUs interface/// </summary>- public partial class ContactUsService : IContactUsService+ public class ContactUsService : IContactUsService{private readonly IRepository<ContactUs> _contactusRepository;@@ -55,6 +55,7 @@ namespace Grand.Business.Marketing.Services.Contacts/// <param name="email">email</param>/// <param name="vendorId">vendorId; null to load all records</param>/// <param name="customerId">customerId; null to load all records</param>+ /// <param name="storeId">Store ident</param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>ContactUs items</returns>@@ -70,14 +71,14 @@ namespace Grand.Business.Marketing.Services.Contactsquery = query.Where(l => fromUtc.Value <= l.CreatedOnUtc);if (toUtc.HasValue)query = query.Where(l => toUtc.Value >= l.CreatedOnUtc);- if (!String.IsNullOrEmpty(vendorId))+ if (!string.IsNullOrEmpty(vendorId))query = query.Where(l => vendorId == l.VendorId);- if (!String.IsNullOrEmpty(customerId))+ if (!string.IsNullOrEmpty(customerId))query = query.Where(l => customerId == l.CustomerId);- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId))query = query.Where(l => storeId == l.StoreId);- if (!String.IsNullOrEmpty(email))+ if (!string.IsNullOrEmpty(email))query = query.Where(l => l.Email.ToLower().Contains(email.ToLower()));query = query.OrderByDescending(x => x.CreatedOnUtc);diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.csindex a3db454f8..ab69b6263 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs@@ -36,7 +36,7 @@ namespace Grand.Business.Marketing.Services.Courseswhere a.CustomerId == customerId && a.LessonId == lessonIdselect a).FirstOrDefault());- return query != null ? query.Finished : false;+ return query is { Finished: true };}public virtual async Task<CourseAction> InsertAsync(CourseAction courseAction)diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.csindex cd15dae5d..45b27b246 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs@@ -31,7 +31,7 @@ namespace Grand.Business.Marketing.Services.Coursespublic virtual async Task<IList<CourseLesson>> GetByCourseId(string courseId){if (string.IsNullOrEmpty(courseId))- throw new ArgumentNullException("courseId");+ throw new ArgumentNullException(nameof(courseId));var query = from c in _courseLessonRepository.Tablewhere c.CourseId == courseIddiff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.csindex 243b83647..fc6f81bf8 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs@@ -51,7 +51,7 @@ namespace Grand.Business.Marketing.Services.Coursesquery = query.Where(c => c.Published);- if ((!CommonHelper.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)))+ if (!CommonHelper.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !CommonHelper.IgnoreStoreLimitations)){if (!CommonHelper.IgnoreAcl){diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.csindex a9aded952..3c4d04d3b 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs@@ -36,7 +36,7 @@ namespace Grand.Business.Marketing.Services.Customersif (customer.Coordinates == null)await Task.FromResult((0, 0));- return await Task.FromResult((customer.Coordinates.X, customer.Coordinates.Y));+ return await Task.FromResult((customer.Coordinates!.X, customer.Coordinates!.Y));}public async Task SaveGeoCoordinate(double longitude, double latitude)diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.csindex 7a9b62b35..1ca2bed0c 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs@@ -37,7 +37,7 @@ namespace Grand.Business.Marketing.Services.Customers/// <summary>/// Gets a customer product price/// </summary>- /// <param name="Id">Identifier</param>+ /// <param name="id">Identifier</param>/// <returns>Customer product price</returns>public virtual Task<CustomerProductPrice> GetCustomerProductPriceById(string id){@@ -53,19 +53,15 @@ namespace Grand.Business.Marketing.Services.Customerspublic virtual async Task<double?> GetPriceByCustomerProduct(string customerId, string productId){var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerId, productId);- var productprice = await _cacheBase.GetAsync(key, async () =>+ var productPrice = await _cacheBase.GetAsync(key, async () =>{- var pp = await Task.FromResult(_customerProductPriceRepository.Table.Where(x => x.CustomerId == customerId && x.ProductId == productId).FirstOrDefault());- if (pp == null)- return (null, false);- else- return (pp, true);+ var pp = await Task.FromResult(_customerProductPriceRepository.Table.FirstOrDefault(x => x.CustomerId == customerId && x.ProductId == productId));+ return pp == null ? (null, false) : (pp, true);});- if (!productprice.Item2)+ if (!productPrice.Item2)return null;- else- return productprice.pp.Price;+ return productPrice.pp.Price;}/// <summary>diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.csindex 26b71b92f..d79daccea 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs@@ -12,7 +12,7 @@ namespace Grand.Business.Marketing.Services.Customers/// <summary>/// Customer tag service/// </summary>- public partial class CustomerTagService : ICustomerTagService+ public class CustomerTagService : ICustomerTagService{#region Fields@@ -193,11 +193,11 @@ namespace Grand.Business.Marketing.Services.Customers/// <returns>Customer tag products</returns>public virtual async Task<IList<CustomerTagProduct>> GetCustomerTagProducts(string customerTagId){- string key = string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagId);+ var key = string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagId);return await _cacheBase.GetAsync(key, async () =>{var query = from cr in _customerTagProductRepository.Table- where (cr.CustomerTagId == customerTagId)+ where cr.CustomerTagId == customerTagIdorderby cr.DisplayOrderselect cr;return await Task.FromResult(query.ToList());@@ -222,7 +222,7 @@ namespace Grand.Business.Marketing.Services.Customers/// <summary>/// Gets customer tag product/// </summary>- /// <param name="Id">id</param>+ /// <param name="id">id</param>/// <returns>Customer tag product</returns>public virtual Task<CustomerTagProduct> GetCustomerTagProductById(string id){diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.csindex e3bcc5084..82089636d 100644--- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs@@ -8,7 +8,7 @@ using Grand.Domain.Common;namespace Grand.Business.Marketing.Services.Documents{- public partial class DocumentService : IDocumentService+ public class DocumentService : IDocumentService{private readonly IRepository<Document> _documentRepository;private readonly IMediator _mediator;diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.csindex d32803017..402c69e40 100644--- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs@@ -6,7 +6,7 @@ using MediatR;namespace Grand.Business.Marketing.Services.Documents{- public partial class DocumentTypeService : IDocumentTypeService+ public class DocumentTypeService : IDocumentTypeService{private readonly IRepository<DocumentType> _documentTypeRepository;private readonly IMediator _mediator;diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.csindex 3e4fb34fd..f0a9a95d9 100644--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs@@ -112,7 +112,7 @@ namespace Grand.Business.Marketing.Services.NewstelettersnewsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email);//get previous newsLetterSubscription record- var prevnewsLetterSubscription = await _subscriptionRepository.GetByIdAsync(newsLetterSubscription.Id);+ var prevNewsLetterSubscription = await _subscriptionRepository.GetByIdAsync(newsLetterSubscription.Id);//Persistawait _subscriptionRepository.UpdateAsync(newsLetterSubscription);@@ -121,14 +121,17 @@ namespace Grand.Business.Marketing.Services.Newstelettersawait newsLetterSubscription.SaveHistory<NewsLetterSubscription>(_historyService);//Publish the un/subscribe event- if (prevnewsLetterSubscription != null)+ if (prevNewsLetterSubscription != null){- if (newsLetterSubscription.Active && !prevnewsLetterSubscription.Active)- await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);-- if (!newsLetterSubscription.Active && prevnewsLetterSubscription.Active)- await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);-+ switch (newsLetterSubscription.Active)+ {+ case true when !prevNewsLetterSubscription.Active:+ await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);+ break;+ case false when prevNewsLetterSubscription.Active:+ await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);+ break;+ }}//Publish eventawait _mediator.EntityUpdated(newsLetterSubscription);@@ -206,7 +209,7 @@ namespace Grand.Business.Marketing.Services.Newsteletters/// <returns>NewsLetter subscription</returns>public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByCustomerId(string customerId){- if (String.IsNullOrEmpty(customerId))+ if (string.IsNullOrEmpty(customerId))return null;var newsLetterSubscriptions = from nls in _subscriptionRepository.Table@@ -221,8 +224,8 @@ namespace Grand.Business.Marketing.Services.Newsteletters/// </summary>/// <param name="email">Email to search or string. Empty to load all records.</param>/// <param name="storeId">Store identifier. "" to load all records.</param>- /// <param name="customerGroupId">Customer group identifier. Used to filter subscribers by customer group. "" to load all records.</param>/// <param name="isActive">Value indicating whether subscriber record should be active or not; null to load all records</param>+ /// <param name="categoryIds"></param>/// <param name="pageIndex">Page index</param>/// <param name="pageSize">Page size</param>/// <returns>NewsLetterSubscription entities</returns>@@ -234,13 +237,13 @@ namespace Grand.Business.Marketing.Services.Newstelettersvar query = from p in _subscriptionRepository.Tableselect p;- if (!String.IsNullOrEmpty(email))+ if (!string.IsNullOrEmpty(email))query = query.Where(nls => nls.Email.ToLower().Contains(email.ToLower()));- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId))query = query.Where(nls => nls.StoreId == storeId);if (isActive.HasValue)query = query.Where(nls => nls.Active == isActive.Value);- if (categoryIds != null && categoryIds.Length > 0)+ if (categoryIds is { Length: > 0 })query = query.Where(c => c.Categories.Any(x => categoryIds.Contains(x)));query = query.OrderBy(nls => nls.Email);@@ -257,7 +260,7 @@ namespace Grand.Business.Marketing.Services.Newstelettersif (subscriptions == null)throw new ArgumentNullException(nameof(subscriptions));- const string separator = ",";+ const char separator = ',';var sb = new StringBuilder();foreach (var subscription in subscriptions){@@ -283,81 +286,75 @@ namespace Grand.Business.Marketing.Services.Newsteletters/// <returns>Number of imported subscribers</returns>public virtual async Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId){- int count = 0;- using (var reader = new StreamReader(stream))+ var count = 0;+ using var reader = new StreamReader(stream);+ while (!reader.EndOfStream){- while (!reader.EndOfStream)+ var line = await reader.ReadLineAsync();+ if (string.IsNullOrWhiteSpace(line))+ continue;+ var tmp = line.Split(',');++ var email = "";+ var isActive = true;+ var categories = new List<string>();+ var isCategories = false;+ var storeId = currentStoreId;+ switch (tmp.Length){- string line = reader.ReadLine();- if (string.IsNullOrWhiteSpace(line))- continue;- string[] tmp = line.Split(',');-- var email = "";- bool isActive = true;- var categories = new List<string>();- bool iscategories = false;- string storeId = currentStoreId;//parse- if (tmp.Length == 1)- {+ case 1://"email" onlyemail = tmp[0].Trim();- }- else if (tmp.Length == 2)- {+ break;+ case 2://"email" and "active" fields specifiedemail = tmp[0].Trim();- isActive = Boolean.Parse(tmp[1].Trim());- }- else if (tmp.Length == 3)- {+ isActive = bool.Parse(tmp[1].Trim());+ break;+ case 3://"email" and "active" and "storeId" fields specifiedemail = tmp[0].Trim();- isActive = Boolean.Parse(tmp[1].Trim());+ isActive = bool.Parse(tmp[1].Trim());storeId = tmp[2].Trim();- }- else if (tmp.Length == 4)- {+ break;+ case 4://"email" and "active" and "storeId" and categories fields specifiedemail = tmp[0].Trim();- isActive = Boolean.Parse(tmp[1].Trim());+ isActive = bool.Parse(tmp[1].Trim());storeId = tmp[2].Trim();try{var items = tmp[3].Trim().Split(';').ToList();- foreach (var item in items)- {- if (!string.IsNullOrEmpty(item))- {- categories.Add(item);- }- }- iscategories = true;+ categories.AddRange(items.Where(item => !string.IsNullOrEmpty(item)));+ isCategories = true;}- catch { };- }- else+ catch+ {+ // ignored+ }+ break;+ default:throw new GrandException("Wrong file format");+ }- //import- await ImportSubscription(email, storeId, isActive, iscategories, categories);+ //import+ await ImportSubscription(email, storeId, isActive, isCategories, categories);- count++;- }+ count++;}return count;}- protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool iscategories, List<string> categories)+ protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool isCategories, List<string> categories){var subscription = await GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);if (subscription != null){subscription.Email = email;subscription.Active = isActive;- if (iscategories)+ if (isCategories){subscription.Categories.Clear();foreach (var item in categories)diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.csindex 4fbc22437..34ffdc099 100644--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs@@ -1,12 +1,12 @@using Grand.Business.Core.Interfaces.Marketing.Newsletters;-using Grand.Infrastructure.Extensions;using Grand.Domain.Data;using Grand.Domain.Messages;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Newsteletters+namespace Grand.Business.Marketing.Services.Newsletters{- public partial class NewsletterCategoryService : INewsletterCategoryService+ public class NewsletterCategoryService : INewsletterCategoryService{#region Fields@@ -28,47 +28,47 @@ namespace Grand.Business.Marketing.Services.Newsteletters/// <summary>/// Inserts a newsletter category/// </summary>- /// <param name="newslettercategory">NewsletterCategory</param>- public virtual async Task InsertNewsletterCategory(NewsletterCategory newslettercategory)+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task InsertNewsletterCategory(NewsletterCategory newsletterCategory){- if (newslettercategory == null)- throw new ArgumentNullException(nameof(newslettercategory));+ if (newsletterCategory == null)+ throw new ArgumentNullException(nameof(newsletterCategory));- await _newsletterCategoryRepository.InsertAsync(newslettercategory);+ await _newsletterCategoryRepository.InsertAsync(newsletterCategory);//event notification- await _mediator.EntityInserted(newslettercategory);+ await _mediator.EntityInserted(newsletterCategory);}/// <summary>/// Updates a newsletter category/// </summary>- /// <param name="newslettercategory">NewsletterCategory</param>- public virtual async Task UpdateNewsletterCategory(NewsletterCategory newslettercategory)+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task UpdateNewsletterCategory(NewsletterCategory newsletterCategory){- if (newslettercategory == null)- throw new ArgumentNullException(nameof(newslettercategory));+ if (newsletterCategory == null)+ throw new ArgumentNullException(nameof(newsletterCategory));- await _newsletterCategoryRepository.UpdateAsync(newslettercategory);+ await _newsletterCategoryRepository.UpdateAsync(newsletterCategory);//event notification- await _mediator.EntityUpdated(newslettercategory);+ await _mediator.EntityUpdated(newsletterCategory);}/// <summary>/// Deleted a newsletter category/// </summary>- /// <param name="newslettercategory">NewsletterCategory</param>- public virtual async Task DeleteNewsletterCategory(NewsletterCategory newslettercategory)+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task DeleteNewsletterCategory(NewsletterCategory newsletterCategory){- if (newslettercategory == null)- throw new ArgumentNullException(nameof(newslettercategory));+ if (newsletterCategory == null)+ throw new ArgumentNullException(nameof(newsletterCategory));- await _newsletterCategoryRepository.DeleteAsync(newslettercategory);+ await _newsletterCategoryRepository.DeleteAsync(newsletterCategory);//event notification- await _mediator.EntityDeleted(newslettercategory);+ await _mediator.EntityDeleted(newsletterCategory);}diff --git a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.csindex 7f21e7c89..821d55cf4 100644--- a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs@@ -14,7 +14,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications{public class PushNotificationsService : IPushNotificationsService{- private readonly IRepository<PushRegistration> _pushRegistratiosnRepository;+ private readonly IRepository<PushRegistration> _pushRegistrationRepository;private readonly IRepository<PushMessage> _pushMessagesRepository;private readonly IMediator _mediator;private readonly PushNotificationsSettings _pushNotificationsSettings;@@ -22,10 +22,10 @@ namespace Grand.Business.Marketing.Services.PushNotificationsprivate readonly ILogger _logger;private readonly HttpClient _httpClient;- private readonly string fcmUrl = "https://fcm.googleapis.com/fcm/send";+ private const string FcmUrl = "https://fcm.googleapis.com/fcm/send";public PushNotificationsService(- IRepository<PushRegistration> pushRegistratiosnRepository,+ IRepository<PushRegistration> pushRegistrationRepository,IRepository<PushMessage> pushMessagesRepository,IMediator mediator,PushNotificationsSettings pushNotificationsSettings,@@ -33,7 +33,7 @@ namespace Grand.Business.Marketing.Services.PushNotificationsILogger logger,HttpClient httpClient){- _pushRegistratiosnRepository = pushRegistratiosnRepository;+ _pushRegistrationRepository = pushRegistrationRepository;_pushMessagesRepository = pushMessagesRepository;_mediator = mediator;_pushNotificationsSettings = pushNotificationsSettings;@@ -45,10 +45,10 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// <summary>/// Inserts push receiver/// </summary>- /// <param name="model"></param>+ /// <param name="registration"></param>public virtual async Task InsertPushReceiver(PushRegistration registration){- await _pushRegistratiosnRepository.InsertAsync(registration);+ await _pushRegistrationRepository.InsertAsync(registration);await _mediator.EntityInserted(registration);}@@ -56,10 +56,10 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// <summary>/// Deletes push receiver/// </summary>- /// <param name="model"></param>+ /// <param name="registration"></param>public virtual async Task DeletePushReceiver(PushRegistration registration){- await _pushRegistratiosnRepository.DeleteAsync(registration);+ await _pushRegistrationRepository.DeleteAsync(registration);await _mediator.EntityDeleted(registration);}@@ -69,7 +69,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// <param name="customerId"></param>public virtual async Task<PushRegistration> GetPushReceiverByCustomerId(string customerId){- return await Task.FromResult(_pushRegistratiosnRepository.Table.Where(x => x.CustomerId == customerId).FirstOrDefault());+ return await Task.FromResult(_pushRegistrationRepository.Table.FirstOrDefault(x => x.CustomerId == customerId));}/// <summary>@@ -78,7 +78,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// <param name="registration"></param>public virtual async Task UpdatePushReceiver(PushRegistration registration){- await _pushRegistratiosnRepository.UpdateAsync(registration);+ await _pushRegistrationRepository.UpdateAsync(registration);await _mediator.EntityUpdated(registration);}@@ -87,7 +87,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// </summary>public virtual async Task<List<PushRegistration>> GetPushReceivers(){- return await Task.FromResult(_pushRegistratiosnRepository.Table.Where(x => x.Allowed).ToList());+ return await Task.FromResult(_pushRegistrationRepository.Table.Where(x => x.Allowed).ToList());}/// <summary>@@ -95,7 +95,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// </summary>public virtual async Task<int> GetAllowedReceivers(){- return await Task.FromResult(_pushRegistratiosnRepository.Table.Where(x => x.Allowed).Count());+ return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => x.Allowed));}/// <summary>@@ -103,13 +103,13 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// </summary>public virtual async Task<int> GetDeniedReceivers(){- return await Task.FromResult(_pushRegistratiosnRepository.Table.Where(x => !x.Allowed).Count());+ return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => !x.Allowed));}/// <summary>/// Inserts push message/// </summary>- /// <param name="registration"></param>+ /// <param name="message"></param>public virtual async Task InsertPushMessage(PushMessage message){await _pushMessagesRepository.InsertAsync(message);@@ -130,7 +130,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// </summary>public virtual async Task<IPagedList<PushRegistration>> GetPushReceivers(int pageIndex = 0, int pageSize = int.MaxValue){- var query = _pushRegistratiosnRepository.Table.OrderByDescending(x => x.RegisteredOn);+ var query = _pushRegistrationRepository.Table.OrderByDescending(x => x.RegisteredOn);return await Task.FromResult(new PagedList<PushRegistration>(query, pageIndex, pageSize));}@@ -159,14 +159,13 @@ namespace Grand.Business.Marketing.Services.PushNotificationsreturn (false, _translationService.GetResource("Admin.PushNotifications.Error.NoReceivers"));}- int batchsize = 1000;- for (int batch = 0; batch <= Math.Round((double)(receivers.Count / batchsize), 0, MidpointRounding.ToEven); batch++)+ const int batchSize = 1000;+ for (var batch = 0; batch <= Math.Round((double)(receivers.Count / batchSize), 0, MidpointRounding.ToEven); batch++){- var t = receivers.Skip(batch * batchsize).Take(batchsize);- foreach (var receiver in receivers)+ var t = receivers.Skip(batch * batchSize).Take(batchSize);+ foreach (var receiver in receivers.Where(receiver => !ids.Contains(receiver.Token))){- if (!ids.Contains(receiver.Token))- ids.Add(receiver.Token);+ ids.Add(receiver.Token);}}}@@ -187,37 +186,31 @@ namespace Grand.Business.Marketing.Services.PushNotificationstry{- using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, fcmUrl))- {- httpRequest.Headers.Add("Authorization", $"key = {_pushNotificationsSettings.PrivateApiKey}");- httpRequest.Headers.Add("Sender", $"id = {_pushNotificationsSettings.SenderId}");+ using var httpRequest = new HttpRequestMessage(HttpMethod.Post, FcmUrl);+ httpRequest.Headers.Add("Authorization", $"key = {_pushNotificationsSettings.PrivateApiKey}");+ httpRequest.Headers.Add("Sender", $"id = {_pushNotificationsSettings.SenderId}");- httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");+ httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");- using (var response = await _httpClient.SendAsync(httpRequest))- {- var responseString = await response.Content.ReadAsStringAsync();- if (!response.IsSuccessStatusCode)- {- await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Error occured while sending push notification.", responseString);- return (false, responseString);- }- else- {- var responseMessage = JsonConvert.DeserializeObject<JsonResponse>(responseString);-- await InsertPushMessage(new PushMessage {- NumberOfReceivers = responseMessage.success,- SentOn = DateTime.UtcNow,- Text = text,- Title = title- });-- return (true, string.Format(_translationService.GetResource("Admin.PushNotifications.MessageSent"), responseMessage.success, responseMessage.failure));- }-- }+ using var response = await _httpClient.SendAsync(httpRequest);+ var responseString = await response.Content.ReadAsStringAsync();+ if (!response.IsSuccessStatusCode)+ {+ await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Error occured while sending push notification.", responseString);+ return (false, responseString);}++ var responseMessage = JsonConvert.DeserializeObject<JsonResponse>(responseString);+ if (responseMessage == null) return (false, "PushNotifications.ResponseMessage.Empty");++ await InsertPushMessage(new PushMessage {+ NumberOfReceivers = responseMessage.success,+ SentOn = DateTime.UtcNow,+ Text = text,+ Title = title+ });++ return (true, string.Format(_translationService.GetResource("Admin.PushNotifications.MessageSent"), responseMessage.success, responseMessage.failure));}catch (Exception ex){@@ -245,7 +238,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications/// <param name="id">Ident</param>public virtual Task<PushRegistration> GetPushReceiver(string id){- return _pushRegistratiosnRepository.GetByIdAsync(id);+ return _pushRegistrationRepository.GetByIdAsync(id);}}}diff --git a/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs b/src/Business/Grand.Business.Marketing/Startup/StartupApplication.csindex cde3e1cbc..8a36c6aab 100644--- a/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs@@ -10,6 +10,7 @@ using Grand.Business.Marketing.Services.Contacts;using Grand.Business.Marketing.Services.Courses;using Grand.Business.Marketing.Services.Customers;using Grand.Business.Marketing.Services.Documents;+using Grand.Business.Marketing.Services.Newsletters;using Grand.Business.Marketing.Services.Newsteletters;using Grand.Business.Marketing.Services.PushNotifications;using Grand.Infrastructure;diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.csindex 167c3f81c..479c96081 100644--- a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs+++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs@@ -1,9 +1,10 @@using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Common;using Grand.Domain.Data;using Grand.Domain.Messages;using MediatR;-namespace Grand.Business.Messages.Commands.Handlers+namespace Grand.Business.Messages.Commands.Handlers.Common{public class InsertContactUsCommandHandler : IRequestHandler<InsertContactUsCommand, bool>{@@ -17,7 +18,7 @@ namespace Grand.Business.Messages.Commands.Handlerspublic async Task<bool> Handle(InsertContactUsCommand request, CancellationToken cancellationToken){- var contactus = new ContactUs() {+ var contactus = new ContactUs {CreatedOnUtc = DateTime.UtcNow,CustomerId = request.CustomerId,StoreId = request.StoreId,diff --git a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs b/src/Business/Grand.Business.Messages/Services/EmailAccountService.csindex 13b369ecc..3ba455427 100644--- a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs+++ b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs@@ -10,7 +10,7 @@ using MediatR;namespace Grand.Business.Messages.Services{- public partial class EmailAccountService : IEmailAccountService+ public class EmailAccountService : IEmailAccountService{private readonly IRepository<EmailAccount> _emailAccountRepository;private readonly ICacheBase _cacheBase;diff --git a/src/Business/Grand.Business.Messages/Services/EmailSender.cs b/src/Business/Grand.Business.Messages/Services/EmailSender.csindex 68e42c8a1..8abf9bf6d 100644--- a/src/Business/Grand.Business.Messages/Services/EmailSender.cs+++ b/src/Business/Grand.Business.Messages/Services/EmailSender.cs@@ -10,7 +10,7 @@ namespace Grand.Business.Messages.Services/// <summary>/// Email sender/// </summary>- public partial class EmailSender : IEmailSender+ public class EmailSender : IEmailSender{private readonly IDownloadService _downloadService;private readonly IMimeMappingService _mimeMappingService;@@ -37,7 +37,7 @@ namespace Grand.Business.Messages.Services/// <param name="ccAddresses">CC addresses list</param>/// <param name="attachmentFilePath">Attachment file path</param>/// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>- /// <param name="attachedDownloads">Attachment download ID (another attachedment)</param>+ /// <param name="attachedDownloads">Attachment download ID (another attachment)</param>public virtual async Task SendEmail(EmailAccount emailAccount, string subject, string body,string fromAddress, string fromName, string toAddress, string toName,string replyToAddress = null, string replyToName = null,@@ -50,7 +50,7 @@ namespace Grand.Business.Messages.Services//from, to, reply tomessage.From.Add(new MailboxAddress(fromName, fromAddress));message.To.Add(new MailboxAddress(toName, toAddress));- if (!String.IsNullOrEmpty(replyToAddress))+ if (!string.IsNullOrEmpty(replyToAddress)){message.ReplyTo.Add(new MailboxAddress(replyToName, replyToAddress));}@@ -58,7 +58,7 @@ namespace Grand.Business.Messages.Services//BCCif (bccAddresses != null && bccAddresses.Any()){- foreach (var address in bccAddresses.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))+ foreach (var address in bccAddresses.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue))){message.Bcc.Add(MailboxAddress.Parse(address.Trim()));}@@ -67,7 +67,7 @@ namespace Grand.Business.Messages.Services//CCif (ccAddresses != null && ccAddresses.Any()){- foreach (var address in ccAddresses.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))+ foreach (var address in ccAddresses.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue))){message.Cc.Add(MailboxAddress.Parse(address.Trim()));}@@ -77,11 +77,12 @@ namespace Grand.Business.Messages.Servicesmessage.Subject = subject;//content- var builder = new BodyBuilder();- builder.HtmlBody = body;+ var builder = new BodyBuilder {+ HtmlBody = body+ };//create the file attachment for this e-mail message- if (!String.IsNullOrEmpty(attachmentFilePath) &&+ if (!string.IsNullOrEmpty(attachmentFilePath) &&File.Exists(attachmentFilePath)){// TODO: should probably include a check for the attachmentFileName not being null or white space@@ -125,16 +126,14 @@ namespace Grand.Business.Messages.Servicesmessage.Body = builder.ToMessageBody();//send email- using (var smtpClient = new SmtpClient())- {- smtpClient.ServerCertificateValidationCallback =- (s, c, h, e) => emailAccount.UseServerCertificateValidation;- await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port,- (SecureSocketOptions)emailAccount.SecureSocketOptionsId);- await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password);- await smtpClient.SendAsync(message);- await smtpClient.DisconnectAsync(true);- }+ using var smtpClient = new SmtpClient();+ smtpClient.ServerCertificateValidationCallback =+ (_, _, _, _) => emailAccount.UseServerCertificateValidation;+ await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port,+ (SecureSocketOptions)emailAccount.SecureSocketOptionsId);+ await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password);+ await smtpClient.SendAsync(message);+ await smtpClient.DisconnectAsync(true);}}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/MessageProviderService.csindex acf7df339..f1e11ae64 100644--- a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs+++ b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs@@ -2,7 +2,7 @@using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Stores;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Common;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Queries.Messages;@@ -25,7 +25,7 @@ using System.Net;namespace Grand.Business.Messages.Services{- public partial class MessageProviderService : IMessageProviderService+ public class MessageProviderService : IMessageProviderService{#region Fields@@ -87,20 +87,14 @@ namespace Grand.Business.Messages.Services//ensure it's activevar isActive = messageTemplate.IsActive;- if (!isActive)- return null;-- return messageTemplate;+ return !isActive ? null : messageTemplate;}protected virtual async Task<EmailAccount> GetEmailAccountOfMessageTemplate(MessageTemplate messageTemplate, string languageId){var emailAccounId = messageTemplate.GetTranslation(mt => mt.EmailAccountId, languageId);- var emailAccount = await _emailAccountService.GetEmailAccountById(emailAccounId);- if (emailAccount == null)- emailAccount = await _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);- if (emailAccount == null)- emailAccount = (await _emailAccountService.GetAllEmailAccounts()).FirstOrDefault();+ var emailAccount = (await _emailAccountService.GetEmailAccountById(emailAccounId) ?? await _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId)) ??+ (await _emailAccountService.GetAllEmailAccounts()).FirstOrDefault();return emailAccount;}@@ -110,12 +104,12 @@ namespace Grand.Business.Messages.Services//load language by specified IDvar language = await _languageService.GetLanguageById(languageId);- if (language == null || !language.Published)+ if (language is not { Published: true }){//load any language from the specified storelanguage = (await _languageService.GetAllLanguages(storeId: storeId)).FirstOrDefault();}- if (language == null || !language.Published)+ if (language is not { Published: true }){//load any languagelanguage = (await _languageService.GetAllLanguages()).FirstOrDefault();@@ -283,9 +277,10 @@ namespace Grand.Business.Messages.Services/// <param name="languageId">Message language identifier</param>public virtual async Task<int> SendOrderRefundedStoreOwnerMessage(Order order, double refundedAmount, string languageId){- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = order.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId });return await SendOrderStoreOwnerMessage(MessageTemplateNames.SendOrderRefundedStoreOwnerMessage, order, customer, languageId, refundedAmount);}+/// <summary>/// Sends an order notification to a store owner/// </summary>@@ -293,6 +288,7 @@ namespace Grand.Business.Messages.Services/// <param name="order">Order instance</param>/// <param name="customer">Customer instance</param>/// <param name="languageId">Message language identifier</param>+ /// <param name="refundedAmount"></param>private async Task<int> SendOrderStoreOwnerMessage(string template, Order order, Customer customer, string languageId, double refundedAmount = 0){if (order == null)@@ -390,7 +386,7 @@ namespace Grand.Business.Messages.Services/// <returns>Queued email identifier</returns>public virtual async Task<int> SendOrderRefundedCustomerMessage(Order order, double refundedAmount, string languageId){- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = order.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId });return await SendOrderCustomerMessage(MessageTemplateNames.SendOrderRefundedCustomerMessage, order, customer, languageId, refundedAmount: refundedAmount);}@@ -404,6 +400,7 @@ namespace Grand.Business.Messages.Services/// <param name="attachmentFilePath">Attachment file path</param>/// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>/// <param name="attachments">Attachments ident</param>+ /// <param name="refundedAmount"></param>private async Task<int> SendOrderCustomerMessage(string message, Order order, Customer customer, string languageId,string attachmentFilePath = null, string attachmentFileName = null, IEnumerable<string> attachments = null, double refundedAmount = 0){@@ -499,7 +496,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = order.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount)@@ -565,7 +562,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = order.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount)@@ -611,7 +608,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = order.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount)@@ -886,7 +883,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = merchandiseReturn.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = merchandiseReturn.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount);@@ -942,7 +939,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = merchandiseReturn.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = merchandiseReturn.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount);@@ -987,7 +984,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = merchandiseReturn.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = merchandiseReturn.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount);@@ -1035,7 +1032,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = merchandiseReturn.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = merchandiseReturn.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount);@@ -1153,9 +1150,9 @@ namespace Grand.Business.Messages.Servicesif (order != null) store = await _storeService.GetStoreById(order.StoreId);store ??= (await _storeService.GetAllStores()).FirstOrDefault();- var language = await EnsureLanguageIsActive(languageId, store.Id);+ var language = await EnsureLanguageIsActive(languageId, store?.Id);- var messageTemplate = await GetMessageTemplate("GiftVoucher.Notification", store.Id);+ var messageTemplate = await GetMessageTemplate("GiftVoucher.Notification", store?.Id);if (messageTemplate == null)return 0;@@ -1197,7 +1194,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = productReview.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = productReview.CustomerId });var builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount)@@ -1240,7 +1237,7 @@ namespace Grand.Business.Messages.Services//email accountvar emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);//customer- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = vendorReview.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = vendorReview.CustomerId });//vendorvar vendor = await _mediator.Send(new GetVendorByIdQuery() { Id = vendorReview.VendorId });@@ -1303,6 +1300,7 @@ namespace Grand.Business.Messages.Services/// <summary>/// Sends a "quantity below" notification to a store owner/// </summary>+ /// <param name="product"></param>/// <param name="combination">Attribute combination</param>/// <param name="languageId">Message language identifier</param>public virtual async Task<int> SendQuantityBelowStoreOwnerMessage(Product product, ProductAttributeCombination combination, string languageId)@@ -1337,7 +1335,7 @@ namespace Grand.Business.Messages.Services}/// <summary>- /// Sends a "new VAT sumitted" notification to a store owner+ /// Sends a "new VAT" notification to a store owner/// </summary>/// <param name="customer">Customer</param>/// <param name="languageId">Message language identifier</param>@@ -1392,7 +1390,7 @@ namespace Grand.Business.Messages.Servicesbuilder.AddStoreTokens(store, language, emailAccount).AddBlogCommentTokens(blogPost, blogComment, store, _storeHelper.DomainHost, language);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = blogComment.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = blogComment.CustomerId });if (customer != null && await _groupService.IsRegistered(customer))builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);@@ -1411,6 +1409,7 @@ namespace Grand.Business.Messages.Services/// <summary>/// Sends an article comment notification message to a store owner/// </summary>+ /// <param name="article"></param>/// <param name="articleComment">Article comment</param>/// <param name="languageId">Message language identifier</param>public virtual async Task<int> SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseArticleComment articleComment, string languageId)@@ -1432,7 +1431,7 @@ namespace Grand.Business.Messages.Servicesbuilder.AddStoreTokens(store, language, emailAccount).AddArticleCommentTokens(article, articleComment, store, _storeHelper.DomainHost, language);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = articleComment.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = articleComment.CustomerId });if (customer != null && await _groupService.IsRegistered(customer))builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);LiquidObject liquidObject = await builder.BuildAsync();@@ -1470,7 +1469,7 @@ namespace Grand.Business.Messages.Servicesvar builder = new LiquidObjectBuilder(_mediator);builder.AddStoreTokens(store, language, emailAccount).AddNewsCommentTokens(newsItem, newsComment, store, _storeHelper.DomainHost, language);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = newsComment.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = newsComment.CustomerId });if (customer != null)builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);@@ -1492,7 +1491,7 @@ namespace Grand.Business.Messages.Services/// <param name="product">Product</param>/// <param name="subscription">Subscription</param>/// <param name="languageId">Message language identifier</param>- public virtual async Task<int> SendBackinStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, string languageId)+ public virtual async Task<int> SendBackInStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, string languageId){if (subscription == null)throw new ArgumentNullException(nameof(subscription));@@ -1690,41 +1689,38 @@ namespace Grand.Business.Messages.Servicesif (product == null)throw new ArgumentNullException(nameof(product));- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = bid.CustomerId });- if (customer != null)+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId });+ if (customer == null) return 0;+ if (string.IsNullOrEmpty(languageId)){- if (string.IsNullOrEmpty(languageId))- {- languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);- }+ languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);+ }- var store = await GetStore(bid.StoreId);- var language = await EnsureLanguageIsActive(languageId, store.Id);+ var store = await GetStore(bid.StoreId);+ var language = await EnsureLanguageIsActive(languageId, store.Id);- var messageTemplate = await GetMessageTemplate("AuctionEnded.CustomerNotificationWin", store.Id);- if (messageTemplate == null)- return 0;+ var messageTemplate = await GetMessageTemplate("AuctionEnded.CustomerNotificationWin", store.Id);+ if (messageTemplate == null)+ return 0;- var emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);+ var emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);- var builder = new LiquidObjectBuilder(_mediator);- builder.AddAuctionTokens(product, bid)- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)- .AddProductTokens(product, language, store, _storeHelper.DomainHost)- .AddStoreTokens(store, language, emailAccount);+ var builder = new LiquidObjectBuilder(_mediator);+ builder.AddAuctionTokens(product, bid)+ .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)+ .AddProductTokens(product, language, store, _storeHelper.DomainHost)+ .AddStoreTokens(store, language, emailAccount);- LiquidObject liquidObject = await builder.BuildAsync();- //event notification- await _mediator.MessageTokensAdded(messageTemplate, liquidObject);+ LiquidObject liquidObject = await builder.BuildAsync();+ //event notification+ await _mediator.MessageTokensAdded(messageTemplate, liquidObject);- var toEmail = customer.Email;- var toName = customer.GetFullName();- return await SendNotification(messageTemplate, emailAccount,- languageId, liquidObject,- toEmail, toName,- reference: Reference.Customer, objectId: customer.Id);- }- return 0;+ var toEmail = customer.Email;+ var toName = customer.GetFullName();+ return await SendNotification(messageTemplate, emailAccount,+ languageId, liquidObject,+ toEmail, toName,+ reference: Reference.Customer, objectId: customer.Id);}public virtual async Task<int> SendAuctionEndedLostCustomerMessage(Product product, string languageId, Bid bid)@@ -1732,7 +1728,7 @@ namespace Grand.Business.Messages.Servicesif (product == null)throw new ArgumentNullException(nameof(product));- var winner = await _mediator.Send(new GetCustomerByIdQuery() { Id = bid.CustomerId });+ var winner = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId });if (winner == null) return 0;var store = await GetStore(bid.StoreId);@@ -1755,7 +1751,7 @@ namespace Grand.Business.Messages.Servicesforeach (var item in bids){var builder2 = new LiquidObjectBuilder(_mediator, liquidObject);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = item.Key });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = item.Key });if (string.IsNullOrEmpty(languageId)){languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);@@ -1799,7 +1795,7 @@ namespace Grand.Business.Messages.Servicesforeach (var item in bids){var builder2 = new LiquidObjectBuilder(_mediator, liquidObject);- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = item.Key });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = item.Key });if (customer != null){if (string.IsNullOrEmpty(languageId))@@ -1834,7 +1830,7 @@ namespace Grand.Business.Messages.Servicesif (bid != null){- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = bid.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId });if (string.IsNullOrEmpty(languageId)){languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);@@ -1882,12 +1878,13 @@ namespace Grand.Business.Messages.Services/// </summary>/// <param name="languageId">Message language identifier</param>/// <param name="product">Product</param>+ /// <param name="bid"></param>public virtual async Task<int> SendOutBidCustomerMessage(Product product, string languageId, Bid bid){if (product == null)throw new ArgumentNullException(nameof(product));- var customer = await _mediator.Send(new GetCustomerByIdQuery() { Id = bid.CustomerId });+ var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId });if (string.IsNullOrEmpty(languageId)){languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.csindex 4158652d0..fb0e9f4ed 100644--- a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs+++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs@@ -1,5 +1,5 @@-namespace Grand.Business.Messages+namespace Grand.Business.Messages.Services{public static class MessageTemplateNames{diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.csindex b47bdd8ce..db48ad254 100644--- a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs+++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs@@ -10,7 +10,7 @@ using MediatR;namespace Grand.Business.Messages.Services{- public partial class MessageTemplateService : IMessageTemplateService+ public class MessageTemplateService : IMessageTemplateService{#region Fields@@ -124,7 +124,7 @@ namespace Grand.Business.Messages.Servicesvar templates = await Task.FromResult(query.ToList());//store acl- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId)){templates = templates.Where(t => _aclService.Authorize(t, storeId))diff --git a/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs b/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.csindex ea88f78cd..582623eda 100644--- a/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs+++ b/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs@@ -3,9 +3,8 @@ using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;namespace Grand.Business.Messages.Services{- public partial class MessageTokenProvider : IMessageTokenProvider+ public class MessageTokenProvider : IMessageTokenProvider{-#region Methods/// <summary>diff --git a/src/Business/Grand.Business.Messages/Services/MimeMappingService.cs b/src/Business/Grand.Business.Messages/Services/MimeMappingService.csindex 0a54acbe0..84a6aa5c1 100644--- a/src/Business/Grand.Business.Messages/Services/MimeMappingService.cs+++ b/src/Business/Grand.Business.Messages/Services/MimeMappingService.cs@@ -3,7 +3,7 @@ using Microsoft.AspNetCore.StaticFiles;namespace Grand.Business.Messages.Services{- public partial class MimeMappingService : IMimeMappingService+ public class MimeMappingService : IMimeMappingService{private readonly FileExtensionContentTypeProvider _contentTypeProvider;diff --git a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.csindex fdfe76817..eea13ead2 100644--- a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs+++ b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs@@ -8,7 +8,7 @@ using Grand.Domain.Common;namespace Grand.Business.Messages.Services{- public partial class QueuedEmailService : IQueuedEmailService+ public class QueuedEmailService : IQueuedEmailService{private readonly IRepository<QueuedEmail> _queuedEmailRepository;private readonly IMediator _mediator;diff --git a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.csindex 67cde7ad5..660b08f1e 100644--- a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Storage.Services/// <summary>/// Picture service for Amazon/// </summary>- public partial class AmazonPictureService : PictureService+ public class AmazonPictureService : PictureService{#region Fields@@ -86,10 +86,10 @@ namespace Grand.Business.Storage.Services_bucketExist = await _s3Client.DoesS3BucketExistAsync(_bucketName);while (_bucketExist == false){- S3Region s3region = S3Region.FindValue(_config.AmazonRegion);+ S3Region s3Region = S3Region.FindValue(_config.AmazonRegion);var putBucketRequest = new PutBucketRequest {BucketName = _bucketName,- BucketRegion = s3region,+ BucketRegion = s3Region,};try@@ -151,9 +151,7 @@ namespace Grand.Business.Storage.Services{return await Task.FromResult($"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}");}- else- return await Task.FromResult($"https://{_distributionDomainName}/{thumbFileName}");-+ return await Task.FromResult($"https://{_distributionDomainName}/{thumbFileName}");}/// <summary>@@ -164,19 +162,12 @@ namespace Grand.Business.Storage.Services/// <returns>Local picture thumb path</returns>protected override string GetThumbUrl(string thumbFileName, string storeLocation = null){- if (string.IsNullOrEmpty(_distributionDomainName))- {- return $"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}";- }- else- return $"https://{_distributionDomainName}/{thumbFileName}";-+ return string.IsNullOrEmpty(_distributionDomainName) ? $"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}" : $"https://{_distributionDomainName}/{thumbFileName}";}/// <summary>/// Save a value indicating whether some file (thumb) already exists/// </summary>- /// <param name="thumbFilePath">Thumb file path (unused in Amazon S3)</param>/// <param name="thumbFileName">Thumb file name</param>/// <param name="binary">Picture binary</param>protected override Task SaveThumb(string thumbFileName, byte[] binary)diff --git a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs b/src/Business/Grand.Business.Storage/Services/AzurePictureService.csindex 2a72c3aa6..bb48e9918 100644--- a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs@@ -15,11 +15,11 @@ namespace Grand.Business.Storage.Services/// <summary>/// Picture service for Windows Azure/// </summary>- public partial class AzurePictureService : PictureService+ public class AzurePictureService : PictureService{#region Fields- private static BlobContainerClient container = null;+ private static BlobContainerClient _container = null;private readonly AzureConfig _config;private readonly IMimeMappingService _mimeMappingService;@@ -57,7 +57,7 @@ namespace Grand.Business.Storage.Servicesif (string.IsNullOrEmpty(_config.AzureBlobStorageEndPoint))throw new Exception("Azure end point for BLOB is not specified");- container = new BlobContainerClient(_config.AzureBlobStorageConnectionString, _config.AzureBlobStorageContainerName);+ _container = new BlobContainerClient(_config.AzureBlobStorageConnectionString, _config.AzureBlobStorageContainerName);}@@ -71,12 +71,12 @@ namespace Grand.Business.Storage.Services/// <param name="picture">Picture</param>protected override async Task DeletePictureThumbs(Picture picture){- string filter = string.Format("{0}", picture.Id);- var blobs = container.GetBlobs(Azure.Storage.Blobs.Models.BlobTraits.All, Azure.Storage.Blobs.Models.BlobStates.All, filter);+ var filter = $"{picture.Id}";+ var blobs = _container.GetBlobs(BlobTraits.All, BlobStates.All, filter);foreach (var blob in blobs){- await container.DeleteBlobAsync(blob.Name);+ await _container.DeleteBlobAsync(blob.Name);}}@@ -88,7 +88,7 @@ namespace Grand.Business.Storage.Servicesprotected override async Task<string> GetThumbPhysicalPath(string thumbFileName){var thumbFilePath = $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}/{thumbFileName}";- var blobClient = container.GetBlobClient(thumbFileName);+ var blobClient = _container.GetBlobClient(thumbFileName);bool exists = await blobClient.ExistsAsync();return exists? thumbFilePath : string.Empty;}@@ -115,11 +115,11 @@ namespace Grand.Business.Storage.Services{Stream stream = new MemoryStream(binary);- container.UploadBlob(thumbFileName, stream);+ _container.UploadBlob(thumbFileName, stream);//Update content type and other properties- string contentType = _mimeMappingService.Map(thumbFileName);- var blobClient = container.GetBlobClient(thumbFileName);+ var contentType = _mimeMappingService.Map(thumbFileName);+ var blobClient = _container.GetBlobClient(thumbFileName);BlobProperties properties = blobClient.GetProperties();BlobHttpHeaders blobHttpHeaders = new BlobHttpHeaders {// Set the MIME ContentType every time the propertiesdiff --git a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.csindex aaafb8033..f110b83bb 100644--- a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs+++ b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs@@ -25,9 +25,9 @@ namespace Grand.Business.Storage.Services{return _fileStore.GetDirectoryInfo(path);}- public virtual Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directorypath)+ public virtual Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath){- return _fileStore.GetPhysicalDirectoryInfo(directorypath);+ return _fileStore.GetPhysicalDirectoryInfo(directoryPath);}public virtual IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true)diff --git a/src/Business/Grand.Business.Storage/Services/DownloadService.cs b/src/Business/Grand.Business.Storage/Services/DownloadService.csindex bf1ac6f70..3ff67cf2f 100644--- a/src/Business/Grand.Business.Storage/Services/DownloadService.cs+++ b/src/Business/Grand.Business.Storage/Services/DownloadService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.Storage.Services/// <summary>/// Download service/// </summary>- public partial class DownloadService : IDownloadService+ public class DownloadService : IDownloadService{#region Fields@@ -50,11 +50,11 @@ namespace Grand.Business.Storage.Servicesif (string.IsNullOrEmpty(downloadId))return null;- var _download = await _downloadRepository.GetByIdAsync(downloadId);- if (_download != null && !_download.UseDownloadUrl)- _download.DownloadBinary = await DownloadAsBytes(_download.DownloadObjectId);+ var download = await _downloadRepository.GetByIdAsync(downloadId);+ if (download is { UseDownloadUrl: false })+ download.DownloadBinary = await DownloadAsBytes(download.DownloadObjectId);- return _download;+ return download;}protected virtual async Task<byte[]> DownloadAsBytes(string objectId)@@ -77,7 +77,7 @@ namespace Grand.Business.Storage.Servicesselect o;var order = query.FirstOrDefault();- if (!order.UseDownloadUrl)+ if (order is { UseDownloadUrl: false })order.DownloadBinary = await DownloadAsBytes(order.DownloadObjectId);return await Task.FromResult(order);diff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStore.csindex 448e784cb..6bd1e731f 100644--- a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs+++ b/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs@@ -20,12 +20,7 @@ namespace Grand.Business.Storage.Servicesvar fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath));- if (fileInfo.Exists)- {- return Task.FromResult<IFileStoreEntry>(new FileSystemStoreEntry(path, fileInfo));- }-- return Task.FromResult<IFileStoreEntry>(null);+ return Task.FromResult<IFileStoreEntry>(fileInfo.Exists ? new FileSystemStoreEntry(path, fileInfo) : null);}public IFileStoreEntry GetDirectoryInfo(string path)@@ -34,26 +29,16 @@ namespace Grand.Business.Storage.Servicesvar directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));- if (directoryInfo.Exists)- {- return new FileSystemStoreEntry(path, directoryInfo);- }-- return null;+ return directoryInfo.Exists ? new FileSystemStoreEntry(path, directoryInfo) : null;}- public Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directorypath)+ public Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath){- var physicalPath = GetPhysicalPath(directorypath);+ var physicalPath = GetPhysicalPath(directoryPath);var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));- if (directoryInfo.Exists)- {- return Task.FromResult(directoryInfo);- }-- return Task.FromResult<PhysicalDirectoryInfo>(null);+ return directoryInfo.Exists ? Task.FromResult(directoryInfo) : Task.FromResult<PhysicalDirectoryInfo>(null);}public IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true){@@ -97,11 +82,9 @@ namespace Grand.Business.Storage.Servicespublic bool TryCreateDirectory(string path){var physicalPath = GetPhysicalPath(path);-+if (File.Exists(physicalPath))- {throw new Exception($"Cannot create directory because the path '{path}' already exists and is a file.");- }if (Directory.Exists(physicalPath)){@@ -270,10 +253,8 @@ namespace Grand.Business.Storage.ServicesDirectory.CreateDirectory(physicalDirectoryPath);var fileInfo = new FileInfo(physicalPath);- using (var outputStream = fileInfo.Create())- {- await inputStream.CopyToAsync(outputStream);- }+ await using var outputStream = fileInfo.Create();+ await inputStream.CopyToAsync(outputStream);return path;}diff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.csindex 21d4aa62b..55e59221f 100644--- a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs+++ b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Storage.Servicespublic string Path => _path;public string Name => _fileInfo.Name;- public string DirectoryPath => _path[0..(_path.Length - Name.Length)].TrimEnd('/');+ public string DirectoryPath => _path[0..^Name.Length].TrimEnd('/');public string PhysicalPath => _fileInfo.PhysicalPath;public DateTime LastModifiedUtc => _fileInfo.LastModified.UtcDateTime;public long Length => _fileInfo.Length;diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.csindex 59fb46c5b..59dda0a1a 100644--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs@@ -19,7 +19,7 @@ namespace Grand.Business.Storage.Services/// <summary>/// Picture service/// </summary>- public partial class PictureService : IPictureService+ public class PictureService : IPictureService{#region Fields@@ -47,6 +47,7 @@ namespace Grand.Business.Storage.Services/// <param name="cacheBase">Cache manager</param>/// <param name="mediaFileStore">Media file storage</param>/// <param name="mediaSettings">Media settings</param>+ /// <param name="storageSettings">Storage settings</param>public PictureService(IRepository<Picture> pictureRepository,ILogger logger,IMediator mediator,@@ -75,13 +76,13 @@ namespace Grand.Business.Storage.Services/// </summary>/// <param name="mimeType">Mime type</param>/// <returns>File extension</returns>- protected virtual string GetFileExtensionFromMimeType(string mimeType)+ private string GetFileExtensionFromMimeType(string mimeType){if (mimeType == null)return null;- string[] parts = mimeType.Split('/');- string lastPart = parts[parts.Length - 1];+ var parts = mimeType.Split('/');+ var lastPart = parts[^1];switch (lastPart){case "pjpeg":@@ -107,13 +108,13 @@ namespace Grand.Business.Storage.Services/// <returns>Picture binary</returns>protected virtual async Task<byte[]> LoadPictureFromFile(string pictureId, string mimeType){- string lastPart = GetFileExtensionFromMimeType(mimeType);- string fileName = string.Format("{0}_0.{1}", pictureId, lastPart);+ var lastPart = GetFileExtensionFromMimeType(mimeType);+ var fileName = $"{pictureId}_0.{lastPart}";var filePath = await GetPicturePhysicalPath(fileName);if (string.IsNullOrEmpty(filePath))- return new byte[0];+ return Array.Empty<byte>();- return File.ReadAllBytes(filePath);+ return await File.ReadAllBytesAsync(filePath);}@@ -123,22 +124,20 @@ namespace Grand.Business.Storage.Services/// <param name="picture">Picture</param>protected virtual Task DeletePictureThumbs(Picture picture){- string filter = string.Format("{0}*.*", picture.Id);+ var filter = $"{picture.Id}*.*";var thumbDirectoryPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);- if (thumbDirectoryPath != null)+ if (thumbDirectoryPath == null) return Task.CompletedTask;+ var currentFiles = Directory.GetFiles(thumbDirectoryPath.PhysicalPath, filter, SearchOption.AllDirectories);+ foreach (var currentFileName in currentFiles){- string[] currentFiles = Directory.GetFiles(thumbDirectoryPath.PhysicalPath, filter, SearchOption.AllDirectories);- foreach (string currentFileName in currentFiles)+ try{- try- {- if (File.Exists(currentFileName))- File.Delete(currentFileName);- }- catch (Exception ex)- {- _logger.InsertLog(Domain.Logging.LogLevel.Error, ex.Message);- }+ if (File.Exists(currentFileName))+ File.Delete(currentFileName);+ }+ catch (Exception ex)+ {+ _logger.InsertLog(Domain.Logging.LogLevel.Error, ex.Message);}}return Task.CompletedTask;@@ -180,8 +179,8 @@ namespace Grand.Business.Storage.Services/// <returns>Physical picture path</returns>protected virtual async Task<string> GetPicturePhysicalPath(string fileName){- var fileinfo = await _mediaFileStore.GetFileInfo(_mediaFileStore.Combine(CommonPath.ImagePath, fileName));- return fileinfo?.PhysicalPath;+ var fileInfo = await _mediaFileStore.GetFileInfo(_mediaFileStore.Combine(CommonPath.ImagePath, fileName));+ return fileInfo?.PhysicalPath;}/// <summary>@@ -281,33 +280,28 @@ namespace Grand.Business.Storage.Services_workContext.CurrentStore.SslEnabled ? _workContext.CurrentStore.SecureUrl : _workContext.CurrentStore.Url :_mediaFileStore.Combine(_mediaSettings.StoreLocation, CommonPath.ImagePath, _mediaSettings.DefaultImageName);}- else- {- string fileExtension = Path.GetExtension(filePath);- string thumbFileName = string.Format("{0}_{1}{2}",- Path.GetFileNameWithoutExtension(filePath),- targetSize,- fileExtension);- var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);+ var fileExtension = Path.GetExtension(filePath);+ var thumbFileName = $"{Path.GetFileNameWithoutExtension(filePath)}_{targetSize}{fileExtension}";- if (!string.IsNullOrEmpty(thumbFilePath))- return GetThumbUrl(thumbFileName, storeLocation);+ var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);++ if (!string.IsNullOrEmpty(thumbFilePath))+ return GetThumbUrl(thumbFileName, storeLocation);- using (var mutex = new Mutex(false, thumbFileName))+ using (var mutex = new Mutex(false, thumbFileName))+ {+ mutex.WaitOne();+ using (var image = SKBitmap.Decode(filePath)){- mutex.WaitOne();- using (var image = SKBitmap.Decode(filePath))- {- var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);- if (pictureBinary != null)- await SaveThumb(thumbFileName, pictureBinary);- }- mutex.ReleaseMutex();+ var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);+ if (pictureBinary != null)+ await SaveThumb(thumbFileName, pictureBinary);}- var url = GetThumbUrl(thumbFileName, storeLocation);- return url;+ mutex.ReleaseMutex();}+ var url = GetThumbUrl(thumbFileName, storeLocation);+ return url;}/// <summary>@@ -361,9 +355,8 @@ namespace Grand.Business.Storage.Servicesif (targetSize == 0){- thumbFileName = !string.IsNullOrEmpty(seoFileName) ?- string.Format("{0}_{1}.{2}", picture.Id, seoFileName, lastPart) :- string.Format("{0}.{1}", picture.Id, lastPart);+ thumbFileName = !string.IsNullOrEmpty(seoFileName) ? $"{picture.Id}_{seoFileName}.{lastPart}"+ : $"{picture.Id}.{lastPart}";var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);@@ -372,18 +365,15 @@ namespace Grand.Business.Storage.Servicesvar pictureBinary = await LoadPictureBinary(picture);- using (var mutex = new Mutex(false, thumbFileName))- {- mutex.WaitOne();- await SaveThumb(thumbFileName, pictureBinary);- mutex.ReleaseMutex();- }+ using var mutex = new Mutex(false, thumbFileName);+ mutex.WaitOne();+ await SaveThumb(thumbFileName, pictureBinary);+ mutex.ReleaseMutex();}else{- thumbFileName = !string.IsNullOrEmpty(seoFileName) ?- string.Format("{0}_{1}_{2}.{3}", picture.Id, seoFileName, targetSize, lastPart) :- string.Format("{0}_{1}.{2}", picture.Id, targetSize, lastPart);+ thumbFileName = !string.IsNullOrEmpty(seoFileName) ? $"{picture.Id}_{seoFileName}_{targetSize}.{lastPart}"+ : $"{picture.Id}_{targetSize}.{lastPart}";var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);@@ -392,24 +382,25 @@ namespace Grand.Business.Storage.Servicesvar pictureBinary = await LoadPictureBinary(picture);- using (var mutex = new Mutex(false, thumbFileName))+ using var mutex = new Mutex(false, thumbFileName);+ mutex.WaitOne();+ if (pictureBinary != null){- mutex.WaitOne();- if (pictureBinary != null)+ try{- try- {- using var image = SKBitmap.Decode(pictureBinary);- var resizedbinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);- if (resizedbinary != null)- pictureBinary = resizedbinary;- }- catch { }+ 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);++ mutex.ReleaseMutex();}return GetThumbUrl(thumbFileName, storeLocation);}@@ -423,7 +414,7 @@ namespace Grand.Business.Storage.Services/// <returns></returns>public virtual async Task<string> GetThumbPhysicalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true){- string url = await GetPictureUrl(picture, targetSize, showDefaultPicture);+ var url = await GetPictureUrl(picture, targetSize, showDefaultPicture);if (string.IsNullOrEmpty(url))return string.Empty;@@ -497,7 +488,7 @@ namespace Grand.Business.Storage.Servicesthrow new ArgumentNullException(nameof(picture));var lastPart = GetFileExtensionFromMimeType(picture.MimeType);- var fileName = string.Format("{0}_0.{1}", picture.Id, lastPart);+ var fileName = $"{picture.Id}_0.{lastPart}";var filePath = await GetPicturePhysicalPath(fileName);if (!string.IsNullOrEmpty(filePath)){@@ -569,7 +560,7 @@ namespace Grand.Business.Storage.ServicespictureBinary = ValidatePicture(pictureBinary, mimeType);var picture = new Picture {- PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : new byte[0],+ PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : Array.Empty<byte>(),MimeType = mimeType,SeoFilename = seoFilename,AltAttribute = altAttribute,@@ -599,13 +590,13 @@ namespace Grand.Business.Storage.Services/// <param name="altAttribute">"alt" attribute for "img" HTML element</param>/// <param name="titleAttribute">"title" attribute for "img" HTML element</param>/// <param name="style">style attribute for "img" HTML element</param>- /// <param name="extrafield">Extra field</param>+ /// <param name="extraField">Extra field</param>/// <param name="isNew">A value indicating whether the picture is new</param>/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>/// <returns>Picture</returns>public virtual async Task<Picture> UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType,string seoFilename, string altAttribute = null, string titleAttribute = null,- string style = null, string extrafield = null,+ string style = null, string extraField = null,bool isNew = true, bool validateBinary = true){mimeType = CommonHelper.EnsureNotNull(mimeType);@@ -645,7 +636,7 @@ namespace Grand.Business.Storage.Servicespicture.Style = style;await _pictureRepository.UpdateField(picture.Id, x => x.Style, picture.Style);- picture.ExtraField = extrafield;+ picture.ExtraField = extraField;await _pictureRepository.UpdateField(picture.Id, x => x.ExtraField, picture.ExtraField);picture.IsNew = isNew;@@ -688,13 +679,15 @@ namespace Grand.Business.Storage.Services/// Updates the picture/// </summary>/// <param name="picture">Picture</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>/// <returns>Picture</returns>public virtual async Task UpdatePictureField<T>(Picture picture, Expression<Func<Picture, T>> expression, T value){if (picture == null)throw new ArgumentNullException(nameof(picture));- await _pictureRepository.UpdateField<T>(picture.Id, expression, value);+ await _pictureRepository.UpdateField(picture.Id, expression, value);//event notificationawait _mediator.EntityUpdated(picture);@@ -713,15 +706,15 @@ namespace Grand.Business.Storage.Servicespublic virtual Task SavePictureInFile(string pictureId, byte[] pictureBinary, string mimeType){var lastPart = GetFileExtensionFromMimeType(mimeType);- var fileName = string.Format("{0}_0.{1}", pictureId, lastPart);- var dirpath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImagePath);- if (dirpath != null)+ var fileName = $"{pictureId}_0.{lastPart}";+ var dirPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImagePath);+ if (dirPath != null){- var filepath = _mediaFileStore.Combine(dirpath.PhysicalPath, fileName);+ var filepath = _mediaFileStore.Combine(dirPath.PhysicalPath, fileName);File.WriteAllBytes(filepath, pictureBinary);}else- _ = _logger.Error("Drirectory path not exist.");+ _ = _logger.Error("Directory path not exist.");return Task.CompletedTask;}@@ -738,25 +731,23 @@ namespace Grand.Business.Storage.Servicesthrow new ArgumentException("No picture found with the specified id");//update if it has been changed- if (seoFilename != picture.SeoFilename)- {- //update SeoFilename picture- picture.SeoFilename = seoFilename;- await UpdatePictureField(picture, p => p.SeoFilename, seoFilename);+ if (seoFilename == picture.SeoFilename) return picture;+ //update SeoFilename picture+ picture.SeoFilename = seoFilename;+ await UpdatePictureField(picture, p => p.SeoFilename, seoFilename);- //event notification- await _mediator.EntityUpdated(picture);+ //event notification+ await _mediator.EntityUpdated(picture);- //clare cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));- }+ //clare cache+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));return picture;}/// <summary>/// Validates input picture dimensions/// </summary>- /// <param name="pictureBinary">Picture binary</param>+ /// <param name="byteArray">Picture binary</param>/// <param name="mimeType">MIME type</param>/// <returns>Picture binary or throws an exception</returns>public virtual byte[] ValidatePicture(byte[] byteArray, string mimeType)@@ -764,29 +755,26 @@ namespace Grand.Business.Storage.Servicestry{var format = EncodedImageFormat(mimeType);- using (var ms = new MemoryStream(byteArray))+ using (new MemoryStream(byteArray)){using (var image = SKBitmap.Decode(byteArray)){if (image.Width >= image.Height){//horizontal rectangle or square- if (image.Width > _mediaSettings.MaximumImageSize && image.Height > _mediaSettings.MaximumImageSize)- {- var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);- if (resizedPicture != null)- byteArray = resizedPicture;- }+ if (image.Width <= _mediaSettings.MaximumImageSize ||+ image.Height <= _mediaSettings.MaximumImageSize) return byteArray;+ var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);+ if (resizedPicture != null)+ byteArray = resizedPicture;}else if (image.Width < image.Height){//vertical rectangle- if (image.Width > _mediaSettings.MaximumImageSize)- {- var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);- if (resizedPicture != null)- byteArray = resizedPicture;- }+ if (image.Width <= _mediaSettings.MaximumImageSize) return byteArray;+ var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);+ if (resizedPicture != null)+ byteArray = resizedPicture;}return byteArray;@@ -810,25 +798,30 @@ namespace Grand.Business.Storage.Services/// <returns>Picture binary or throws an exception</returns>public virtual byte[] ConvertPicture(byte[] pictureBinary, int imageQuality, string format = "Webp"){- Enum.TryParse(typeof(SKEncodedImageFormat), format, out var skformat);- if (skformat == null)- skformat = SKEncodedImageFormat.Webp;+ Enum.TryParse(typeof(SKEncodedImageFormat), format, out var skFormat);+ skFormat ??= SKEncodedImageFormat.Webp;using var image = SKBitmap.Decode(pictureBinary);- SKData d = SKImage.FromBitmap(image).Encode((SKEncodedImageFormat)skformat, imageQuality);+ SKData d = SKImage.FromBitmap(image).Encode((SKEncodedImageFormat)skFormat, imageQuality);return d.ToArray();}- protected SKEncodedImageFormat EncodedImageFormat(string mimetype)+ private SKEncodedImageFormat EncodedImageFormat(string mimetype){- SKEncodedImageFormat defaultFormat = SKEncodedImageFormat.Jpeg;+ const SKEncodedImageFormat defaultFormat = SKEncodedImageFormat.Jpeg;if (string.IsNullOrEmpty(mimetype))return defaultFormat;mimetype = mimetype.ToLower();- if (mimetype.Contains("jpeg") || mimetype.Contains("jpg") || mimetype.Contains("pjpeg"))+ if (mimetype.Contains("jpeg"))+ return defaultFormat;++ if (mimetype.Contains("jpg"))+ return defaultFormat;++ if (mimetype.Contains("pjpeg"))return defaultFormat;if (mimetype.Contains("png"))@@ -847,13 +840,10 @@ namespace Grand.Business.Storage.Servicesif (mimetype.Contains("bmp"))return SKEncodedImageFormat.Png;- if (mimetype.Contains("ico"))- return SKEncodedImageFormat.Ico;-- return defaultFormat;-+ return mimetype.Contains("ico") ? SKEncodedImageFormat.Ico : defaultFormat;}- protected byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize)++ private byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize){if (image == null)throw new ArgumentNullException(nameof(image));@@ -884,14 +874,10 @@ namespace Grand.Business.Storage.Servicestry{- using (var resized = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.High))- {- using (var resimage = SKImage.FromBitmap(resized))- {- var skdata = resimage.Encode(format, _mediaSettings.ImageQuality);- return skdata?.ToArray();- }- }+ using var resized = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.High);+ using var resImage = SKImage.FromBitmap(resized);+ var skData = resImage.Encode(format, _mediaSettings.ImageQuality);+ return skData?.ToArray();}catch (Exception ex){diff --git a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs b/src/Business/Grand.Business.Storage/Startup/StartupApplication.csindex ac2ca46f2..a9c9cb048 100644--- a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs@@ -17,13 +17,13 @@ namespace Grand.Business.Storage.Startupservices.AddScoped<IDownloadService, DownloadService>();//picture service- var azureconfig = new AzureConfig();- configuration.GetSection("Azure").Bind(azureconfig);- var useAzureBlobStorage = !string.IsNullOrEmpty(azureconfig.AzureBlobStorageConnectionString);+ var azureConfig = new AzureConfig();+ configuration.GetSection("Azure").Bind(azureConfig);+ var useAzureBlobStorage = !string.IsNullOrEmpty(azureConfig.AzureBlobStorageConnectionString);- var amazonconfig = new AmazonConfig();- configuration.GetSection("Amazon").Bind(amazonconfig);- var useAmazonBlobStorage = (!string.IsNullOrEmpty(amazonconfig.AmazonAwsAccessKeyId) && !string.IsNullOrEmpty(amazonconfig.AmazonAwsSecretAccessKey) && !string.IsNullOrEmpty(amazonconfig.AmazonBucketName) && !string.IsNullOrEmpty(amazonconfig.AmazonRegion));+ var amazonConfig = new AmazonConfig();+ configuration.GetSection("Amazon").Bind(amazonConfig);+ var useAmazonBlobStorage = !string.IsNullOrEmpty(amazonConfig.AmazonAwsAccessKeyId) && !string.IsNullOrEmpty(amazonConfig.AmazonAwsSecretAccessKey) && !string.IsNullOrEmpty(amazonConfig.AmazonBucketName) && !string.IsNullOrEmpty(amazonConfig.AmazonRegion);if (useAzureBlobStorage){diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.csindex 4b228418a..f07766457 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs@@ -31,19 +31,14 @@ namespace Grand.Business.System.Commands.Handlers.Catalogif (request.Product == null)throw new ArgumentNullException(nameof(request.Product));- int result = 0;-var subscriptions = await GetAllSubscriptionsByProductId(request.Product.Id, request.Attributes, request.Warehouse);foreach (var subscription in subscriptions){var customer = await _customerService.GetCustomerById(subscription.CustomerId);//ensure that customer is registered (simple and fast way)- if (customer != null && CommonHelper.IsValidEmail(customer.Email))- {- var customerLanguageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, subscription.StoreId);- await _messageProviderService.SendBackinStockMessage(customer, request.Product, subscription, customerLanguageId);- result++;- }+ if (customer == null || !CommonHelper.IsValidEmail(customer.Email)) continue;+ var customerLanguageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, subscription.StoreId);+ await _messageProviderService.SendBackInStockMessage(customer, request.Product, subscription, customerLanguageId);}return subscriptions;@@ -68,11 +63,11 @@ namespace Grand.Business.System.Commands.Handlers.Catalogquery = query.Where(biss => biss.WarehouseId == warehouseId).ToList();//attributes- if (attributes != null && attributes.Any())- foreach (var item in attributes)- {- query = query.Where(x => x.Attributes.Any(y => y.Key == item.Key && y.Value == item.Value)).ToList();- }+ if (attributes == null || !attributes.Any()) return await Task.FromResult(query.ToList());+ foreach (var item in attributes)+ {+ query = query.Where(x => x.Attributes.Any(y => y.Key == item.Key && y.Value == item.Value)).ToList();+ }return await Task.FromResult(query.ToList());}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Common/GetSitemapXMLCommandHandler.csindex 5be6fad1b..937cc6869 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs@@ -79,18 +79,16 @@ namespace Grand.Business.System.Commands.Handlers.Common}private string RemoveBom(string p){- string BOMMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());- if (p.StartsWith(BOMMarkUtf8))- p = p.Remove(0, BOMMarkUtf8.Length);+ var bomMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());+ if (p.StartsWith(bomMarkUtf8))+ p = p.Remove(0, bomMarkUtf8.Length);return p.Replace("\0", "");}private async Task<string> Generate(Language language, Store store){- using (var stream = new MemoryStream())- {- await Generate(stream, language, store);- return RemoveBom(Encoding.UTF8.GetString(stream.ToArray()));- }+ using var stream = new MemoryStream();+ await Generate(stream, language, store);+ return RemoveBom(Encoding.UTF8.GetString(stream.ToArray()));}private async Task Generate(Stream stream, Language language, Store store)@@ -105,7 +103,7 @@ namespace Grand.Business.System.Commands.Handlers.Common/// <summary>/// Represents sitemap URL/// </summary>- class SitemapUrl+ private class SitemapUrl{public SitemapUrl(string location, string image, UpdateFrequency frequency, DateTime updatedOn){@@ -194,7 +192,7 @@ namespace Grand.Business.System.Commands.Handlers.CommonsitemapUrls.Add(new SitemapUrl(url, string.Empty, UpdateFrequency.Weekly, DateTime.UtcNow));}- //knowledgebase+ //knowledge baseif (_knowledgebaseSettings.Enabled){var url = _linkGenerator.GetUriByRouteValues("Knowledgebase", routeValues, GetHttpProtocol(), GetHost());@@ -203,7 +201,7 @@ namespace Grand.Business.System.Commands.Handlers.Common//categoriesif (_commonSettings.SitemapIncludeCategories)- sitemapUrls.AddRange(await GetCategoryUrls("", language, store));+ sitemapUrls.AddRange(await GetCategoryUrls("", language));//brandsif (_commonSettings.SitemapIncludeBrands)@@ -219,7 +217,7 @@ namespace Grand.Business.System.Commands.Handlers.Common//blog postssitemapUrls.AddRange(await GetBlogPostsUrls(language, store));- //knowledgebase articles+ //knowledge base articlessitemapUrls.AddRange(await GetKnowledgebaseUrls(language));//custom URLs@@ -228,7 +226,7 @@ namespace Grand.Business.System.Commands.Handlers.Commonreturn sitemapUrls;}- private async Task<IEnumerable<SitemapUrl>> GetCategoryUrls(string parentCategoryId, Language language, Store store)+ private async Task<IEnumerable<SitemapUrl>> GetCategoryUrls(string parentCategoryId, Language language){var allCategoriesByParentCategoryId = await _categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId: parentCategoryId);var categories = new List<SitemapUrl>();@@ -251,7 +249,7 @@ namespace Grand.Business.System.Commands.Handlers.Common}}categories.Add(new SitemapUrl(url, imageurl, UpdateFrequency.Weekly, category.UpdatedOnUtc));- categories.AddRange(await GetCategoryUrls(category.Id, language, store));+ categories.AddRange(await GetCategoryUrls(category.Id, language));}return categories;}@@ -259,7 +257,7 @@ namespace Grand.Business.System.Commands.Handlers.Commonprivate async Task<IEnumerable<SitemapUrl>> GetBrandUrls(Language language, Store store){var brands = await _brandService.GetAllBrands(storeId: store.Id);- var _brands = new List<SitemapUrl>();+ var brandUrls = new List<SitemapUrl>();var storeLocation = GetStoreLocation();foreach (var brand in brands){@@ -269,17 +267,17 @@ namespace Grand.Business.System.Commands.Handlers.Common:_linkGenerator.GetUriByRouteValues("Brand", new { SeName = brand.GetSeName(language.Id) }, GetHttpProtocol(), GetHost());- var imageurl = string.Empty;+ var imageUrl = string.Empty;if (_commonSettings.SitemapIncludeImage){if (!string.IsNullOrEmpty(brand.PictureId)){- imageurl = await _pictureService.GetPictureUrl(brand.PictureId, showDefaultPicture: false, storeLocation: storeLocation);+ imageUrl = await _pictureService.GetPictureUrl(brand.PictureId, showDefaultPicture: false, storeLocation: storeLocation);}}- _brands.Add(new SitemapUrl(url, imageurl, UpdateFrequency.Weekly, brand.UpdatedOnUtc));+ brandUrls.Add(new SitemapUrl(url, imageUrl, UpdateFrequency.Weekly, brand.UpdatedOnUtc));}- return _brands;+ return brandUrls;}private async Task<IEnumerable<SitemapUrl>> GetProductUrls(Language language, Store store)@@ -296,15 +294,15 @@ namespace Grand.Business.System.Commands.Handlers.Common:_linkGenerator.GetUriByRouteValues("Product", new { SeName = product.GetSeName(language.Id) }, GetHttpProtocol(), GetHost());- var imageurl = string.Empty;+ var imageUrl = string.Empty;if (_commonSettings.SitemapIncludeImage){if (!string.IsNullOrEmpty(product.ProductPictures.FirstOrDefault()?.PictureId)){- imageurl = await _pictureService.GetPictureUrl(product.ProductPictures.FirstOrDefault().PictureId, showDefaultPicture: false, storeLocation: storeLocation);+ imageUrl = await _pictureService.GetPictureUrl(product.ProductPictures.FirstOrDefault()?.PictureId, showDefaultPicture: false, storeLocation: storeLocation);}}- products.Add(new SitemapUrl(url, imageurl, UpdateFrequency.Weekly, product.UpdatedOnUtc));+ products.Add(new SitemapUrl(url, imageUrl, UpdateFrequency.Weekly, product.UpdatedOnUtc));}return products;@@ -357,19 +355,12 @@ namespace Grand.Business.System.Commands.Handlers.Commonprivate async Task<IEnumerable<SitemapUrl>> GetKnowledgebaseUrls(Language language){var knowledgebasearticles = await _knowledgebaseService.GetPublicKnowledgebaseArticles();- var knowledgebase = new List<SitemapUrl>();- foreach (var knowledgebasearticle in knowledgebasearticles)- {- var url =- _appConfig.SeoFriendlyUrlsForLanguagesEnabled ?- _linkGenerator.GetUriByRouteValues("KnowledgebaseArticle", new { SeName = knowledgebasearticle.GetSeName(language.Id), language = language.UniqueSeoCode }, GetHttpProtocol(), GetHost())- :- _linkGenerator.GetUriByRouteValues("KnowledgebaseArticle", new { SeName = knowledgebasearticle.GetSeName(language.Id) }, GetHttpProtocol(), GetHost());- knowledgebase.Add(new SitemapUrl(url, string.Empty, UpdateFrequency.Weekly, DateTime.UtcNow));- }-- return knowledgebase;+ return knowledgebasearticles.Select(knowledgebasearticle => _appConfig.SeoFriendlyUrlsForLanguagesEnabled+ ? _linkGenerator.GetUriByRouteValues("KnowledgebaseArticle", new { SeName = knowledgebasearticle.GetSeName(language.Id), language = language.UniqueSeoCode }, GetHttpProtocol(), GetHost())+ : _linkGenerator.GetUriByRouteValues("KnowledgebaseArticle", new { SeName = knowledgebasearticle.GetSeName(language.Id) }, GetHttpProtocol(), GetHost()))+ .Select(url => new SitemapUrl(url, string.Empty, UpdateFrequency.Weekly, DateTime.UtcNow))+ .ToList();}private IEnumerable<SitemapUrl> GetCustomUrls()@@ -385,20 +376,18 @@ namespace Grand.Business.System.Commands.Handlers.Commonif (str == null)return null;str = Regex.Replace(str, @"[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]", "", RegexOptions.Compiled);- if (str == null)+ if (string.IsNullOrEmpty(str))return null;var xwSettings = new XmlWriterSettings{ConformanceLevel = ConformanceLevel.Auto};- using (var sw = new StringWriter())- using (var xwr = XmlWriter.Create(sw, xwSettings))- {- xwr.WriteString(str);- xwr.Flush();- return sw.ToString();- }+ using var sw = new StringWriter();+ using var xwr = XmlWriter.Create(sw, xwSettings);+ xwr.WriteString(str);+ xwr.Flush();+ return sw.ToString();}@@ -414,38 +403,36 @@ namespace Grand.Business.System.Commands.Handlers.CommonAsync = true};- using (var writer = XmlWriter.Create(stream, xwSettings))- {- await writer.WriteStartDocumentAsync();- writer.WriteStartElement("urlset");- await writer.WriteAttributeStringAsync("urlset", "xmlns", null, "http://www.sitemaps.org/schemas/sitemap/0.9");-- if (_commonSettings.SitemapIncludeImage)- await writer.WriteAttributeStringAsync("xmlns", "image", null, "http://www.google.com/schemas/sitemap-image/1.1");+ await using var writer = XmlWriter.Create(stream, xwSettings);+ await writer.WriteStartDocumentAsync();+ writer.WriteStartElement("urlset");+ await writer.WriteAttributeStringAsync("urlset", "xmlns", null, "http://www.sitemaps.org/schemas/sitemap/0.9");- await writer.WriteAttributeStringAsync("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");+ if (_commonSettings.SitemapIncludeImage)+ await writer.WriteAttributeStringAsync("xmlns", "image", null, "http://www.google.com/schemas/sitemap-image/1.1");- foreach (var url in sitemapUrls)- {- writer.WriteStartElement("url");- var location = XmlEncode(url.Location);- writer.WriteElementString("loc", location);+ await writer.WriteAttributeStringAsync("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");- if (_commonSettings.SitemapIncludeImage && !string.IsNullOrEmpty(url.Image))- {- writer.WriteStartElement("image", "image", null);- writer.WriteElementString("image", "loc", null, url.Image);- writer.WriteEndElement();- }+ foreach (var url in sitemapUrls)+ {+ writer.WriteStartElement("url");+ var location = XmlEncode(url.Location);+ writer.WriteElementString("loc", location);- writer.WriteElementString("changefreq", url.UpdateFrequency.ToString().ToLowerInvariant());- writer.WriteElementString("lastmod", url.UpdatedOn.ToString(DateFormat));+ if (_commonSettings.SitemapIncludeImage && !string.IsNullOrEmpty(url.Image))+ {+ writer.WriteStartElement("image", "image", null);+ writer.WriteElementString("image", "loc", null, url.Image);writer.WriteEndElement();}- await writer.WriteEndElementAsync();- await writer.FlushAsync();+ writer.WriteElementString("changefreq", url.UpdateFrequency.ToString().ToLowerInvariant());+ writer.WriteElementString("lastmod", url.UpdatedOn.ToString(DateFormat));+ writer.WriteEndElement();}++ await writer.WriteEndElementAsync();+ await writer.FlushAsync();}}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAttributeCombinationTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAttributeCombinationTokensCommandHandler.csindex 2d3fceaf1..ead211cfc 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAttributeCombinationTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAttributeCombinationTokensCommandHandler.cs@@ -1,4 +1,4 @@-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using Grand.Domain.Catalog;@@ -18,9 +18,10 @@ namespace Grand.Business.System.Commands.Handlers.Messagespublic async Task<LiquidAttributeCombination> Handle(GetAttributeCombinationTokensCommand request, CancellationToken cancellationToken){- var liquidAttributeCombination = new LiquidAttributeCombination(request.Combination);- liquidAttributeCombination.Formatted = await _productAttributeFormatter.FormatAttributes(request.Product, request.Combination.Attributes, null, renderPrices: false);- liquidAttributeCombination.SKU = request.Product.FormatSku(request.Combination.Attributes);+ var liquidAttributeCombination = new LiquidAttributeCombination(request.Combination) {+ Formatted = await _productAttributeFormatter.FormatAttributes(request.Product, request.Combination.Attributes, null, renderPrices: false),+ SKU = request.Product.FormatSku(request.Combination.Attributes)+ };return liquidAttributeCombination;}}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.csindex e99c781cd..cc9d34fca 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs@@ -1,8 +1,9 @@using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;+using System.Globalization;namespace Grand.Business.System.Commands.Handlers.Messages{@@ -27,7 +28,7 @@ namespace Grand.Business.System.Commands.Handlers.Messagesvar liquidAuctions = new LiquidAuctions(request.Product, request.Bid);var defaultCurrency = await _currencyService.GetPrimaryStoreCurrency();liquidAuctions.Price = _priceFormatter.FormatPrice(request.Bid.Amount, defaultCurrency);- liquidAuctions.EndTime = _dateTimeService.ConvertToUserTime(request.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc).ToString();+ liquidAuctions.EndTime = _dateTimeService.ConvertToUserTime(request.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc).ToString(CultureInfo.InvariantCulture);return liquidAuctions;}}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetGiftVoucherTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetGiftVoucherTokensCommandHandler.csindex 62d1d2fa8..6a74a9dbc 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetGiftVoucherTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetGiftVoucherTokensCommandHandler.cs@@ -1,5 +1,5 @@using Grand.Business.Core.Interfaces.Catalog.Prices;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.csindex 10780d0ea..0bfa1d59d 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs@@ -2,7 +2,7 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;@@ -38,15 +38,15 @@ namespace Grand.Business.System.Commands.Handlers.MessagesliquidMerchandiseReturn.PickupAddressCountry =!string.IsNullOrEmpty(request.MerchandiseReturn.PickupAddress.CountryId) ?- (country?.GetTranslation(x => x.Name, request.Language.Id)) : "";+ country?.GetTranslation(x => x.Name, request.Language.Id) : "";foreach (var merchandiseReturnItem in request.MerchandiseReturn.MerchandiseReturnItems){var orderItem = request.Order.OrderItems.Where(x => x.Id == merchandiseReturnItem.OrderItemId).First();var product = await _productService.GetProductById(orderItem.ProductId);- var liqitem = new LiquidMerchandiseReturnItem(merchandiseReturnItem, orderItem, product, request.Order.CustomerLanguageId);+ var liquidItem = new LiquidMerchandiseReturnItem(merchandiseReturnItem, orderItem, product, request.Order.CustomerLanguageId);- liquidMerchandiseReturn.Items.Add(liqitem);+ liquidMerchandiseReturn.Items.Add(liquidItem);}return liquidMerchandiseReturn;diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetOrderTokensCommandHandler.csindex 115541431..cde56d4ed 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs@@ -1,4 +1,4 @@-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Catalog.Products;@@ -11,10 +11,10 @@ using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using Grand.Domain.Catalog;using Grand.Domain.Orders;-using Grand.Domain.Shipping;using Grand.Domain.Tax;using Grand.Domain.Vendors;using MediatR;+using System.Globalization;using System.Net;namespace Grand.Business.System.Commands.Handlers.Messages@@ -70,63 +70,53 @@ namespace Grand.Business.System.Commands.Handlers.Messages{var product = await _productService.GetProductById(item.ProductId);Vendor vendorItem = string.IsNullOrEmpty(item.VendorId) ? null : await _vendorService.GetVendorById(item.VendorId);- var liqitem = new LiquidOrderItem(item, product, language, request.Store, request.Host, vendorItem);+ var liquidItem = new LiquidOrderItem(item, product, language, request.Store, request.Host, vendorItem);#region Download- liqitem.IsDownloadAllowed = request.Order.IsDownloadAllowed(item, product);- liqitem.IsLicenseDownloadAllowed = request.Order.IsLicenseDownloadAllowed(item, product);+ liquidItem.IsDownloadAllowed = request.Order.IsDownloadAllowed(item, product);+ liquidItem.IsLicenseDownloadAllowed = request.Order.IsLicenseDownloadAllowed(item, product);#endregion#region Unit price- string unitPriceStr;- if (request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax)- {++ var unitPriceStr =//including tax- unitPriceStr = _priceFormatter.FormatPrice(item.UnitPriceInclTax, currency, language, true);- }- else- {+ request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax ? _priceFormatter.FormatPrice(item.UnitPriceInclTax, currency, language, true) ://excluding tax- unitPriceStr = _priceFormatter.FormatPrice(item.UnitPriceExclTax, currency, language, false);- }- liqitem.UnitPrice = unitPriceStr;+ _priceFormatter.FormatPrice(item.UnitPriceExclTax, currency, language, false);+ liquidItem.UnitPrice = unitPriceStr;#endregion#region total price- string priceStr;- if (request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax)- {++ var priceStr =//including tax- priceStr = _priceFormatter.FormatPrice(item.PriceInclTax, currency, language, true);- }- else- {+ request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax ? _priceFormatter.FormatPrice(item.PriceInclTax, currency, language, true) ://excluding tax- priceStr = _priceFormatter.FormatPrice(item.PriceExclTax, currency, language, false);- }- liqitem.TotalPrice = priceStr;+ _priceFormatter.FormatPrice(item.PriceExclTax, currency, language, false);+ liquidItem.TotalPrice = priceStr;#endregion- string sku = "";+ var sku = "";if (product != null)sku = product.FormatSku(item.Attributes);- liqitem.ProductSku = WebUtility.HtmlEncode(sku);- liquidOrder.OrderItems.Add(liqitem);+ liquidItem.ProductSku = WebUtility.HtmlEncode(sku);+ liquidOrder.OrderItems.Add(liquidItem);}var billingCountry = await _countryService.GetCountryById(request.Order.BillingAddress?.CountryId);liquidOrder.BillingCustomAttributes = await _addressAttributeParser.FormatAttributes(language, request.Order.BillingAddress?.Attributes);liquidOrder.BillingCountry = request.Order.BillingAddress != null && !string.IsNullOrEmpty(request.Order.BillingAddress.CountryId) ? billingCountry?.GetTranslation(x => x.Name, request.Order.CustomerLanguageId) : "";- liquidOrder.BillingStateProvince = !string.IsNullOrEmpty(request.Order.BillingAddress.StateProvinceId) ? billingCountry?.StateProvinces.FirstOrDefault(x => x.Id == request.Order.BillingAddress.StateProvinceId)?.GetTranslation(x => x.Name, request.Order.CustomerLanguageId) : "";+ liquidOrder.BillingStateProvince = !string.IsNullOrEmpty(request.Order.BillingAddress?.StateProvinceId) ? billingCountry?.StateProvinces.FirstOrDefault(x => x.Id == request.Order.BillingAddress.StateProvinceId)?.GetTranslation(x => x.Name, request.Order.CustomerLanguageId) : "";var shippingCountry = await _countryService.GetCountryById(request.Order.ShippingAddress?.CountryId);liquidOrder.ShippingCountry = request.Order.ShippingAddress != null && !string.IsNullOrEmpty(request.Order.ShippingAddress.CountryId) ? shippingCountry?.GetTranslation(x => x.Name, request.Order.CustomerLanguageId) : "";liquidOrder.ShippingStateProvince = request.Order.ShippingAddress != null && !string.IsNullOrEmpty(request.Order.ShippingAddress.StateProvinceId) ? shippingCountry?.StateProvinces.FirstOrDefault(x => x.Id == request.Order.ShippingAddress.StateProvinceId)?.GetTranslation(x => x.Name, request.Order.CustomerLanguageId) : "";- liquidOrder.ShippingCustomAttributes = await _addressAttributeParser.FormatAttributes(language, request.Order.ShippingAddress != null ? request.Order.ShippingAddress.Attributes : null);+ liquidOrder.ShippingCustomAttributes = await _addressAttributeParser.FormatAttributes(language, request.Order.ShippingAddress?.Attributes);var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(request.Order.PaymentMethodSystemName);liquidOrder.PaymentMethod = paymentMethod != null ? paymentMethod.FriendlyName : request.Order.PaymentMethodSystemName;@@ -138,7 +128,7 @@ namespace Grand.Business.System.Commands.Handlers.Messagesvar taxValue = _priceFormatter.FormatPrice(item.Amount, currency, language, false);if (string.IsNullOrEmpty(taxRate))- taxRate = item.Percent.ToString();+ taxRate = item.Percent.ToString(CultureInfo.InvariantCulture);if (!dict.ContainsKey(taxRate))dict.Add(taxRate, taxValue);@@ -151,8 +141,8 @@ namespace Grand.Business.System.Commands.Handlers.Messagesforeach (var gcuh in gcuhC){var giftVoucher = await _giftVoucherService.GetGiftVoucherById(gcuh.GiftVoucherId);- string giftVoucherText = string.Format(_translationService.GetResource("Messages.Order.GiftVoucherInfo", language.Id), WebUtility.HtmlEncode(giftVoucher.Code));- string giftVoucherAmount = _priceFormatter.FormatPrice(-gcuh.UsedValue, currency, language, true, false);+ var giftVoucherText = string.Format(_translationService.GetResource("Messages.Order.GiftVoucherInfo", language.Id), WebUtility.HtmlEncode(giftVoucher.Code));+ var giftVoucherAmount = _priceFormatter.FormatPrice(-gcuh.UsedValue, currency, language, true, false);cards.Add(giftVoucherText, giftVoucherAmount);}liquidOrder.GiftVouchers = cards;@@ -192,8 +182,6 @@ namespace Grand.Business.System.Commands.Handlers.Messages}else{- //exсluding tax-//subtotal_cusSubTotal = _priceFormatter.FormatPrice(request.Order.OrderSubtotalExclTax, currency, language, false);//discount (applied to order subtotal)@@ -226,16 +214,6 @@ namespace Grand.Business.System.Commands.Handlers.Messages//payment method additional fee_cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(request.Order.PaymentMethodAdditionalFeeExclTax, currency, language, false);}-- //shipping- bool displayShipping = request.Order.ShippingStatusId != ShippingStatus.ShippingNotRequired;-- //payment method fee- bool displayPaymentMethodFee = request.Order.PaymentMethodAdditionalFeeExclTax > 0;-- //tax- _displayTax = true;- _displayTaxRates = true;if (_taxSettings.HideTaxInOrderSummary && request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax){_displayTax = false;@@ -253,7 +231,7 @@ namespace Grand.Business.System.Commands.Handlers.Messages_displayTaxRates = _taxSettings.DisplayTaxRates && request.Order.OrderTaxes.Any();_displayTax = !_displayTaxRates;- string taxStr = _priceFormatter.FormatPrice(request.Order.OrderTax, currency, language, request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax, false);+ var taxStr = _priceFormatter.FormatPrice(request.Order.OrderTax, currency, language, request.Order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax, false);_cusTaxTotal = taxStr;}}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShipmentTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShipmentTokensCommandHandler.csindex 0e3768000..87bf222b3 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShipmentTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShipmentTokensCommandHandler.cs@@ -1,5 +1,5 @@using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;@@ -20,10 +20,10 @@ namespace Grand.Business.System.Commands.Handlers.Messagesvar liquidShipment = new LiquidShipment(request.Shipment, request.Order, request.Store, request.Host, request.Language);foreach (var shipmentItem in request.Shipment.ShipmentItems){- var orderitem = request.Order.OrderItems.FirstOrDefault(x => x.Id == shipmentItem.OrderItemId);+ var orderItem = request.Order.OrderItems.FirstOrDefault(x => x.Id == shipmentItem.OrderItemId);var product = await _productService.GetProductById(shipmentItem.ProductId);- var liquidshipmentItems = new LiquidShipmentItem(shipmentItem, request.Shipment, request.Order, orderitem, product, request.Language);- liquidShipment.ShipmentItems.Add(liquidshipmentItems);+ var liquidShipmentItems = new LiquidShipmentItem(shipmentItem, request.Shipment, request.Order, orderItem, product, request.Language);+ liquidShipment.ShipmentItems.Add(liquidShipmentItems);}return liquidShipment;}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.csindex 8e3a1fa86..07264a374 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs@@ -1,6 +1,5 @@using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Extensions;-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using Grand.Business.Core.Interfaces.Storage;using MediatR;@@ -23,33 +22,37 @@ namespace Grand.Business.System.Commands.Handlers.Messages_productAttributeFormatter = productAttributeFormatter;}- public async Task<LiquidShoppingCart> Handle(GetShoppingCartTokensCommand request, CancellationToken cancellationToken)+ public async Task<LiquidShoppingCart> Handle(GetShoppingCartTokensCommand request,+ CancellationToken cancellationToken){var liquidShoppingCart = new LiquidShoppingCart(request.Customer);await ProductList();async Task ProductList(){- string attributeDescription = string.Empty;- string pictureUrl = string.Empty;+ var attributeDescription = string.Empty;+ var pictureUrl = string.Empty;foreach (var item in request.Customer.ShoppingCartItems){var product = await _productService.GetProductById(item.ProductId);- //product name- string productName = product.GetTranslation(x => x.Name, request.Language.Id);if (product.ProductPictures.Any()){- pictureUrl = await _pictureService.GetPictureUrl(product.ProductPictures.OrderBy(x => x.DisplayOrder).FirstOrDefault().PictureId, 100, storeLocation: request.Store.SslEnabled ? request.Store.SecureUrl : request.Store.Url);+ pictureUrl = await _pictureService.GetPictureUrl(+ product.ProductPictures.MinBy(x => x.DisplayOrder)?.PictureId, 100,+ storeLocation: request.Store.SslEnabled ? request.Store.SecureUrl : request.Store.Url);}//attributesif (item.Attributes != null && item.Attributes.Any()){- attributeDescription = await _productAttributeFormatter.FormatAttributes(product, item.Attributes, request.Customer);+ attributeDescription =+ await _productAttributeFormatter.FormatAttributes(product, item.Attributes,+ request.Customer);}- var result = new LiquidShoppingCartItem(product, attributeDescription, pictureUrl, item, request.Language);+ var result = new LiquidShoppingCartItem(product, attributeDescription, pictureUrl, item,+ request.Language);liquidShoppingCart.Items.Add(result);@@ -59,4 +62,4 @@ namespace Grand.Business.System.Commands.Handlers.Messagesreturn liquidShoppingCart;}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetStoreTokensCommandHandler.csindex 8e7be05f8..13f7f2e8a 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs@@ -1,4 +1,4 @@-using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using Grand.Domain.Stores;using MediatR;diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetVendorTokensCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetVendorTokensCommandHandler.csindex 325bc9e71..67671e966 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetVendorTokensCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Messages/GetVendorTokensCommandHandler.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Tokens;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;using MediatR;diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallNewPermissionsCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallNewPermissionsCommandHandler.csindex 01a9a4200..92485618d 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallNewPermissionsCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallNewPermissionsCommandHandler.cs@@ -30,24 +30,22 @@ namespace Grand.Business.System.Commands.Handlers.Securityforeach (var permission in permissions){var permission1 = await _permissionService.GetPermissionBySystemName(permission.SystemName);- if (permission1 == null)+ if (permission1 != null) continue;+ //new permission (install it)+ permission1 = new Permission{- //new permission (install it)- permission1 = new Permission- {- Name = permission.Name,- SystemName = permission.SystemName,- Area = permission.Area,- Category = permission.Category,- Actions = permission.Actions- };+ Name = permission.Name,+ SystemName = permission.SystemName,+ Area = permission.Area,+ Category = permission.Category,+ Actions = permission.Actions+ };- //save new permission- await _permissionService.InsertPermission(permission1);+ //save new permission+ await _permissionService.InsertPermission(permission1);- //save localization- await permission1.SaveTranslationPermissionName(_translationService, _languageService);- }+ //save localization+ await permission1.SaveTranslationPermissionName(_translationService, _languageService);}return true;}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallPermissionsCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallPermissionsCommandHandler.csindex a9a937633..2acdea9d9 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallPermissionsCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Security/InstallPermissionsCommandHandler.cs@@ -35,50 +35,48 @@ namespace Grand.Business.System.Commands.Handlers.Securityforeach (var permission in permissions){var permission1 = await _permissionService.GetPermissionBySystemName(permission.SystemName);- if (permission1 == null)- {- //new permission (install it)- permission1 = new Permission {- Name = permission.Name,- SystemName = permission.SystemName,- Area = permission.Area,- Category = permission.Category,- Actions = permission.Actions- };+ if (permission1 != null) continue;+ //new permission (install it)+ permission1 = new Permission {+ Name = permission.Name,+ SystemName = permission.SystemName,+ Area = permission.Area,+ Category = permission.Category,+ Actions = permission.Actions+ };- //default customer group mappings- var defaultPermissions = request.PermissionProvider.GetDefaultPermissions();- foreach (var defaultPermission in defaultPermissions)+ //default customer group mappings+ var defaultPermissions = request.PermissionProvider.GetDefaultPermissions();+ foreach (var defaultPermission in defaultPermissions)+ {+ var customerGroup = await _groupService.GetCustomerGroupBySystemName(defaultPermission.CustomerGroupSystemName);+ if (customerGroup == null){- var customerGroup = await _groupService.GetCustomerGroupBySystemName(defaultPermission.CustomerGroupSystemName);- if (customerGroup == null)- {- //new role (save it)- customerGroup = new CustomerGroup {- Name = defaultPermission.CustomerGroupSystemName,- Active = true,- SystemName = defaultPermission.CustomerGroupSystemName- };- await _groupService.InsertCustomerGroup(customerGroup);- }+ //new role (save it)+ customerGroup = new CustomerGroup {+ Name = defaultPermission.CustomerGroupSystemName,+ Active = true,+ SystemName = defaultPermission.CustomerGroupSystemName+ };+ await _groupService.InsertCustomerGroup(customerGroup);+ }- var defaultMappingProvided = (from p in defaultPermission.Permissions- where p.SystemName == permission1.SystemName- select p).Any();- if (defaultMappingProvided)- {- permission1.CustomerGroups.Add(customerGroup.Id);- }+ var defaultMappingProvided = (from p in defaultPermission.Permissions+ where p.SystemName == permission1.SystemName+ select p).Any();+ if (defaultMappingProvided)+ {+ permission1.CustomerGroups.Add(customerGroup.Id);}+ }- //save new permission- await _permissionService.InsertPermission(permission1);+ //save new permission+ await _permissionService.InsertPermission(permission1);- //save localization- await permission1.SaveTranslationPermissionName(_translationService, _languageService);- }+ //save localization+ await permission1.SaveTranslationPermissionName(_translationService, _languageService);}return true;}diff --git a/src/Business/Grand.Business.System/Commands/Handlers/Security/UninstallPermissionsCommandHandler.cs b/src/Business/Grand.Business.System/Commands/Handlers/Security/UninstallPermissionsCommandHandler.csindex 914267f18..525b85e25 100644--- a/src/Business/Grand.Business.System/Commands/Handlers/Security/UninstallPermissionsCommandHandler.cs+++ b/src/Business/Grand.Business.System/Commands/Handlers/Security/UninstallPermissionsCommandHandler.cs@@ -28,13 +28,11 @@ namespace Grand.Business.System.Commands.Handlers.Securityforeach (var permission in permissions){var permission1 = await _permissionService.GetPermissionBySystemName(permission.SystemName);- if (permission1 != null)- {- await _permissionService.DeletePermission(permission1);+ if (permission1 == null) continue;+ await _permissionService.DeletePermission(permission1);- //delete permission locales- await permission1.DeleteTranslationPermissionName(_translationService, _languageService);- }+ //delete permission locales+ await permission1.DeleteTranslationPermissionName(_translationService, _languageService);}return true;}diff --git a/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs b/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.csindex 857a0b05e..3747d89b1 100644--- a/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs+++ b/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs@@ -21,17 +21,16 @@ namespace Grand.Business.System.Services.Adminpublic virtual async Task<IList<AdminSiteMap>> GetSiteMap(){- return await _cacheBase.GetAsync($"ADMIN_SITEMAP", async () =>+ return await _cacheBase.GetAsync("ADMIN_SITEMAP", async () =>{var query = from c in _adminSiteMapRepository.Table- orderby c.DisplayOrder ascending+ orderby c.DisplayOrderselect c;var list = query.ToList();if (list.Any())return list;- else- return await Task.FromResult(StandardAdminSiteMap.SiteMap.OrderBy(x=>x.DisplayOrder).ToList());+ return await Task.FromResult(StandardAdminSiteMap.SiteMap.OrderBy(x=>x.DisplayOrder).ToList());});}}diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/CancelOrderScheduledTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/CancelOrderScheduledTask.csindex 86c509941..360aac7fe 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/CancelOrderScheduledTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/CancelOrderScheduledTask.cs@@ -4,7 +4,7 @@ using Grand.Domain.Common;namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks{- public partial class CancelOrderScheduledTask : IScheduleTask+ public class CancelOrderScheduledTask : IScheduleTask{private readonly SystemSettings _systemSettings;private readonly IOrderService _orderService;diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearCacheScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearCacheScheduleTask.csindex d8b7fff09..85f928865 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearCacheScheduleTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearCacheScheduleTask.cs@@ -4,9 +4,9 @@ using Grand.Infrastructure.Caching;namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks{/// <summary>- /// Clear cache schedueled task implementation+ /// Clear cache scheduled task implementation/// </summary>- public partial class ClearCacheScheduleTask : IScheduleTask+ public class ClearCacheScheduleTask : IScheduleTask{private readonly ICacheBase _cacheBase;diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.csindex 29cc34121..a869cb738 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs@@ -6,7 +6,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task to clear Log table/// </summary>- public partial class ClearLogScheduleTask : IScheduleTask+ public class ClearLogScheduleTask : IScheduleTask{private readonly ILogger _logger;public ClearLogScheduleTask(ILogger logger)diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/DeleteGuestsScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/DeleteGuestsScheduleTask.csindex 026438059..ebe8fc3ad 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/DeleteGuestsScheduleTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/DeleteGuestsScheduleTask.cs@@ -7,7 +7,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task for deleting guest customers/// </summary>- public partial class DeleteGuestsScheduleTask : IScheduleTask+ public class DeleteGuestsScheduleTask : IScheduleTask{private readonly ICustomerService _customerService;private readonly SystemSettings _systemSettings;diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.csindex eccbe3b00..5bf257f5d 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs@@ -12,7 +12,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task end auctions/// </summary>- public partial class EndAuctionsTask : IScheduleTask+ public class EndAuctionsTask : IScheduleTask{private readonly IAuctionService _auctionService;private readonly IMessageProviderService _messageProviderService;@@ -41,7 +41,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasksvar auctionsToEnd = await _auctionService.GetAuctionsToEnd();foreach (var auctionToEnd in auctionsToEnd){- var bid = (await _auctionService.GetBidsByProductId(auctionToEnd.Id)).OrderByDescending(x => x.Amount).FirstOrDefault();+ var bid = (await _auctionService.GetBidsByProductId(auctionToEnd.Id)).MaxBy(x => x.Amount);if (bid == null){await _auctionService.UpdateAuctionEnded(auctionToEnd, true);diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/GenerateSitemapXmlTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/GenerateSitemapXmlTask.csindex 20f5007cf..451c4a3ac 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/GenerateSitemapXmlTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/GenerateSitemapXmlTask.cs@@ -10,7 +10,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task end auctions/// </summary>- public partial class GenerateSitemapXmlTask : IScheduleTask+ public class GenerateSitemapXmlTask : IScheduleTask{private readonly IMediator _mediator;private readonly ILanguageService _languageService;@@ -40,13 +40,13 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasksforeach (var store in stores){- var storelanguages = await _languageService.GetAllLanguages(storeId: store.Id);- foreach (var lang in storelanguages)+ var storeLanguages = await _languageService.GetAllLanguages(storeId: store.Id);+ foreach (var lang in storeLanguages){var siteMap = await _mediator.Send(new GetSitemapXmlCommand(){Language = lang,- Store = store,+ Store = store});if (!(stores.Count == 1 && languages.Count == 1))diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.csindex 9a2cdc43a..d688770b1 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs@@ -8,7 +8,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task for sending queued message/// </summary>- public partial class QueuedMessagesSendScheduleTask : IScheduleTask+ public class QueuedMessagesSendScheduleTask : IScheduleTask{private readonly IQueuedEmailService _queuedEmailService;private readonly IEmailSender _emailSender;@@ -30,14 +30,14 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// </summary>public async Task Execute(){- var maxTries = 3;+ const int maxTries = 3;var queuedEmails = await _queuedEmailService.SearchEmails(null, null, null, null, null, true, true, maxTries, false, -1, null, 0, 500);foreach (var queuedEmail in queuedEmails){- var bcc = String.IsNullOrWhiteSpace(queuedEmail.Bcc)+ var bcc = string.IsNullOrWhiteSpace(queuedEmail.Bcc)? null: queuedEmail.Bcc.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);- var cc = String.IsNullOrWhiteSpace(queuedEmail.CC)+ var cc = string.IsNullOrWhiteSpace(queuedEmail.CC)? null: queuedEmail.CC.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);@@ -63,7 +63,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks}catch (Exception exc){- _ = _logger.Error(string.Format("Error sending e-mail. {0}", exc.Message), exc);+ _ = _logger.Error($"Error sending e-mail. {exc.Message}", exc);}finally{diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.csindex d8073f277..32066a02e 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs@@ -51,7 +51,6 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Gets all tasks/// </summary>- /// <param name="showHidden">A value indicating whether to show hidden records</param>/// <returns>Tasks</returns>public virtual async Task<IList<ScheduleTask>> GetAllTasks(){diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/UpdateExchangeRateScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/UpdateExchangeRateScheduleTask.csindex b621dc547..61fcec802 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/UpdateExchangeRateScheduleTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/UpdateExchangeRateScheduleTask.cs@@ -8,7 +8,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks/// <summary>/// Represents a task for updating exchange rates/// </summary>- public partial class UpdateExchangeRateScheduleTask : ScheduleTask, IScheduleTask+ public class UpdateExchangeRateScheduleTask : ScheduleTask, IScheduleTask{private readonly ICurrencyService _currencyService;private readonly IExchangeRateService _exchangeRateService;@@ -34,15 +34,13 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasksvar primaryCurrencyCode = (await _currencyService.GetPrimaryExchangeRateCurrency()).CurrencyCode;var exchangeRates = await _exchangeRateService.GetCurrencyLiveRates(primaryCurrencyCode);- foreach (var exchageRate in exchangeRates)+ foreach (var exchangeRate in exchangeRates){- var currency = await _currencyService.GetCurrencyByCode(exchageRate.CurrencyCode);- if (currency != null)- {- currency.Rate = exchageRate.Rate;- currency.UpdatedOnUtc = DateTime.UtcNow;- await _currencyService.UpdateCurrency(currency);- }+ var currency = await _currencyService.GetCurrencyByCode(exchangeRate.CurrencyCode);+ if (currency == null) continue;+ currency.Rate = exchangeRate.Rate;+ currency.UpdatedOnUtc = DateTime.UtcNow;+ await _currencyService.UpdateCurrency(currency);}}}diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataActivityLogTypes.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataActivityLogTypes.csindex 0d77d4d1b..149a7bdad 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataActivityLogTypes.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataActivityLogTypes.cs@@ -3,7 +3,7 @@ using Grand.Domain.Logging;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallActivityLogTypes(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataAffiliates.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataAffiliates.csindex c97d332b4..4139ac6aa 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataAffiliates.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataAffiliates.cs@@ -4,7 +4,7 @@ using Grand.Domain.Common;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallAffiliates(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataBlogPosts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataBlogPosts.csindex abd5e9b7e..00876dcaf 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataBlogPosts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataBlogPosts.cs@@ -5,7 +5,7 @@ using Grand.Domain.Seo;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallBlogPosts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataBrandLayouts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataBrandLayouts.csindex 9ff3c6735..82f2ed4f1 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataBrandLayouts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataBrandLayouts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallBrandLayouts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataBrands.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataBrands.csindex 9a79f2a43..c03f65fb8 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataBrands.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataBrands.cs@@ -7,13 +7,11 @@ using Microsoft.Extensions.DependencyInjection;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallBrands(){var pictureService = _serviceProvider.GetRequiredService<IPictureService>();- var downloadService = _serviceProvider.GetRequiredService<IDownloadService>();-var sampleImagesPath = GetSamplesPath();var brandLayoutInGridAndLines =diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCategories.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCategories.csindex 7c352d25a..9e78c446e 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCategories.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCategories.cs@@ -7,7 +7,7 @@ using Microsoft.Extensions.DependencyInjection;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCategories(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCategoryLayouts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCategoryLayouts.csindex 3759a0b3e..b649fcf43 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCategoryLayouts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCategoryLayouts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCategoryLayouts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCheckoutAttributes.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCheckoutAttributes.csindex 7155a233a..406f0b55a 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCheckoutAttributes.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCheckoutAttributes.cs@@ -4,7 +4,7 @@ using Grand.Domain.Orders;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCheckoutAttributes(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCollectionLayouts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCollectionLayouts.csindex 48ca23133..62b58ead2 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCollectionLayouts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCollectionLayouts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCollectionLayouts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCountriesAndStates.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCountriesAndStates.csindex 8cb466bae..794228e51 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCountriesAndStates.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCountriesAndStates.cs@@ -3,7 +3,7 @@ using Grand.Domain.Directory;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCountriesAndStates(){@@ -574,97 +574,97 @@ namespace Grand.Business.System.Services.InstallationDisplayOrder = 100,Published = true,};- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 0,Name = "dolnośląskie",Published = true,Abbreviation = "DŚ"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 1,Name = "kujawsko-pomorskie",Published = true,Abbreviation = "KP"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 2,Name = "lubelskie",Published = true,Abbreviation = "LB"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 3,Name = "lubuskie",Published = true,Abbreviation = "LS"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 4,Name = "łódzkie",Published = true,Abbreviation = "ŁD"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 5,Name = "małopolskie",Published = true,Abbreviation = "MP"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 6,Name = "mazowieckie",Published = true,Abbreviation = "MZ"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 7,Name = "opolskie",Published = true,Abbreviation = "OP"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 8,Name = "podkarpackie",Published = true,Abbreviation = "PK"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 9,Name = "podlaskie",Published = true,Abbreviation = "PL"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 10,Name = "pomorskie",Published = true,Abbreviation = "PM"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 11,Name = "śląskie",Published = true,Abbreviation = "ŚL"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 12,Name = "świętokrzyskie",Published = true,Abbreviation = "ŚK"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 13,Name = "warmińsko-mazurskie",Published = true,Abbreviation = "WM"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 14,Name = "wielkopolskie",Published = true,Abbreviation = "WP"});- cPoland.StateProvinces.Add(new StateProvince() {+ cPoland.StateProvinces.Add(new () {DisplayOrder = 15,Name = "zachodniopomorskie",Published = true,diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCurrencies.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCurrencies.csindex 429704475..1418da31e 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCurrencies.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCurrencies.cs@@ -3,7 +3,7 @@ using Grand.Domain.Directory;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCurrencies(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataCustomersAndUsers.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataCustomersAndUsers.csindex c646c74e1..28f0c706e 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataCustomersAndUsers.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataCustomersAndUsers.cs@@ -4,7 +4,7 @@ using Grand.Domain.Customers;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallCustomersAndUsers(string defaultUserEmail, string defaultUserPassword){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataDeliveryDates.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataDeliveryDates.csindex 24567249f..b552e4504 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataDeliveryDates.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataDeliveryDates.cs@@ -3,7 +3,7 @@ using Grand.Domain.Shipping;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallDeliveryDates(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataDiscounts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataDiscounts.csindex b86707c9e..b3e6a0ef8 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataDiscounts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataDiscounts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Discounts;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallDiscounts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataEmailAccounts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataEmailAccounts.csindex e9544640f..f444871d1 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataEmailAccounts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataEmailAccounts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Messages;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallEmailAccounts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataLanguages.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataLanguages.csindex 08b4a3e88..77beea0d9 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataLanguages.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataLanguages.cs@@ -3,7 +3,7 @@ using Grand.Domain.Localization;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallLanguages(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataLocaleResources.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataLocaleResources.csindex 589e47e87..4b18e3d56 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataLocaleResources.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataLocaleResources.cs@@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallLocaleResources(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataMeasures.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataMeasures.csindex 1562ed488..d3e5469b2 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataMeasures.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataMeasures.cs@@ -3,7 +3,7 @@ using Grand.Domain.Directory;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallMeasures(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnActions.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnActions.csindex a8c39f2cd..a5867ee45 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnActions.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnActions.cs@@ -3,7 +3,7 @@ using Grand.Domain.Orders;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallMerchandiseReturnActions(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnReasons.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnReasons.csindex f193f5fc0..42c536611 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnReasons.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataMerchandiseReturnReasons.cs@@ -3,7 +3,7 @@ using Grand.Domain.Orders;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallMerchandiseReturnReasons(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataMessageTemplates.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataMessageTemplates.csindex 19be10ce3..1399175a9 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataMessageTemplates.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataMessageTemplates.cs@@ -3,7 +3,7 @@ using Grand.Domain.Messages;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallMessageTemplates(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataNews.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataNews.csindex a1dd31934..5788ef69b 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataNews.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataNews.cs@@ -5,7 +5,7 @@ using Grand.Domain.Seo;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallNews(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderStatus.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderStatus.csindex fb2c04b7b..107cad069 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderStatus.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderStatus.cs@@ -3,7 +3,7 @@ using Grand.Domain.Orders;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallOrderStatus(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderTags.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderTags.csindex 614a5c920..d15374048 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderTags.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataOrderTags.cs@@ -3,7 +3,7 @@ using Grand.Domain.Orders;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallOrderTags(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataPageLayouts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataPageLayouts.csindex e31bc2c02..30c4ad2ed 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataPageLayouts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataPageLayouts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Pages;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallPageLayouts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataPages.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataPages.csindex fa80cb305..36c459169 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataPages.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataPages.cs@@ -4,7 +4,7 @@ using Grand.Domain.Seo;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallPages(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataPickupPoints.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataPickupPoints.csindex b28b0b147..ed7083465 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataPickupPoints.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataPickupPoints.cs@@ -4,7 +4,7 @@ using Grand.Domain.Shipping;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallPickupPoints(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataProductAttributes.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataProductAttributes.csindex 1d5c4931f..211f37f71 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataProductAttributes.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataProductAttributes.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallProductAttributes(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataProductLayouts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataProductLayouts.csindex 541c64c37..bc19f03e2 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataProductLayouts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataProductLayouts.cs@@ -3,7 +3,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallProductLayouts(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataProducts.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataProducts.csindex b3955a840..cf32710fe 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataProducts.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataProducts.cs@@ -8,7 +8,7 @@ using Microsoft.Extensions.DependencyInjection;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallProducts(string defaultUserEmail){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataRobotsTxt.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataRobotsTxt.csindex 17a6cd505..a2065ceb9 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataRobotsTxt.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataRobotsTxt.cs@@ -4,7 +4,7 @@ using Grand.Domain.Stores;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallDataRobotsTxt(Store store)diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataScheduleTasks.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataScheduleTasks.csindex 0b95ff41d..fa67a37f6 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataScheduleTasks.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataScheduleTasks.cs@@ -3,7 +3,7 @@ using Grand.Domain.Tasks;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallScheduleTasks(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.csindex 54cdebda4..89fd595e1 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs@@ -26,7 +26,7 @@ using Microsoft.Extensions.DependencyInjection;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallSettings(bool installSampleData){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataShippingMethods.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataShippingMethods.csindex 1b6fc6e6c..3e6e9eaa7 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataShippingMethods.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataShippingMethods.cs@@ -3,7 +3,7 @@ using Grand.Domain.Shipping;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallShippingMethods(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataSpecificationAttributes.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataSpecificationAttributes.csindex 476fe29e3..0d26656c6 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataSpecificationAttributes.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataSpecificationAttributes.cs@@ -4,7 +4,7 @@ using Grand.Domain.Catalog;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallSpecificationAttributes(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataStores.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataStores.csindex a4ddc6528..4cf78fba1 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataStores.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataStores.cs@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Http;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallStores(string httpscheme, HostString host,diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataTaxCategories.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataTaxCategories.csindex 55f6a03dd..2da8a4847 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataTaxCategories.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataTaxCategories.cs@@ -3,7 +3,7 @@ using Grand.Domain.Tax;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallTaxCategories(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataVendors.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataVendors.csindex 9c63c8467..5dd5190a7 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataVendors.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataVendors.cs@@ -5,7 +5,7 @@ using Grand.Domain.Vendors;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallVendors(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataWarehouses.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataWarehouses.csindex 868096854..2400f60ac 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataWarehouses.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataWarehouses.cs@@ -4,7 +4,7 @@ using Grand.Domain.Shipping;namespace Grand.Business.System.Services.Installation{- public partial class InstallationService : IInstallationService+ public partial class InstallationService{protected virtual async Task InstallWarehouses(){diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallationLocalizedService.cs b/src/Business/Grand.Business.System/Services/Installation/InstallationLocalizedService.csindex 914bea97d..d2b68f90b 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallationLocalizedService.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallationLocalizedService.cs@@ -9,7 +9,7 @@ namespace Grand.Business.System.Services.Installation/// <summary>/// Translation service for installation process/// </summary>- public partial class InstallationLocalizedService : IInstallationLocalizedService+ public class InstallationLocalizedService : IInstallationLocalizedService{/// <summary>/// Available languages@@ -20,12 +20,7 @@ namespace Grand.Business.System.Services.Installation/// Available collation/// </summary>private IList<InstallationCollation> _availableCollation;--- public InstallationLocalizedService()- {-- }+/// <summary>/// Get locale resource value/// </summary>@@ -42,11 +37,9 @@ namespace Grand.Business.System.Services.Installation.Select(r => r.Value).FirstOrDefault();- if (string.IsNullOrEmpty(resourceValue))+ return string.IsNullOrEmpty(resourceValue) ?//return name- return resourceName;-- return resourceValue;+ resourceName : resourceValue;}/// <summary>diff --git a/src/Business/Grand.Business.System/Services/Reports/CustomerReportService.cs b/src/Business/Grand.Business.System/Services/Reports/CustomerReportService.csindex a657d3638..80aaed815 100644--- a/src/Business/Grand.Business.System/Services/Reports/CustomerReportService.cs+++ b/src/Business/Grand.Business.System/Services/Reports/CustomerReportService.cs@@ -1,5 +1,4 @@using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.System.Reports;using Grand.Business.Core.Utilities.System;using Grand.Domain;@@ -14,13 +13,12 @@ namespace Grand.Business.System.Services.Reports/// <summary>/// Customer report service/// </summary>- public partial class CustomerReportService : ICustomerReportService+ public class CustomerReportService : ICustomerReportService{#region Fieldsprivate readonly IRepository<Customer> _customerRepository;private readonly IRepository<Order> _orderRepository;- private readonly ICustomerService _customerService;private readonly IGroupService _groupService;private readonly IDateTimeService _dateTimeService;@@ -33,18 +31,15 @@ namespace Grand.Business.System.Services.Reports/// </summary>/// <param name="customerRepository">Customer repository</param>/// <param name="orderRepository">Order repository</param>- /// <param name="customerService">Customer service</param>/// <param name="dateTimeService">Date time helper</param>/// <param name="groupService">group service</param>public CustomerReportService(IRepository<Customer> customerRepository,IRepository<Order> orderRepository,- ICustomerService customerService,IGroupService groupService,IDateTimeService dateTimeService){_customerRepository = customerRepository;_orderRepository = orderRepository;- _customerService = customerService;_groupService = groupService;_dateTimeService = dateTimeService;}@@ -142,7 +137,7 @@ namespace Grand.Business.System.Services.Reportsc.CreatedOnUtc >= date//&& c.CreatedOnUtc <= DateTime.UtcNowselect c;- int count = query.Count();+ var count = query.Count();return count;}@@ -150,6 +145,7 @@ namespace Grand.Business.System.Services.Reports/// <summary>/// Get "customer by time" report/// </summary>+ /// <param name="storeId">Store ident</param>/// <param name="startTimeUtc">Start date</param>/// <param name="endTimeUtc">End date</param>/// <returns>Result</returns>@@ -158,10 +154,8 @@ namespace Grand.Business.System.Services.Reports{List<CustomerByTimeReportLine> report = new List<CustomerByTimeReportLine>();- if (!startTimeUtc.HasValue)- startTimeUtc = DateTime.MinValue;- if (!endTimeUtc.HasValue)- endTimeUtc = DateTime.UtcNow;+ startTimeUtc ??= DateTime.MinValue;+ endTimeUtc ??= DateTime.UtcNow;var endTime = new DateTime(endTimeUtc.Value.Year, endTimeUtc.Value.Month, endTimeUtc.Value.Day, 23, 59, 00);var builderquery = from p in _customerRepository.Table@@ -188,7 +182,7 @@ namespace Grand.Business.System.Services.Reportsforeach (var item in query){report.Add(new CustomerByTimeReportLine() {- Time = item.Year.ToString() + "-" + item.Month.ToString().PadLeft(2, '0'),+ Time = item.Year + "-" + item.Month.ToString().PadLeft(2, '0'),Registered = item.Count,});}@@ -206,7 +200,7 @@ namespace Grand.Business.System.Services.Reportsforeach (var item in query){report.Add(new CustomerByTimeReportLine() {- Time = item.Year.ToString() + "-" + item.Month.ToString().PadLeft(2, '0') + "-" + item.Day.ToString().PadLeft(2, '0'),+ Time = item.Year + "-" + item.Month.ToString().PadLeft(2, '0') + "-" + item.Day.ToString().PadLeft(2, '0'),Registered = item.Count,});}diff --git a/src/Business/Grand.Business.System/Services/Reports/OrderReportService.cs b/src/Business/Grand.Business.System/Services/Reports/OrderReportService.csindex 06674d9c1..e1a70c143 100644--- a/src/Business/Grand.Business.System/Services/Reports/OrderReportService.cs+++ b/src/Business/Grand.Business.System/Services/Reports/OrderReportService.cs@@ -14,7 +14,7 @@ namespace Grand.Business.System.Services.Reports/// <summary>/// Order report service/// </summary>- public partial class OrderReportService : IOrderReportService+ public class OrderReportService : IOrderReportService{#region Fields@@ -66,7 +66,7 @@ namespace Grand.Business.System.Services.Reportsselect p;query = query.Where(o => !o.Deleted);- if (!String.IsNullOrEmpty(storeId))+ if (!string.IsNullOrEmpty(storeId))query = query.Where(o => o.StoreId == storeId);if (os.HasValue)query = query.Where(o => o.OrderStatusId == os.Value);@@ -110,10 +110,8 @@ namespace Grand.Business.System.Services.ReportsDateTime? endTimeUtc = null){List<OrderByTimeReportLine> report = new List<OrderByTimeReportLine>();- if (!startTimeUtc.HasValue)- startTimeUtc = DateTime.MinValue;- if (!endTimeUtc.HasValue)- endTimeUtc = DateTime.UtcNow;+ startTimeUtc ??= DateTime.MinValue;+ endTimeUtc ??= DateTime.UtcNow;var endTime = new DateTime(endTimeUtc.Value.Year, endTimeUtc.Value.Month, endTimeUtc.Value.Day, 23, 59, 00);@@ -187,8 +185,9 @@ namespace Grand.Business.System.Services.Reports/// <param name="startTimeUtc">Start date</param>/// <param name="endTimeUtc">End date</param>/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>+ /// <param name="billingLastName"></param>/// <param name="ignoreCancelledOrders">A value indicating whether to ignore cancelled orders</param>- /// <param name="tagid">Tag ident.</param>+ /// <param name="tagId">Tag ident.</param>/// <returns>Result</returns>public virtual async Task<OrderAverageReportLine> GetOrderAverageReportLine(string storeId = "", string customerId = "",string vendorId = "", string salesEmployeeId = "", string billingCountryId = "",@@ -196,7 +195,7 @@ namespace Grand.Business.System.Services.Reportsint? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,DateTime? startTimeUtc = null, DateTime? endTimeUtc = null,string billingEmail = null, string billingLastName = "", bool ignoreCancelledOrders = false,- string tagid = null)+ string tagId = null){var builderquery = from p in _orderRepository.Tableselect p;@@ -225,9 +224,7 @@ namespace Grand.Business.System.Services.Reportsif (ignoreCancelledOrders){- var cancelledOrderStatusId = OrderStatusSystem.Cancelled;- builderquery = builderquery.Where(o => o.OrderStatusId != (int)cancelledOrderStatusId);-+ builderquery = builderquery.Where(o => o.OrderStatusId != (int)OrderStatusSystem.Cancelled);}if (!string.IsNullOrEmpty(paymentMethodSystemName))builderquery = builderquery.Where(o => o.PaymentMethodSystemName == paymentMethodSystemName);@@ -248,14 +245,14 @@ namespace Grand.Business.System.Services.Reportsbuilderquery = builderquery.Where(o => endTimeUtc.Value >= o.CreatedOnUtc);if (!string.IsNullOrEmpty(billingEmail))- builderquery = builderquery.Where(o => o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail));+ builderquery = builderquery.Where(o => o.BillingAddress != null && !string.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail));if (!string.IsNullOrEmpty(billingLastName))- builderquery = builderquery.Where(o => o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.LastName) && o.BillingAddress.LastName.Contains(billingLastName));+ builderquery = builderquery.Where(o => o.BillingAddress != null && !string.IsNullOrEmpty(o.BillingAddress.LastName) && o.BillingAddress.LastName.Contains(billingLastName));//tag filtering- if (!string.IsNullOrEmpty(tagid))- builderquery = builderquery.Where(o => o.OrderTags.Any(y => y == tagid));+ if (!string.IsNullOrEmpty(tagId))+ builderquery = builderquery.Where(o => o.OrderTags.Any(y => y == tagId));var query = builderquery.GroupBy(x => 1).Select(g => new OrderAverageReportLine {@@ -348,8 +345,6 @@ namespace Grand.Business.System.Services.Reports/// </summary>/// <param name="storeId">Store identifier</param>/// <param name="vendorId">Vendor identifier</param>- /// <param name="categoryId">Category identifier</param>- /// <param name="collectionId">Collection identifier</param>/// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>/// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>/// <param name="os">Order status; null to load all records</param>@@ -475,11 +470,8 @@ namespace Grand.Business.System.Services.Reportsproduct = product.Take(recordsToReturn);var report = product.ToList();- var ids = new List<string>();- foreach (var reportLine in report)- ids.Add(reportLine.ProductId);- return await Task.FromResult(ids.ToArray());+ return await Task.FromResult(report.Select(reportLine => reportLine.ProductId).ToArray());}/// <summary>@@ -498,21 +490,21 @@ namespace Grand.Business.System.Services.Reportsint pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false){- createdFromUtc = !createdFromUtc.HasValue ? DateTime.MinValue : createdFromUtc;- createdToUtc = !createdToUtc.HasValue ? DateTime.MaxValue : createdToUtc;+ createdFromUtc ??= DateTime.MinValue;+ createdToUtc ??= DateTime.MaxValue;- var query = ((from order in _orderRepository.Table- where- (string.IsNullOrEmpty(storeId) || order.StoreId == storeId) &&- (createdFromUtc.Value <= order.CreatedOnUtc) &&- (createdToUtc.Value >= order.CreatedOnUtc) &&- (!order.Deleted)- from orderItem in order.OrderItems- select new { orderItem.ProductId }).ToList()).Distinct().Select(x => x.ProductId);+ var query = (from order in _orderRepository.Table+ where+ (string.IsNullOrEmpty(storeId) || order.StoreId == storeId) &&+ createdFromUtc.Value <= order.CreatedOnUtc &&+ createdToUtc.Value >= order.CreatedOnUtc &&+ (!order.Deleted)+ from orderItem in order.OrderItems+ select new { orderItem.ProductId }).ToList().Distinct().Select(x => x.ProductId);var qproducts = from p in _productRepository.Tableorderby p.Name- where (!query.Contains(p.Id)) &&+ where !query.Contains(p.Id) &&//include only simple products(p.ProductTypeId == ProductType.SimpleProduct) &&(vendorId == "" || p.VendorId == vendorId) &&@@ -523,11 +515,6 @@ namespace Grand.Business.System.Services.Reportsreturn await PagedList<Product>.Create(qproducts, pageIndex, pageSize);}- public class UnwindedOrderItem- {- public OrderItem OrderItems { get; set; }- }-public class OrderStats{public int Year { get; set; }diff --git a/src/Business/Grand.Business.System/Services/Reports/ProductsReportService.cs b/src/Business/Grand.Business.System/Services/Reports/ProductsReportService.csindex 1eeacd3be..8453f205d 100644--- a/src/Business/Grand.Business.System/Services/Reports/ProductsReportService.cs+++ b/src/Business/Grand.Business.System/Services/Reports/ProductsReportService.cs@@ -35,19 +35,19 @@ namespace Grand.Business.System.Services.Reports{//Track inventory for product//simple products- var query_simple_products = from p in _productRepository.Table+ var querySimpleProducts = from p in _productRepository.Tablewhere p.LowStock &&- ((p.ProductTypeId == ProductType.SimpleProduct || p.ProductTypeId == ProductType.BundledProduct)- && p.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)+ (p.ProductTypeId == ProductType.SimpleProduct || p.ProductTypeId == ProductType.BundledProduct)+ && p.ManageInventoryMethodId == ManageInventoryMethod.ManageStockselect p;if (!string.IsNullOrEmpty(vendorId))- query_simple_products = query_simple_products.Where(x => x.VendorId == vendorId);+ querySimpleProducts = querySimpleProducts.Where(x => x.VendorId == vendorId);if (!string.IsNullOrEmpty(storeId))- query_simple_products = query_simple_products.Where(x => x.Stores.Contains(storeId));+ querySimpleProducts = querySimpleProducts.Where(x => x.Stores.Contains(storeId));- var products = query_simple_products.ToList();+ var products = querySimpleProducts.ToList();//Track inventory for product by product attributesvar query2_1 = from p in _productRepository.Tablediff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.csindex 1d76a6443..5a97069cf 100644--- a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs+++ b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs@@ -22,7 +22,7 @@ namespace Grand.Domain.Catalog/// </summary>public string SeName { get; set; }- // <summary>+ /// <summary>/// Gets or sets the color RGB value (used when you want to display "Color squares" instead of text)/// </summary>public string ColorSquaresRgb { get; set; }diff --git a/src/Core/Grand.Domain/Data/IRepository.cs b/src/Core/Grand.Domain/Data/IRepository.csindex b5da6c10e..6d634caf1 100644--- a/src/Core/Grand.Domain/Data/IRepository.cs+++ b/src/Core/Grand.Domain/Data/IRepository.cs@@ -147,12 +147,11 @@ namespace Grand.Domain.Data/// <param name="id">Ident of entitie</param>/// <param name="field"></param>/// <param name="elemFieldMatch">Subdocument field to match</param>- /// <param name="elemMatch">Subdocument ident value</param>/// <param name="value">Subdocument - to update (all values)</param>/// <returns></returns>Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value);- // <summary>+ /// <summary>/// Update subdocuments/// </summary>/// <typeparam name="T">Document</typeparam>diff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.csindex 56d06272e..a6916ec8a 100644--- a/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs@@ -296,7 +296,7 @@ namespace Grand.Domain.Data.LiteDbreturn Task.CompletedTask;}- // <summary>+ /// <summary>/// Add to set - add subdocument/// </summary>/// <typeparam name="U"></typeparam>@@ -399,7 +399,7 @@ namespace Grand.Domain.Data.LiteDbreturn Task.CompletedTask;}- // <summary>+ /// <summary>/// Update subdocuments/// </summary>/// <typeparam name="T">Document</typeparam>diff --git a/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs b/src/Core/Grand.Domain/Data/Mongo/MongoRepository.csindex ffb2077f7..793621f9d 100644--- a/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs+++ b/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs@@ -250,7 +250,7 @@ namespace Grand.Domain.Data.Mongoawait _collection.UpdateManyAsync(filterexpression, update);}- // <summary>+ /// <summary>/// Add to set - add subdocument/// </summary>/// <typeparam name="U"></typeparam>@@ -318,7 +318,7 @@ namespace Grand.Domain.Data.Mongo}}- // <summary>+ /// <summary>/// Update subdocuments/// </summary>/// <typeparam name="T">Document</typeparam>diff --git a/src/Core/Grand.Domain/Payments/PaymentRestictedSettings.cs b/src/Core/Grand.Domain/Payments/PaymentRestrictedSettings.cssimilarity index 66%rename from src/Core/Grand.Domain/Payments/PaymentRestictedSettings.csrename to src/Core/Grand.Domain/Payments/PaymentRestrictedSettings.csindex aad34da45..a49e4a43e 100644--- a/src/Core/Grand.Domain/Payments/PaymentRestictedSettings.cs+++ b/src/Core/Grand.Domain/Payments/PaymentRestrictedSettings.cs@@ -2,9 +2,9 @@namespace Grand.Domain.Payments{- public class PaymentRestictedSettings : ISettings+ public class PaymentRestrictedSettings : ISettings{- public PaymentRestictedSettings()+ public PaymentRestrictedSettings(){Ids = new List<string>();}diff --git a/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.csindex 740a30f2a..19ca90847 100644--- a/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs+++ b/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs@@ -70,7 +70,7 @@ namespace Grand.Infrastructure.TypeSearchersreturn result;}- // <summary>+ /// <summary>/// Does type implement generic?/// </summary>/// <param name="type"></param>diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.csindex 5287d3ae1..345b4d7d6 100644--- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs+++ b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs@@ -85,7 +85,7 @@ namespace Payments.PayPalStandard.ControllersOrder order = await _orderService.GetOrderByGuid(orderNumberGuid);if (order != null){- var paymentTransaction = await _paymentTransactionService.GetByOrdeGuid(orderNumberGuid);+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(orderNumberGuid);double mc_gross = 0;try@@ -265,7 +265,7 @@ namespace Payments.PayPalStandard.ControllersCreatedOnUtc = DateTime.UtcNow,OrderId = order.Id,});- var paymentTransaction = await _paymentTransactionService.GetByOrdeGuid(order.OrderGuid);+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);switch (newPaymentStatus){diff --git a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.csindex 843c041da..480fd7a1d 100644--- a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs+++ b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs@@ -15,7 +15,7 @@ namespace Payments.PayPalStandard.Services_logger = logger;}- // <summary>+ /// <summary>/// Gets IPN PayPal URL/// </summary>/// <returns></returns>diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.csindex f03e79ba4..65cea978b 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs@@ -197,14 +197,14 @@ namespace Grand.Business.Catalog.Services.Products.Tests}[TestMethod()]- public async Task UnpublishProductTest()+ public async Task UnPublishProductTest(){//Arrangevar product = new Product() { Id = "100", Published = true };await _productService.InsertProduct(product);//Act- await _productService.UnpublishProduct(product);+ await _productService.UnPublishProduct(product);var result = await _productService.GetProductById("100");//Assert@@ -235,7 +235,7 @@ namespace Grand.Business.Catalog.Services.Products.Tests//Arrangeawait insertSampleProducts();//Act- var result = await _productService.GetProductsByProductAtributeId("1");+ var result = await _productService.GetProductsByProductAttributeId("1");//AssertAssert.IsTrue(result.Count > 0);diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.csindex 85815cb60..60f33c3d2 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs@@ -165,8 +165,8 @@ namespace Grand.Business.Catalog.Tests.Service.TaxAssert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");- Assert.AreEqual(discountAmountInclTax, result02.discountAmountInclTax, "discount including tax");- Assert.AreEqual(discountAmountExclTax, result02.discountAmountExclTax, "discount excluding tax");+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");}[TestMethod()]@@ -198,8 +198,8 @@ namespace Grand.Business.Catalog.Tests.Service.TaxAssert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");- Assert.AreEqual(discountAmountInclTax, result02.discountAmountInclTax, "discount including tax");- Assert.AreEqual(discountAmountExclTax, result02.discountAmountExclTax, "discount excluding tax");+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");}[TestMethod()]@@ -231,8 +231,8 @@ namespace Grand.Business.Catalog.Tests.Service.TaxAssert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");- Assert.AreEqual(discountAmountInclTax, result02.discountAmountInclTax, "discount including tax");- Assert.AreEqual(discountAmountExclTax, result02.discountAmountExclTax, "discount excluding tax");+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");}[TestMethod()]@@ -264,8 +264,8 @@ namespace Grand.Business.Catalog.Tests.Service.TaxAssert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");- Assert.AreEqual(discountAmountInclTax, result02.discountAmountInclTax, "discount including tax");- Assert.AreEqual(discountAmountExclTax, result02.discountAmountExclTax, "discount excluding tax");+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");}}diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.csindex 41c4578fc..08ad4eea8 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs@@ -1,5 +1,6 @@using Microsoft.VisualStudio.TestTools.UnitTesting;using Grand.Business.Checkout.Events.Shipping;+using Grand.Business.Checkout.Events.ShoppingCart;using System;using System.Collections.Generic;using System.Linq;diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.csindex 1d226e149..35173e67d 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs@@ -44,12 +44,12 @@ namespace Grand.Business.Checkout.Tests.Services.Payments_paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");var expectedResult = new List<string>() { "1", "2", "3", "4" };var expectedKey = "PaymentMethodRestictions.systemName";- _settingService.Setup(s => s.GetSettingByKey<PaymentRestictedSettings>(It.IsAny<string>(), null, ""))- .Returns(() => new PaymentRestictedSettings() { Ids = expectedResult });+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))+ .Returns(() => new PaymentRestrictedSettings() { Ids = expectedResult });var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);Assert.IsTrue(expectedResult.SequenceEqual(result));- _settingService.Verify(s => s.GetSettingByKey<PaymentRestictedSettings>(expectedKey, null, ""), Times.Once);+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);}[TestMethod()]@@ -57,12 +57,12 @@ namespace Grand.Business.Checkout.Tests.Services.Payments{_paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");var expectedKey = "PaymentMethodRestictions.systemName";- _settingService.Setup(s => s.GetSettingByKey<PaymentRestictedSettings>(It.IsAny<string>(), null, ""))+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, "")).Returns(() => null);var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);Assert.IsTrue(result.Count == 0);- _settingService.Verify(s => s.GetSettingByKey<PaymentRestictedSettings>(expectedKey, null, ""), Times.Once);+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);}[TestMethod()]@@ -72,8 +72,8 @@ namespace Grand.Business.Checkout.Tests.Services.Paymentsvar countryIds = new List<string>() { "1", "2", "3", "4" };var expectedKey = "PaymentMethodRestictions.systemName";- await _paymentService.SaveRestictedCountryIds(_paymentProviderMock.Object, countryIds);- _settingService.Verify(s => s.SetSetting(expectedKey, It.IsAny<PaymentRestictedSettings>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);+ await _paymentService.SaveRestrictedCountryIds(_paymentProviderMock.Object, countryIds);+ _settingService.Verify(s => s.SetSetting(expectedKey, It.IsAny<PaymentRestrictedSettings>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);}[TestMethod()]diff --git a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.csindex 6ccd872e4..a07d8d495 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs@@ -205,7 +205,7 @@ namespace Grand.Business.Checkout.Tests.Validatorspublic async Task ShoppingCartItemAttributeValidator_Success(){//Arrange- var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object, _aclServiceMock.Object,+ var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,_productServiceMock.Object, _productAttributeService.Object);_productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))@@ -236,7 +236,7 @@ namespace Grand.Business.Checkout.Tests.Validatorspublic async Task ShoppingCartItemAttributeValidator_Fail(){//Arrange- var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object, _aclServiceMock.Object,+ var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,_productServiceMock.Object, _productAttributeService.Object);_productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.csindex 87ff633c1..0337a183a 100644--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs@@ -238,7 +238,7 @@ namespace Grand.Business.Customers.Services.Testsawait _repository.InsertAsync(customer);//Actcustomer.AdminComment = "test";- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);//AssertAssert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).AdminComment);diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.csindex 3318869ef..99808ce21 100644--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs@@ -1,4 +1,5 @@-using Grand.Business.Marketing.Services.Newsteletters;+using Grand.Business.Marketing.Services.Newsletters;+using Grand.Business.Marketing.Services.Newsteletters;using Grand.Domain.Data;using Grand.Domain.Messages;using Grand.Infrastructure.Events;diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.csindex 9b8b3a142..7c73cb871 100644--- a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs+++ b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs@@ -1,5 +1,7 @@using Grand.Business.Messages.Commands.Handlers;using Grand.Business.Core.Commands.Messages;+using Grand.Business.Core.Commands.Messages.Common;+using Grand.Business.Messages.Commands.Handlers.Common;using Grand.Domain.Common;using Grand.Domain.Data;using Grand.Domain.Messages;diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentController.csindex e1f1b75d5..252375f9c 100644--- a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs@@ -207,7 +207,7 @@ namespace Grand.Web.Admin.ControllersnewCountryIds.Add(c.Id);}}- await _paymentService.SaveRestictedCountryIds(pm, newCountryIds);+ await _paymentService.SaveRestrictedCountryIds(pm, newCountryIds);formKey = "restrictship_" + pm.SystemName;var shipIdsToRestrict = (form[formKey].ToString() != null ? form[formKey].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string>())@@ -221,7 +221,7 @@ namespace Grand.Web.Admin.ControllersnewShipIds.Add(s.Name);}}- await _paymentService.SaveRestictedShippingIds(pm, newShipIds);+ await _paymentService.SaveRestrictedShippingIds(pm, newShipIds);}Success(_translationService.GetResource("Admin.Configuration.Payment.MethodRestrictions.Updated"));diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.csindex 9b5196ae5..9bf2db5c2 100644--- a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs@@ -105,7 +105,7 @@ namespace Grand.Web.Admin.ControllerscreatedFromUtc: startDateValue,createdToUtc: endDateValue,storeId: model.StoreId,- orderguid: orderGuid,+ orderGuid: orderGuid,pageIndex: command.Page - 1,pageSize: command.PageSize);@@ -154,7 +154,7 @@ namespace Grand.Web.Admin.Controllersif (order == null)return RedirectToAction("List", "PaymentTransaction");- var paymentTransaction = await _paymentTransactionService.GetByOrdeGuid(order.OrderGuid);+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);if (paymentTransaction == null)//not foundreturn RedirectToAction("List", "PaymentTransaction");diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.csindex 6be4e7c7e..a6b75ba40 100644--- a/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs@@ -219,7 +219,7 @@ namespace Grand.Web.Admin.Controllers[HttpPost]public async Task<IActionResult> UsedByProducts(DataSourceRequest command, string productAttributeId){- var orders = await _productService.GetProductsByProductAtributeId(+ var orders = await _productService.GetProductsByProductAttributeId(productAttributeId: productAttributeId,pageIndex: command.Page - 1,pageSize: command.PageSize);diff --git a/src/Web/Grand.Web.Admin/Services/CheckoutAttributeViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CheckoutAttributeViewModelService.csindex 5209f2887..18fe87405 100644--- a/src/Web/Grand.Web.Admin/Services/CheckoutAttributeViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/CheckoutAttributeViewModelService.cs@@ -91,7 +91,7 @@ namespace Grand.Web.Admin.Services{EnableCondition = checkoutAttribute.ConditionAttribute.Any(),SelectedAttributeId = selectedAttribute != null ? selectedAttribute.Id : "",- ConditionAttributes = (await _checkoutAttributeService.GetAllCheckoutAttributes(ignorAcl: false))+ ConditionAttributes = (await _checkoutAttributeService.GetAllCheckoutAttributes(ignoreAcl: false))//ignore this attribute and non-combinable attributes.Where(x => x.Id != checkoutAttribute.Id && x.CanBeUsedAsCondition()).Select(x =>@@ -166,7 +166,7 @@ namespace Grand.Web.Admin.Servicespublic virtual async Task<IEnumerable<CheckoutAttributeModel>> PrepareCheckoutAttributeListModel(){- var checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(ignorAcl: true);+ var checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(ignoreAcl: true);return checkoutAttributes.Select((Func<CheckoutAttribute, CheckoutAttributeModel>)(x =>{var attributeModel = x.ToModel();diff --git a/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.csindex 0f075077f..8a13ea9d6 100644--- a/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs@@ -94,7 +94,7 @@ namespace Grand.Web.Admin.Servicespublic virtual async Task<IEnumerable<ContactAttributeModel>> PrepareContactAttributeListModel(){- var contactAttributes = await _contactAttributeService.GetAllContactAttributes(_workContext.CurrentCustomer.StaffStoreId, ignorAcl: true);+ var contactAttributes = await _contactAttributeService.GetAllContactAttributes(_workContext.CurrentCustomer.StaffStoreId, ignoreAcl: true);return contactAttributes.Select(x =>{var attributeModel = x.ToModel();@@ -121,7 +121,7 @@ namespace Grand.Web.Admin.Services{EnableCondition = contactAttribute.ConditionAttribute.Any(),SelectedAttributeId = selectedAttribute != null ? selectedAttribute.Id : "",- ConditionAttributes = (await _contactAttributeService.GetAllContactAttributes(_workContext.CurrentCustomer.StaffStoreId, ignorAcl: true))+ ConditionAttributes = (await _contactAttributeService.GetAllContactAttributes(_workContext.CurrentCustomer.StaffStoreId, ignoreAcl: true))//ignore this attribute and non-combinable attributes.Where(x => x.Id != contactAttribute.Id && x.CanBeUsedAsCondition()).Select(x =>diff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.csindex 379632991..1d77ae194 100644--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs@@ -961,7 +961,7 @@ namespace Grand.Web.Admin.Servicescustomer.Groups.Remove(customer.Groups.First(x => x == customerGroup.Id));}}- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);//ensure that a customer with a vendor associated is not in "Administrators" role@@ -969,7 +969,7 @@ namespace Grand.Web.Admin.Servicesif (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(customer.VendorId)){customer.VendorId = "";- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);}//ensure that a customer with a staff associated is not in "Administrators" role@@ -977,7 +977,7 @@ namespace Grand.Web.Admin.Servicesif (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(customer.StaffStoreId)){customer.StaffStoreId = "";- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);}//ensure that a customer in the Vendors role has a vendor account associated.@@ -1141,7 +1141,7 @@ namespace Grand.Web.Admin.Servicespublic virtual async Task DeleteAddress(Customer customer, Address address){customer.RemoveAddress(address);- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);}public virtual async Task<Address> InsertAddressModel(Customer customer, CustomerAddressModel model, List<CustomAttribute> customAttributes)@@ -1150,7 +1150,7 @@ namespace Grand.Web.Admin.Servicesaddress.Attributes = customAttributes;address.CreatedOnUtc = DateTime.UtcNow;customer.Addresses.Add(address);- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);return address;}@@ -1219,7 +1219,7 @@ namespace Grand.Web.Admin.Services{address = model.Address.ToEntity(address);address.Attributes = customAttributes;- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);return address;}@@ -1266,7 +1266,7 @@ namespace Grand.Web.Admin.Services{await _serviceProvider.GetRequiredService<IShoppingCartService>().DeleteShoppingCartItem(customer, cart, ensureOnlyActiveCheckoutAttributes: true);- await _customerService.UpdateCustomerinAdminPanel(customer);+ await _customerService.UpdateCustomerInAdminPanel(customer);}}diff --git a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.csindex f58249145..acb96d3d6 100644--- a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs@@ -576,7 +576,7 @@ namespace Grand.Web.Admin.Servicesmodel.PaymentMethod = pm != null ? pm.FriendlyName : order.PaymentMethodSystemName;model.PaymentStatus = order.PaymentStatusId.GetTranslationEnum(_translationService, _workContext);model.PaymentStatusEnum = order.PaymentStatusId;- var pt = await _paymentTransactionService.GetByOrdeGuid(order.OrderGuid);+ var pt = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);if (pt != null)model.PaymentTransactionId = pt.Id;diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.csindex 44be79d9b..b48e37845 100644--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs@@ -78,7 +78,7 @@ namespace Grand.Web.Common.Infrastructure_ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception.Message, exception.ToString(),customer: workContext.CurrentCustomer,ipAddress: context.Connection?.RemoteIpAddress?.ToString(),- pageurl: context.Request?.GetDisplayUrl(),+ pageUrl: context.Request?.GetDisplayUrl(),referrerUrl: context.Request?.GetTypedHeaders().Referer?.ToString());//log error_ = logger.Error(exception.Message, exception, workContext.CurrentCustomer);@@ -125,7 +125,7 @@ namespace Grand.Web.Common.Infrastructure$"Error 404. The requested page ({context.HttpContext.Request?.GetDisplayUrl()}) was not found",customer: workContext.CurrentCustomer,ipAddress: context.HttpContext?.Connection?.RemoteIpAddress?.ToString(),- pageurl: context.HttpContext?.Request?.GetDisplayUrl(),+ pageUrl: context.HttpContext?.Request?.GetDisplayUrl(),referrerUrl: context.HttpContext?.Request?.GetTypedHeaders().Referer?.ToString());}}@@ -153,7 +153,7 @@ namespace Grand.Web.Common.Infrastructurevar workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();_ = logger.InsertLog(Domain.Logging.LogLevel.Error, "Error 400. Bad request", null, customer: workContext.CurrentCustomer,ipAddress: context.HttpContext?.Connection?.RemoteIpAddress?.ToString(),- pageurl: context.HttpContext?.Request?.GetDisplayUrl(),+ pageUrl: context.HttpContext?.Request?.GetDisplayUrl(),referrerUrl: context.HttpContext?.Request?.GetTypedHeaders().Referer?.ToString());}}diff --git a/src/Web/Grand.Web/Controllers/OrderController.cs b/src/Web/Grand.Web/Controllers/OrderController.csindex a4e9249c6..e8dd81517 100644--- a/src/Web/Grand.Web/Controllers/OrderController.cs+++ b/src/Web/Grand.Web/Controllers/OrderController.cs@@ -206,7 +206,7 @@ namespace Grand.Web.Controllersif (!await order.Access(_workContext.CurrentCustomer, _groupService))return Challenge();- var paymentTransaction = await _paymentTransactionService.GetByOrdeGuid(order.OrderGuid);+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);if (paymentTransaction == null || !await _paymentService.CanRePostRedirectPayment(paymentTransaction))return RedirectToRoute("OrderDetails", new { orderId = orderId });diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.csindex 531c6db8a..05bd22e68 100644--- a/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs@@ -200,7 +200,7 @@ namespace Grand.Web.Features.Handlers.Ordersvar paymentMethod = _paymentService.LoadPaymentMethodBySystemName(request.Order.PaymentMethodSystemName);model.PaymentMethod = paymentMethod != null ? paymentMethod.FriendlyName : request.Order.PaymentMethodSystemName;model.PaymentMethodStatus = request.Order.PaymentStatusId.GetTranslationEnum(_translationService, request.Language.Id);- var paymentTransaction = await _paymentTransactionService.GetByOrdeGuid(request.Order.OrderGuid);+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(request.Order.OrderGuid);model.CanRePostProcessPayment = paymentTransaction != null ? await _paymentService.CanRePostRedirectPayment(paymentTransaction) : false;}diff --git a/src/Web/Grand.Web/Grand.Web.csproj b/src/Web/Grand.Web/Grand.Web.csprojindex 8288b74a2..ec7ec57ac 100644--- a/src/Web/Grand.Web/Grand.Web.csproj+++ b/src/Web/Grand.Web/Grand.Web.csproj@@ -1,7 +1,25 @@<Project Sdk="Microsoft.NET.Sdk.Web"><Import Project="..\..\Build\Grand.Common.props" /><PropertyGroup>+ <!--The common language runtime (CLR) supports two types of garbage collection:+ workstation garbage collection, which is available on all systems, and server garbage collection,+ which is available on multiprocessor systems.+ For single-processor computers, the default workstation garbage collection should be the fastest option.+ Either workstation or server can be used for two-processor computers.+ Server garbage collection should be the fastest option for more than two processors.+ More details about GC you can see here: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals--><ServerGarbageCollection>false</ServerGarbageCollection>+ <!--In workstation or server garbage collection, you can enable concurrent garbage collection,+ which enables threads to run concurrently with a dedicated thread that performs the garbage+ collection for most of the duration of the collection.+ Concurrent garbage collection enables interactive applications to be more responsive by+ minimizing pauses for a collection. Managed threads can continue to run most of the time while+ the concurrent garbage collection thread is running. This results in shorter pauses while+ a garbage collection is occurring.+ To improve performance when several processes are running, disable concurrent garbage collection.+ More details here: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#concurrent-garbage-collection-->+ <ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>+<PreserveCompilationReferences>true</PreserveCompilationReferences><DockerComposeProjectPath>..\..\..\docker-compose.dcproj</DockerComposeProjectPath><UserSecretsId>a2091e37-94a0-4446-8a5d-1d5c0835333a</UserSecretsId>