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
Grand.Api - Code cleanup (ReSharper)
support320d2cd4a5d4
diff --git a/src/API/Grand.Api/ApiExplorer/ApiParameterContext.cs b/src/API/Grand.Api/ApiExplorer/ApiParameterContext.csindex 6a791136b..bcd7f8a5d 100644--- a/src/API/Grand.Api/ApiExplorer/ApiParameterContext.cs+++ b/src/API/Grand.Api/ApiExplorer/ApiParameterContext.cs@@ -28,4 +28,4 @@ public class ApiParameterContextpublic IList<ApiParameterDescription> Results { get; }public IReadOnlyList<TemplatePart> RouteParameters { get; }-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/ApiExplorer/ApiResponseTypeProvider.cs b/src/API/Grand.Api/ApiExplorer/ApiResponseTypeProvider.csindex e4f4087f9..e1966754c 100644--- a/src/API/Grand.Api/ApiExplorer/ApiResponseTypeProvider.cs+++ b/src/API/Grand.Api/ApiExplorer/ApiResponseTypeProvider.cs@@ -14,8 +14,8 @@ namespace Grand.Api.ApiExplorer;public class ApiResponseTypeProvider{- private readonly IModelMetadataProvider _modelMetadataProvider;private readonly IActionResultTypeMapper _mapper;+ private readonly IModelMetadataProvider _modelMetadataProvider;private readonly MvcOptions _mvcOptions;public ApiResponseTypeProvider(@@ -47,9 +47,7 @@ public class ApiResponseTypeProvidervar defaultErrorType = typeof(void);if (action.Properties.TryGetValue(typeof(ProducesErrorResponseTypeAttribute), out result))- {defaultErrorType = ((ProducesErrorResponseTypeAttribute)result!).Type;- }var apiResponseTypes = GetApiResponseTypes(responseMetadataAttributes, runtimeReturnType, defaultErrorType);return apiResponseTypes;@@ -85,28 +83,22 @@ public class ApiResponseTypeProvider// Set the default status only when no status has already been set explicitlyif (responseTypes.Count == 0 && type != null)- {responseTypes.Add(new ApiResponseType {StatusCode = StatusCodes.Status200OK,Type = type});- }if (contentTypes.Count == 0)- {// None of the IApiResponseMetadataProvider specified a content type. This is common for actions that// specify one or more ProducesResponseType but no ProducesAttribute. In this case, formatters will participate in conneg// and respond to the incoming request.// Querying IApiResponseTypeMetadataProvider.GetSupportedContentTypes with "null" should retrieve all supported// content types that each formatter may respond in.contentTypes.Add((string)null!);- }foreach (var apiResponse in responseTypes)- {CalculateResponseFormatForType(apiResponse, contentTypes, responseTypeMetadataProviders,_modelMetadataProvider);- }return responseTypes;}@@ -135,10 +127,7 @@ public class ApiResponseTypeProvider// Produces exists on both a controller and an action within the controller,// we favor the definition in the action. This is a semantic that does not// apply to ProducesResponseType, which allows multiple instances on an target.- if (metadataAttribute is not ProducesResponseTypeAttribute)- {- metadataAttribute.SetContentTypes(contentTypes);- }+ if (metadataAttribute is not ProducesResponseTypeAttribute) metadataAttribute.SetContentTypes(contentTypes);var statusCode = metadataAttribute.StatusCode;@@ -151,13 +140,11 @@ public class ApiResponseTypeProviderif (apiResponseType.Type == typeof(void)){if (type != null && statusCode is StatusCodes.Status200OK or StatusCodes.Status201Created)- {// ProducesResponseTypeAttribute's constructor defaults to setting "Type" to void when no value is specified.// In this event, use the action's return type for 200 or 201 status codes. This lets you decorate an action with a// [ProducesResponseType(201)] instead of [ProducesResponseType(typeof(Person), 201] when typeof(Person) can be inferred// from the return type.apiResponseType.Type = type;- }/*else if (IsClientError(statusCode)){// Determine whether or not the type was provided by the user. If so, favor it over the default@@ -167,10 +154,7 @@ public class ApiResponseTypeProvider};apiResponseType.Type = setByDefault ? defaultErrorType : apiResponseType.Type;}*/- else if (apiResponseType.IsDefaultResponse)- {- apiResponseType.Type = defaultErrorType;- }+ else if (apiResponseType.IsDefaultResponse) apiResponseType.Type = defaultErrorType;}// We special case the handling of ProcuesResponseTypeAttributes since@@ -186,12 +170,9 @@ public class ApiResponseTypeProviderresponseTypeMetadataProviders, modelMetadataProvider);}- if (apiResponseType.Type != null)- {- results[apiResponseType.StatusCode] = apiResponseType;- }+ if (apiResponseType.Type != null) results[apiResponseType.StatusCode] = apiResponseType;}-+return results.Values.ToList();}@@ -204,10 +185,7 @@ public class ApiResponseTypeProvider// If response formats have already been calculate for this type,// then exit early. This avoids populating the ApiResponseFormat for// types that have already been handled, specifically ProducesResponseTypes.- if (apiResponse.ApiResponseFormats.Count > 0)- {- return;- }+ if (apiResponse.ApiResponseFormats.Count > 0) return;// Given the content-types that were declared for this action, determine the formatters that support the content-type for the given// response type.@@ -218,10 +196,7 @@ public class ApiResponseTypeProvider// dictates the content-type.// e.g. [Produces("application/pdf")] Action() => FileStream("somefile.pdf", "application/pdf");var responseType = apiResponse.Type;- if (responseType == null || responseType == typeof(void))- {- return;- }+ if (responseType == null || responseType == typeof(void)) return;apiResponse.ModelMetadata = modelMetadataProvider?.GetMetadataForType(responseType);@@ -230,38 +205,29 @@ public class ApiResponseTypeProvidervar isSupportedContentType = false;if (responseTypeMetadataProviders != null)- {foreach (var responseTypeMetadataProvider in responseTypeMetadataProviders){var formatterSupportedContentTypes = responseTypeMetadataProvider.GetSupportedContentTypes(contentType,responseType);- if (formatterSupportedContentTypes == null)- {- continue;- }+ if (formatterSupportedContentTypes == null) continue;isSupportedContentType = true;foreach (var formatterSupportedContentType in formatterSupportedContentTypes)- {apiResponse.ApiResponseFormats.Add(new ApiResponseFormat {Formatter = (IOutputFormatter)responseTypeMetadataProvider,MediaType = formatterSupportedContentType});- }}- }if (!isSupportedContentType)- {// No output formatter was found that supports this content type. Add the user specified content type as-is to the result.apiResponse.ApiResponseFormats.Add(new ApiResponseFormat {MediaType = contentType});- }}}@@ -271,25 +237,18 @@ public class ApiResponseTypeProviderif (declaredReturnType == typeof(void) ||declaredReturnType == typeof(Task) ||declaredReturnType == typeof(ValueTask))- {return typeof(void);- }// Unwrap the type if it's a Task<T>. The Task (non-generic) case was already handled.var unwrappedType = declaredReturnType;if (declaredReturnType.IsGenericType &&(declaredReturnType.GetGenericTypeDefinition() == typeof(Task<>) ||declaredReturnType.GetGenericTypeDefinition() == typeof(ValueTask<>)))- {unwrappedType = declaredReturnType.GetGenericArguments()[0];- }// If the method is declared to return IActionResult or a derived class, that information// isn't valuable to the formatter.- if (typeof(IActionResult).IsAssignableFrom(unwrappedType))- {- return null;- }+ if (typeof(IActionResult).IsAssignableFrom(unwrappedType)) return null;// If we get here, the type should be a user-defined data type or an envelope type// like ActionResult<T>. The mapper service will unwrap envelopes.@@ -315,10 +274,8 @@ public class ApiResponseTypeProvidervar provider = providers[i];if (provider is ProducesAttribute { Type: null })- {// ProducesAttribute that does not specify type is considered not significant.continue;- }// Any other IApiResponseMetadataProvider is considered significantreturn true;diff --git a/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs b/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.csindex e52c96cc7..c483be7ba 100644--- a/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs+++ b/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs@@ -17,27 +17,30 @@ using Microsoft.AspNetCore.Routing;using Microsoft.AspNetCore.Routing.Template;using Microsoft.Extensions.Options;using System.Reflection;+using ApiControllerAttribute = Grand.SharedKernel.Attributes.ApiControllerAttribute;namespace Grand.Api.ApiExplorer;public class MetadataApiDescriptionProvider : IApiDescriptionProvider{- private readonly MvcOptions _mvcOptions;- private readonly RouteOptions _routeOptions;private readonly IInlineConstraintResolver _constraintResolver;private readonly IModelMetadataProvider _modelMetadataProvider;+ private readonly MvcOptions _mvcOptions;private readonly ApiResponseTypeProvider _responseTypeProvider;+ private readonly RouteOptions _routeOptions;/// <summary>- /// Creates a new instance of <see cref="DefaultApiDescriptionProvider"/>.+ /// Creates a new instance of <see cref="DefaultApiDescriptionProvider" />./// </summary>- /// <param name="optionsAccessor">The accessor for <see cref="MvcOptions"/>.</param>- /// <param name="constraintResolver">The <see cref="IInlineConstraintResolver"/> used for resolving inline- /// constraints.</param>- /// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param>- /// <param name="mapper">The <see cref="IActionResultTypeMapper"/>.</param>- /// <param name="routeOptions">The accessor for <see cref="RouteOptions"/>.</param>- /// <remarks>The <paramref name="mapper"/> parameter is currently ignored.</remarks>+ /// <param name="optionsAccessor">The accessor for <see cref="MvcOptions" />.</param>+ /// <param name="constraintResolver">+ /// The <see cref="IInlineConstraintResolver" /> used for resolving inline+ /// constraints.+ /// </param>+ /// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider" />.</param>+ /// <param name="mapper">The <see cref="IActionResultTypeMapper" />.</param>+ /// <param name="routeOptions">The accessor for <see cref="RouteOptions" />.</param>+ /// <remarks>The <paramref name="mapper" /> parameter is currently ignored.</remarks>public MetadataApiDescriptionProvider(IOptions<MvcOptions> optionsAccessor,IInlineConstraintResolver constraintResolver,@@ -62,23 +65,17 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderforeach (var action in context.Actions.OfType<ControllerActionDescriptor>()){- if (!action.ControllerTypeInfo.GetCustomAttributes<SharedKernel.Attributes.ApiControllerAttribute>(true)+ if (!action.ControllerTypeInfo.GetCustomAttributes<ApiControllerAttribute>(true).Any())continue;if (action.MethodInfo.GetCustomAttributes<IgnoreApiAttribute>(true).Any())continue;- if (action.AttributeRouteInfo is { SuppressPathMatching: true })- {- continue;- }+ if (action.AttributeRouteInfo is { SuppressPathMatching: true }) continue;var httpMethods = GetHttpMethods(action);- foreach (var httpMethod in httpMethods)- {- context.Results.Add(CreateApiDescription(action, httpMethod, "v2"));- }+ foreach (var httpMethod in httpMethods) context.Results.Add(CreateApiDescription(action, httpMethod, "v2"));}}@@ -107,17 +104,12 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvidervar parameterContext = new ApiParameterContext(_modelMetadataProvider, action, templateParameters);foreach (var parameter in GetParameters(parameterContext,httpMethod.Equals("GET", StringComparison.CurrentCultureIgnoreCase)))- {apiDescription.ParameterDescriptions.Add(parameter);- }var requestMetadataAttributes = GetRequestMetadataAttributes(action);var apiResponseTypes = _responseTypeProvider.GetApiResponseTypes(action);- foreach (var apiResponseType in apiResponseTypes)- {- apiDescription.SupportedResponseTypes.Add(apiResponseType);- }+ foreach (var apiResponseType in apiResponseTypes) apiDescription.SupportedResponseTypes.Add(apiResponseType);// It would be possible here to configure an action with multiple body parameters, in which case you// could end up with duplicate data.@@ -125,29 +117,22 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider{var contentTypes = GetDeclaredContentTypes(requestMetadataAttributes);foreach (var parameter in apiDescription.ParameterDescriptions)- {if (parameter.Source == BindingSource.Body ||parameter.Source == BindingSource.Form){// For request body bound parameters, determine the content types supported// by input formatters.var requestFormats = GetSupportedFormats(contentTypes, parameter.Type);- foreach (var format in requestFormats)- {- apiDescription.SupportedRequestFormats.Add(format);- }+ foreach (var format in requestFormats) apiDescription.SupportedRequestFormats.Add(format);}else if (parameter.Source == BindingSource.FormFile){// Add all declared media types since FormFiles do not get processed by formatters.foreach (var contentType in contentTypes)- {apiDescription.SupportedRequestFormats.Add(new ApiRequestFormat {MediaType = contentType});- }}- }}return apiDescription;@@ -163,19 +148,15 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderModelMetadata metadata;if (actionParameter is ControllerParameterDescriptor controllerParameterDescriptor &&_modelMetadataProvider is ModelMetadataProvider provider)- {// The default model metadata provider derives from ModelMetadataProvider// and can therefore supply information about attributes applied to parameters.metadata = provider.GetMetadataForParameter(controllerParameterDescriptor.ParameterInfo);- }else- {// For backward compatibility, if there's a custom model metadata provider that// only implements the older IModelMetadataProvider interface, access the more// limited metadata information it supplies. In this scenario, validation attributes// are not supported on parameters.metadata = _modelMetadataProvider.GetMetadataForType(actionParameter.ParameterType);- }if (!httpGet &&actionParameter.BindingInfo == null &&@@ -186,7 +167,7 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvidernew BindingInfo {BindingSource = new BindingSource("Body", "Body", true, true)},- propertyName: actionParameter.Name);+ actionParameter.Name);visitor.WalkParameter(bindingContext);}else@@ -194,7 +175,7 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvidervar bindingContext = new ApiParameterDescriptionContext(metadata,actionParameter.BindingInfo,- propertyName: actionParameter.Name);+ actionParameter.Name);visitor.WalkParameter(bindingContext);}}@@ -203,19 +184,18 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider{var visitor = new PseudoModelBindingVisitor(context, actionParameter);var modelMetadata = context.MetadataProvider.GetMetadataForProperty(- containerType: context.ActionDescriptor.ControllerTypeInfo.AsType(),- propertyName: actionParameter.Name);+ context.ActionDescriptor.ControllerTypeInfo.AsType(),+ actionParameter.Name);var bindingContext = new ApiParameterDescriptionContext(modelMetadata,actionParameter.BindingInfo,- propertyName: actionParameter.Name);+ actionParameter.Name);visitor.WalkParameter(bindingContext);}for (var i = context.Results.Count - 1; i >= 0; i--)- {// Remove any 'hidden' parameters. These are things that can't come from user input,// so they aren't worth showing.if (!context.Results[i].Source.IsFromRequest)@@ -228,7 +208,6 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvidermetadata.Attributes.Attributes.OfType<IgnoreApiUrlAttribute>().Any())context.Results.RemoveAt(i);}- }// Next, we want to join up any route parameters with those discovered from the action's parameters.// This will result us in creating a parameter representation for each route parameter that does not@@ -248,16 +227,12 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider{var routeParameters = new Dictionary<string, ApiParameterRouteInfo>(StringComparer.OrdinalIgnoreCase);foreach (var routeParameter in context.RouteParameters)- {routeParameters.Add(routeParameter.Name!, CreateRouteInfo(routeParameter));- }foreach (var parameter in context.Results)- {if (parameter.Source == BindingSource.Path ||parameter.Source == BindingSource.ModelBinding ||parameter.Source == BindingSource.Custom)- {if (routeParameters.TryGetValue(parameter.Name, out var routeInfo)){parameter.RouteInfo = routeInfo;@@ -265,25 +240,19 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderif (parameter.Source == BindingSource.ModelBinding &&!parameter.RouteInfo.IsOptional)- {// If we didn't see any information about the parameter, but we have// a route parameter that matches, let's switch it to path.parameter.Source = BindingSource.Path;- }}- }- }// Lastly, create a parameter representation for each route parameter that did not find// a partner.foreach (var routeParameter in routeParameters)- {context.Results.Add(new ApiParameterDescription {Name = routeParameter.Key,RouteInfo = routeParameter.Value,Source = BindingSource.Path});- }}internal static void ProcessIsRequired(ApiParameterContext context, MvcOptions mvcOptions)@@ -294,36 +263,24 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider{if (parameter.BindingInfo == null ||parameter.BindingInfo.EmptyBodyBehavior == EmptyBodyBehavior.Default)- {parameter.IsRequired = !mvcOptions.AllowEmptyInputInBodyModelBinding;- }else- {parameter.IsRequired = parameter.BindingInfo.EmptyBodyBehavior != EmptyBodyBehavior.Allow;- }}- if (parameter.ModelMetadata is { IsBindingRequired: true })- {- parameter.IsRequired = true;- }+ if (parameter.ModelMetadata is { IsBindingRequired: true }) parameter.IsRequired = true;if (parameter.Source == BindingSource.Path && parameter.RouteInfo is { IsOptional: false })- {parameter.IsRequired = true;- }}}internal static void ProcessParameterDefaultValue(ApiParameterContext context){foreach (var parameter in context.Results)- {if (parameter.Source == BindingSource.Path)- {parameter.DefaultValue = parameter.RouteInfo?.DefaultValue;- }- /*else+ /*else{if (parameter.ParameterDescriptor is ControllerParameterDescriptor controllerParameter &&ParameterDefaultValues.TryGetDeclaredParameterDefaultValue(controllerParameter.ParameterInfo,@@ -332,16 +289,13 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderparameter.DefaultValue = defaultValue;}}*/- }}private ApiParameterRouteInfo CreateRouteInfo(TemplatePart routeParameter){var constraints = new List<IRouteConstraint>();foreach (var constraint in routeParameter.InlineConstraints)- {constraints.Add(_constraintResolver.ResolveConstraint(constraint.Constraint)!);- }return new ApiParameterRouteInfo {Constraints = constraints,@@ -366,10 +320,7 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderprivate string? GetRelativePath(ControllerActionDescriptor action, RouteTemplate? parsedTemplate){- if (parsedTemplate == null)- {- return $"/{action.ControllerName}/{action.ActionName}";- }+ if (parsedTemplate == null) return $"/{action.ControllerName}/{action.ActionName}";var segments = new List<string>();@@ -377,16 +328,9 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider{var currentSegment = string.Empty;foreach (var part in segment.Parts)- {if (part.IsLiteral)- {currentSegment += _routeOptions.LowercaseUrls ? part.Text!.ToLowerInvariant() : part.Text;- }- else if (part.IsParameter)- {- currentSegment += "{" + part.Name + "}";- }- }+ else if (part.IsParameter) currentSegment += "{" + part.Name + "}";segments.Add(currentSegment);}@@ -396,33 +340,22 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderprivate IReadOnlyList<ApiRequestFormat> GetSupportedFormats(MediaTypeCollection contentTypes, Type type){- if (contentTypes.Count == 0)- {- contentTypes = ["application/json"];- }+ if (contentTypes.Count == 0) contentTypes = ["application/json"];var results = new List<ApiRequestFormat>();foreach (var contentType in contentTypes)- {- foreach (var formatter in _mvcOptions.InputFormatters.OfType<SystemTextJsonInputFormatter>())+ foreach (var formatter in _mvcOptions.InputFormatters.OfType<SystemTextJsonInputFormatter>())+ if (formatter is IApiRequestFormatMetadataProvider requestFormatMetadataProvider){- if (formatter is IApiRequestFormatMetadataProvider requestFormatMetadataProvider)- {- var supportedTypes = requestFormatMetadataProvider.GetSupportedContentTypes(contentType, type);-- if (supportedTypes != null)- {- foreach (var supportedType in supportedTypes.Where(x => x == "application/json"))- {- results.Add(new ApiRequestFormat {- Formatter = formatter,- MediaType = supportedType- });- }- }- }+ var supportedTypes = requestFormatMetadataProvider.GetSupportedContentTypes(contentType, type);++ if (supportedTypes != null)+ foreach (var supportedType in supportedTypes.Where(x => x == "application/json"))+ results.Add(new ApiRequestFormat {+ Formatter = formatter,+ MediaType = supportedType+ });}- }return results;}@@ -434,12 +367,8 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider// the results of the previous ones. This is similar to the execution path for content-negotiation.var contentTypes = new MediaTypeCollection();if (requestMetadataAttributes != null)- {foreach (var metadataAttribute in requestMetadataAttributes)- {metadataAttribute.SetContentTypes(contentTypes);- }- }return contentTypes;}@@ -458,16 +387,6 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderprivate class ApiParameterDescriptionContext{- public ModelMetadata ModelMetadata { get; }-- public string? BinderModelName { get; }-- public BindingSource? BindingSource { get; }-- public string? PropertyName { get; }-- public BindingInfo? BindingInfo { get; }-public ApiParameterDescriptionContext(ModelMetadata metadata,BindingInfo? bindingInfo,@@ -480,6 +399,16 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProviderPropertyName = propertyName ?? metadata.Name;BindingInfo = bindingInfo;}++ public ModelMetadata ModelMetadata { get; }++ public string? BinderModelName { get; }++ public BindingSource? BindingSource { get; }++ public string? PropertyName { get; }++ public BindingInfo? BindingInfo { get; }}private class PseudoModelBindingVisitor@@ -505,7 +434,7 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider//// The default is ModelBinding (aka all default value providers)var source = BindingSource.ModelBinding;- Visit(context, source, containerName: string.Empty);+ Visit(context, source, string.Empty);}private void Visit(@@ -564,10 +493,7 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider// We don't want to append the **parameter** name when building a model name.var newContainerName = containerName;- if (modelMetadata.ContainerType != null)- {- newContainerName = GetName(containerName, bindingContext);- }+ if (modelMetadata.ContainerType != null) newContainerName = GetName(containerName, bindingContext);var metadataProperties = modelMetadata.Properties;var metadataPropertiesCount = metadataProperties.Count;@@ -579,8 +505,8 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvidervar propertyContext = new ApiParameterDescriptionContext(propertyMetadata,- bindingInfo: bindingInfo,- propertyName: null);+ bindingInfo,+ null);if (Visited.Add(key)){diff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddBrandCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddBrandCommandHandler.csindex c05cce808..a04db90aa 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddBrandCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddBrandCommandHandler.cs@@ -8,37 +8,37 @@ using Grand.Business.Core.Interfaces.Common.Seo;using Grand.Domain.Seo;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddBrandCommandHandler : IRequestHandler<AddBrandCommand, BrandDto>{- public class AddBrandCommandHandler : IRequestHandler<AddBrandCommand, BrandDto>- {- private readonly IBrandService _brandService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly SeoSettings _seoSettings;+ private readonly IBrandService _brandService;+ private readonly ILanguageService _languageService;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;- public AddBrandCommandHandler(- IBrandService brandService,- ISlugService slugService,- ILanguageService languageService,- SeoSettings seoSettings)- {- _brandService = brandService;- _slugService = slugService;- _languageService = languageService;- _seoSettings = seoSettings;- }+ public AddBrandCommandHandler(+ IBrandService brandService,+ ISlugService slugService,+ ILanguageService languageService,+ SeoSettings seoSettings)+ {+ _brandService = brandService;+ _slugService = slugService;+ _languageService = languageService;+ _seoSettings = seoSettings;+ }- public async Task<BrandDto> Handle(AddBrandCommand request, CancellationToken cancellationToken)- {- var brand = request.Model.ToEntity();- await _brandService.InsertBrand(brand);- request.Model.SeName = await brand.ValidateSeName(request.Model.SeName, brand.Name, true, _seoSettings, _slugService, _languageService);- brand.SeName = request.Model.SeName;- await _brandService.UpdateBrand(brand);- await _slugService.SaveSlug(brand, request.Model.SeName, "");+ public async Task<BrandDto> Handle(AddBrandCommand request, CancellationToken cancellationToken)+ {+ var brand = request.Model.ToEntity();+ await _brandService.InsertBrand(brand);+ request.Model.SeName = await brand.ValidateSeName(request.Model.SeName, brand.Name, true, _seoSettings,+ _slugService, _languageService);+ brand.SeName = request.Model.SeName;+ await _brandService.UpdateBrand(brand);+ await _slugService.SaveSlug(brand, request.Model.SeName, "");- return brand.ToModel();- }+ return brand.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddCategoryCommandHandler.csindex efdd7b6a3..77e565e61 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddCategoryCommandHandler.cs@@ -8,38 +8,37 @@ using Grand.Business.Core.Interfaces.Common.Seo;using Grand.Domain.Seo;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddCategoryCommandHandler : IRequestHandler<AddCategoryCommand, CategoryDto>{- public class AddCategoryCommandHandler : IRequestHandler<AddCategoryCommand, CategoryDto>- {- private readonly ICategoryService _categoryService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly SeoSettings _seoSettings;+ private readonly ICategoryService _categoryService;+ private readonly ILanguageService _languageService;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;- public AddCategoryCommandHandler(- ICategoryService categoryService,- ISlugService slugService,- ILanguageService languageService,- SeoSettings seoSettings)- {- _categoryService = categoryService;- _slugService = slugService;- _languageService = languageService;- _seoSettings = seoSettings;- }+ public AddCategoryCommandHandler(+ ICategoryService categoryService,+ ISlugService slugService,+ ILanguageService languageService,+ SeoSettings seoSettings)+ {+ _categoryService = categoryService;+ _slugService = slugService;+ _languageService = languageService;+ _seoSettings = seoSettings;+ }- public async Task<CategoryDto> Handle(AddCategoryCommand request, CancellationToken cancellationToken)- {- var category = request.Model.ToEntity();- await _categoryService.InsertCategory(category);- request.Model.SeName = await category.ValidateSeName(request.Model.SeName,- category.Name, true, _seoSettings, _slugService, _languageService);- category.SeName = request.Model.SeName;- await _categoryService.UpdateCategory(category);- await _slugService.SaveSlug(category, request.Model.SeName, "");+ public async Task<CategoryDto> Handle(AddCategoryCommand request, CancellationToken cancellationToken)+ {+ var category = request.Model.ToEntity();+ await _categoryService.InsertCategory(category);+ request.Model.SeName = await category.ValidateSeName(request.Model.SeName,+ category.Name, true, _seoSettings, _slugService, _languageService);+ category.SeName = request.Model.SeName;+ await _categoryService.UpdateCategory(category);+ await _slugService.SaveSlug(category, request.Model.SeName, "");- return category.ToModel();- }+ return category.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddCollectionCommandHandler.csindex 86458067b..dae7c096a 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddCollectionCommandHandler.cs@@ -9,43 +9,43 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddCollectionCommandHandler : IRequestHandler<AddCollectionCommand, CollectionDto>{- public class AddCollectionCommandHandler : IRequestHandler<AddCollectionCommand, CollectionDto>- {- private readonly ICollectionService _collectionService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;- private readonly SeoSettings _seoSettings;+ private readonly ICollectionService _collectionService;+ private readonly ILanguageService _languageService;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public AddCollectionCommandHandler(- ICollectionService collectionService,- ISlugService slugService,- ILanguageService languageService,- ITranslationService translationService,- IWorkContext workContext,- SeoSettings seoSettings)- {- _collectionService = collectionService;- _slugService = slugService;- _languageService = languageService;- _translationService = translationService;- _workContext = workContext;- _seoSettings = seoSettings;- }+ public AddCollectionCommandHandler(+ ICollectionService collectionService,+ ISlugService slugService,+ ILanguageService languageService,+ ITranslationService translationService,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _collectionService = collectionService;+ _slugService = slugService;+ _languageService = languageService;+ _translationService = translationService;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }- public async Task<CollectionDto> Handle(AddCollectionCommand request, CancellationToken cancellationToken)- {- var collection = request.Model.ToEntity();- await _collectionService.InsertCollection(collection);- request.Model.SeName = await collection.ValidateSeName(request.Model.SeName, collection.Name, true, _seoSettings, _slugService, _languageService);- collection.SeName = request.Model.SeName;- await _collectionService.UpdateCollection(collection);- await _slugService.SaveSlug(collection, request.Model.SeName, "");+ public async Task<CollectionDto> Handle(AddCollectionCommand request, CancellationToken cancellationToken)+ {+ var collection = request.Model.ToEntity();+ await _collectionService.InsertCollection(collection);+ request.Model.SeName = await collection.ValidateSeName(request.Model.SeName, collection.Name, true,+ _seoSettings, _slugService, _languageService);+ collection.SeName = request.Model.SeName;+ await _collectionService.UpdateCollection(collection);+ await _slugService.SaveSlug(collection, request.Model.SeName, "");- return collection.ToModel();- }+ return collection.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.csindex fe1e8285d..617709e44 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs@@ -6,30 +6,30 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductAttributeCommandHandler : IRequestHandler<AddProductAttributeCommand, ProductAttributeDto>{- public class AddProductAttributeCommandHandler : IRequestHandler<AddProductAttributeCommand, ProductAttributeDto>- {- private readonly IProductAttributeService _productAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IProductAttributeService _productAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public AddProductAttributeCommandHandler(- IProductAttributeService productAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _productAttributeService = productAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public AddProductAttributeCommandHandler(+ IProductAttributeService productAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _productAttributeService = productAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<ProductAttributeDto> Handle(AddProductAttributeCommand request, CancellationToken cancellationToken)- {- var productAttribute = request.Model.ToEntity();- await _productAttributeService.InsertProductAttribute(productAttribute);+ public async Task<ProductAttributeDto> Handle(AddProductAttributeCommand request,+ CancellationToken cancellationToken)+ {+ var productAttribute = request.Model.ToEntity();+ await _productAttributeService.InsertProductAttribute(productAttribute);- return productAttribute.ToModel();- }+ return productAttribute.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.csindex 395ed6444..d87d52b12 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs@@ -4,24 +4,26 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class+ AddProductAttributeMappingCommandHandler : IRequestHandler<AddProductAttributeMappingCommand,+ ProductAttributeMappingDto>{- public class AddProductAttributeMappingCommandHandler : IRequestHandler<AddProductAttributeMappingCommand, ProductAttributeMappingDto>- {- private readonly IProductAttributeService _productAttributeService;+ private readonly IProductAttributeService _productAttributeService;- public AddProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)- {- _productAttributeService = productAttributeService;- }+ public AddProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)+ {+ _productAttributeService = productAttributeService;+ }- public async Task<ProductAttributeMappingDto> Handle(AddProductAttributeMappingCommand request, CancellationToken cancellationToken)- {- //insert mapping- var productAttributeMapping = request.Model.ToEntity();- await _productAttributeService.InsertProductAttributeMapping(productAttributeMapping, request.Product.Id);+ public async Task<ProductAttributeMappingDto> Handle(AddProductAttributeMappingCommand request,+ CancellationToken cancellationToken)+ {+ //insert mapping+ var productAttributeMapping = request.Model.ToEntity();+ await _productAttributeService.InsertProductAttributeMapping(productAttributeMapping, request.Product.Id);- return productAttributeMapping.ToModel();- }+ return productAttributeMapping.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.csindex f4b9716ca..3017ab942 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs@@ -3,27 +3,25 @@ using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductCategoryCommandHandler : IRequestHandler<AddProductCategoryCommand, bool>{- public class AddProductCategoryCommandHandler : IRequestHandler<AddProductCategoryCommand, bool>- {- private readonly IProductCategoryService _productcategoryService;+ private readonly IProductCategoryService _productcategoryService;- public AddProductCategoryCommandHandler(IProductCategoryService productcategoryService)- {- _productcategoryService = productcategoryService;- }+ public AddProductCategoryCommandHandler(IProductCategoryService productcategoryService)+ {+ _productcategoryService = productcategoryService;+ }- public async Task<bool> Handle(AddProductCategoryCommand request, CancellationToken cancellationToken)- {- var productCategory = new ProductCategory- {- CategoryId = request.Model.CategoryId,- IsFeaturedProduct = request.Model.IsFeaturedProduct- };- await _productcategoryService.InsertProductCategory(productCategory, request.Product.Id);+ public async Task<bool> Handle(AddProductCategoryCommand request, CancellationToken cancellationToken)+ {+ var productCategory = new ProductCategory {+ CategoryId = request.Model.CategoryId,+ IsFeaturedProduct = request.Model.IsFeaturedProduct+ };+ await _productcategoryService.InsertProductCategory(productCategory, request.Product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.csindex 52bc6f351..d82d29abe 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs@@ -3,27 +3,25 @@ using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductCollectionCommandHandler : IRequestHandler<AddProductCollectionCommand, bool>{- public class AddProductCollectionCommandHandler : IRequestHandler<AddProductCollectionCommand, bool>- {- private readonly IProductCollectionService _productcollectionService;+ private readonly IProductCollectionService _productcollectionService;- public AddProductCollectionCommandHandler(IProductCollectionService productcollectionService)- {- _productcollectionService = productcollectionService;- }+ public AddProductCollectionCommandHandler(IProductCollectionService productcollectionService)+ {+ _productcollectionService = productcollectionService;+ }- public async Task<bool> Handle(AddProductCollectionCommand request, CancellationToken cancellationToken)- {- var productCollection = new ProductCollection- {- CollectionId = request.Model.CollectionId,- IsFeaturedProduct = request.Model.IsFeaturedProduct- };- await _productcollectionService.InsertProductCollection(productCollection, request.Product.Id);+ public async Task<bool> Handle(AddProductCollectionCommand request, CancellationToken cancellationToken)+ {+ var productCollection = new ProductCollection {+ CollectionId = request.Model.CollectionId,+ IsFeaturedProduct = request.Model.IsFeaturedProduct+ };+ await _productcollectionService.InsertProductCollection(productCollection, request.Product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCommandHandler.csindex 825243a35..eae1c4e40 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs@@ -9,46 +9,46 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductCommandHandler : IRequestHandler<AddProductCommand, ProductDto>{- public class AddProductCommandHandler : IRequestHandler<AddProductCommand, ProductDto>- {- private readonly IProductService _productService;- private readonly ISlugService _slugService;- private readonly ITranslationService _translationService;- private readonly ILanguageService _languageService;- private readonly IWorkContext _workContext;+ private readonly ILanguageService _languageService;+ private readonly IProductService _productService;- private readonly SeoSettings _seoSettings;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public AddProductCommandHandler(- IProductService productService,- ISlugService slugService,- ITranslationService translationService,- ILanguageService languageService,- IWorkContext workContext,- SeoSettings seoSettings)- {- _productService = productService;- _slugService = slugService;- _translationService = translationService;- _languageService = languageService;- _workContext = workContext;- _seoSettings = seoSettings;- }+ public AddProductCommandHandler(+ IProductService productService,+ ISlugService slugService,+ ITranslationService translationService,+ ILanguageService languageService,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _productService = productService;+ _slugService = slugService;+ _translationService = translationService;+ _languageService = languageService;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }- public async Task<ProductDto> Handle(AddProductCommand request, CancellationToken cancellationToken)- {- var product = request.Model.ToEntity();- await _productService.InsertProduct(product);+ public async Task<ProductDto> Handle(AddProductCommand request, CancellationToken cancellationToken)+ {+ var product = request.Model.ToEntity();+ await _productService.InsertProduct(product);- request.Model.SeName = await product.ValidateSeName(request.Model.SeName, product.Name, true, _seoSettings, _slugService, _languageService);- product.SeName = request.Model.SeName;- //search engine name- await _slugService.SaveSlug(product, request.Model.SeName, "");- await _productService.UpdateProduct(product);+ request.Model.SeName = await product.ValidateSeName(request.Model.SeName, product.Name, true, _seoSettings,+ _slugService, _languageService);+ product.SeName = request.Model.SeName;+ //search engine name+ await _slugService.SaveSlug(product, request.Model.SeName, "");+ await _productService.UpdateProduct(product);- return product.ToModel();- }+ return product.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductPictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductPictureCommandHandler.csindex ce48d061d..5c7d2cf6c 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductPictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductPictureCommandHandler.cs@@ -4,37 +4,36 @@ using Grand.Business.Core.Interfaces.Storage;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductPictureCommandHandler : IRequestHandler<AddProductPictureCommand, bool>{- public class AddProductPictureCommandHandler : IRequestHandler<AddProductPictureCommand, bool>- {- private readonly IProductService _productService;- private readonly IPictureService _pictureService;+ private readonly IPictureService _pictureService;+ private readonly IProductService _productService;- public AddProductPictureCommandHandler(- IProductService productService,- IPictureService pictureService)- {- _productService = productService;- _pictureService = pictureService;- }+ public AddProductPictureCommandHandler(+ IProductService productService,+ IPictureService pictureService)+ {+ _productService = productService;+ _pictureService = pictureService;+ }- public async Task<bool> Handle(AddProductPictureCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id);- if (product == null)- return false;+ public async Task<bool> Handle(AddProductPictureCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id);+ if (product == null)+ return false;- var picture = await _pictureService.GetPictureById(request.Model.PictureId);- if (picture == null)- return false;+ var picture = await _pictureService.GetPictureById(request.Model.PictureId);+ if (picture == null)+ return false;- await _productService.InsertProductPicture(new ProductPicture {- PictureId = picture.Id,- DisplayOrder = request.Model.DisplayOrder- }, product.Id);+ await _productService.InsertProductPicture(new ProductPicture {+ PictureId = picture.Id,+ DisplayOrder = request.Model.DisplayOrder+ }, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.csindex f489daf98..a1b96ce87 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs@@ -3,40 +3,38 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductSpecificationCommandHandler : IRequestHandler<AddProductSpecificationCommand, bool>{- public class AddProductSpecificationCommandHandler : IRequestHandler<AddProductSpecificationCommand, bool>+ private readonly ISpecificationAttributeService _specificationAttributeService;++ public AddProductSpecificationCommandHandler(ISpecificationAttributeService specificationAttributeService){- private readonly ISpecificationAttributeService _specificationAttributeService;+ _specificationAttributeService = specificationAttributeService;+ }- public AddProductSpecificationCommandHandler(ISpecificationAttributeService specificationAttributeService)+ public async Task<bool> Handle(AddProductSpecificationCommand request, CancellationToken cancellationToken)+ {+ //we allow filtering only for "Option" attribute type+ if (request.Model.AttributeTypeId != SpecificationAttributeType.Option){- _specificationAttributeService = specificationAttributeService;+ request.Model.AllowFiltering = false;+ request.Model.SpecificationAttributeOptionId = null;}- public async Task<bool> Handle(AddProductSpecificationCommand request, CancellationToken cancellationToken)- {- //we allow filtering only for "Option" attribute type- if (request.Model.AttributeTypeId != SpecificationAttributeType.Option)- {- request.Model.AllowFiltering = false;- request.Model.SpecificationAttributeOptionId = null;- }-- var psa = new ProductSpecificationAttribute- {- AttributeTypeId = request.Model.AttributeTypeId,- SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId,- SpecificationAttributeId = request.Model.SpecificationAttributeId,- CustomName = request.Model.CustomName,- CustomValue = request.Model.CustomValue,- AllowFiltering = request.Model.AllowFiltering,- ShowOnProductPage = request.Model.ShowOnProductPage,- DisplayOrder = request.Model.DisplayOrder- };- await _specificationAttributeService.InsertProductSpecificationAttribute(psa, request.Product.Id);+ var psa = new ProductSpecificationAttribute {+ AttributeTypeId = request.Model.AttributeTypeId,+ SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId,+ SpecificationAttributeId = request.Model.SpecificationAttributeId,+ CustomName = request.Model.CustomName,+ CustomValue = request.Model.CustomValue,+ AllowFiltering = request.Model.AllowFiltering,+ ShowOnProductPage = request.Model.ShowOnProductPage,+ DisplayOrder = request.Model.DisplayOrder+ };+ await _specificationAttributeService.InsertProductSpecificationAttribute(psa, request.Product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.csindex 4c0d0d9f0..3c5da8ebb 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs@@ -3,23 +3,22 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class AddProductTierPriceCommandHandler : IRequestHandler<AddProductTierPriceCommand, bool>{- public class AddProductTierPriceCommandHandler : IRequestHandler<AddProductTierPriceCommand, bool>- {- private readonly IProductService _productService;+ private readonly IProductService _productService;- public AddProductTierPriceCommandHandler(IProductService productService)- {- _productService = productService;- }+ public AddProductTierPriceCommandHandler(IProductService productService)+ {+ _productService = productService;+ }- public async Task<bool> Handle(AddProductTierPriceCommand request, CancellationToken cancellationToken)- {- var tierPrice = request.Model.ToEntity();- await _productService.InsertTierPrice(tierPrice, request.Product.Id);+ public async Task<bool> Handle(AddProductTierPriceCommand request, CancellationToken cancellationToken)+ {+ var tierPrice = request.Model.ToEntity();+ await _productService.InsertTierPrice(tierPrice, request.Product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.csindex f50ccfb6d..f10a24d97 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs@@ -6,30 +6,32 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class+ AddSpecificationAttributeCommandHandler : IRequestHandler<AddSpecificationAttributeCommand,+ SpecificationAttributeDto>{- public class AddSpecificationAttributeCommandHandler : IRequestHandler<AddSpecificationAttributeCommand, SpecificationAttributeDto>- {- private readonly ISpecificationAttributeService _specificationAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly ISpecificationAttributeService _specificationAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public AddSpecificationAttributeCommandHandler(- ISpecificationAttributeService specificationAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _specificationAttributeService = specificationAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public AddSpecificationAttributeCommandHandler(+ ISpecificationAttributeService specificationAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _specificationAttributeService = specificationAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<SpecificationAttributeDto> Handle(AddSpecificationAttributeCommand request, CancellationToken cancellationToken)- {- var specificationAttribute = request.Model.ToEntity();- await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);+ public async Task<SpecificationAttributeDto> Handle(AddSpecificationAttributeCommand request,+ CancellationToken cancellationToken)+ {+ var specificationAttribute = request.Model.ToEntity();+ await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);- return specificationAttribute.ToModel();- }+ return specificationAttribute.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.csindex 3dfc4e558..26ff293db 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand, bool>{- public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand, bool>- {- private readonly IBrandService _brandService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IBrandService _brandService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteBrandCommandHandler(- IBrandService brandService,- ITranslationService translationService,- IWorkContext workContext)- {- _brandService = brandService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteBrandCommandHandler(+ IBrandService brandService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _brandService = brandService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)- {- var brand = await _brandService.GetBrandById(request.Model.Id);- if (brand != null)- {- await _brandService.DeleteBrand(brand);- }- return true;- }+ public async Task<bool> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)+ {+ var brand = await _brandService.GetBrandById(request.Model.Id);+ if (brand != null) await _brandService.DeleteBrand(brand);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.csindex 51b1c8511..295caca09 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteCategoryCommandHandler : IRequestHandler<DeleteCategoryCommand, bool>{- public class DeleteCategoryCommandHandler : IRequestHandler<DeleteCategoryCommand, bool>- {- private readonly ICategoryService _categoryService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly ICategoryService _categoryService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteCategoryCommandHandler(- ICategoryService categoryService,- ITranslationService translationService,- IWorkContext workContext)- {- _categoryService = categoryService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteCategoryCommandHandler(+ ICategoryService categoryService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _categoryService = categoryService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteCategoryCommand request, CancellationToken cancellationToken)- {- var category = await _categoryService.GetCategoryById(request.Model.Id);- if (category != null)- {- await _categoryService.DeleteCategory(category);- }- return true;- }+ public async Task<bool> Handle(DeleteCategoryCommand request, CancellationToken cancellationToken)+ {+ var category = await _categoryService.GetCategoryById(request.Model.Id);+ if (category != null) await _categoryService.DeleteCategory(category);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.csindex a0ff756a5..622738863 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteCollectionCommandHandler : IRequestHandler<DeleteCollectionCommand, bool>{- public class DeleteCollectionCommandHandler : IRequestHandler<DeleteCollectionCommand, bool>- {- private readonly ICollectionService _collectionService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly ICollectionService _collectionService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteCollectionCommandHandler(- ICollectionService collectionService,- ITranslationService translationService,- IWorkContext workContext)- {- _collectionService = collectionService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteCollectionCommandHandler(+ ICollectionService collectionService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _collectionService = collectionService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteCollectionCommand request, CancellationToken cancellationToken)- {- var collection = await _collectionService.GetCollectionById(request.Model.Id);- if (collection != null)- {- await _collectionService.DeleteCollection(collection);- }- return true;- }+ public async Task<bool> Handle(DeleteCollectionCommand request, CancellationToken cancellationToken)+ {+ var collection = await _collectionService.GetCollectionById(request.Model.Id);+ if (collection != null) await _collectionService.DeleteCollection(collection);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.csindex 66ce48931..3d7c483d7 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductAttributeCommandHandler : IRequestHandler<DeleteProductAttributeCommand, bool>{- public class DeleteProductAttributeCommandHandler : IRequestHandler<DeleteProductAttributeCommand, bool>- {- private readonly IProductAttributeService _productAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IProductAttributeService _productAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteProductAttributeCommandHandler(- IProductAttributeService productAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _productAttributeService = productAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteProductAttributeCommandHandler(+ IProductAttributeService productAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _productAttributeService = productAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteProductAttributeCommand request, CancellationToken cancellationToken)- {- var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id);- if (productAttribute != null)- {- await _productAttributeService.DeleteProductAttribute(productAttribute);- }- return true;- }+ public async Task<bool> Handle(DeleteProductAttributeCommand request, CancellationToken cancellationToken)+ {+ var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id);+ if (productAttribute != null) await _productAttributeService.DeleteProductAttribute(productAttribute);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.csindex fcad83e51..912b4c2c0 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs@@ -3,24 +3,23 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductAttributeMappingCommandHandler : IRequestHandler<DeleteProductAttributeMappingCommand, bool>{- public class DeleteProductAttributeMappingCommandHandler : IRequestHandler<DeleteProductAttributeMappingCommand, bool>- {- private readonly IProductAttributeService _productAttributeService;+ private readonly IProductAttributeService _productAttributeService;- public DeleteProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)- {- _productAttributeService = productAttributeService;- }+ public DeleteProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)+ {+ _productAttributeService = productAttributeService;+ }- public async Task<bool> Handle(DeleteProductAttributeMappingCommand request, CancellationToken cancellationToken)- {- //insert mapping- var productAttributeMapping = request.Model.ToEntity();- await _productAttributeService.DeleteProductAttributeMapping(productAttributeMapping, request.Product.Id);+ public async Task<bool> Handle(DeleteProductAttributeMappingCommand request, CancellationToken cancellationToken)+ {+ //insert mapping+ var productAttributeMapping = request.Model.ToEntity();+ await _productAttributeService.DeleteProductAttributeMapping(productAttributeMapping, request.Product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.csindex 971e3c705..b9e2df402 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs@@ -3,31 +3,30 @@ using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductCategoryCommandHandler : IRequestHandler<DeleteProductCategoryCommand, bool>{- public class DeleteProductCategoryCommandHandler : IRequestHandler<DeleteProductCategoryCommand, bool>- {- private readonly IProductCategoryService _productcategoryService;- private readonly IProductService _productService;+ private readonly IProductCategoryService _productcategoryService;+ private readonly IProductService _productService;- public DeleteProductCategoryCommandHandler(- IProductCategoryService productcategoryService,- IProductService productService)- {- _productcategoryService = productcategoryService;- _productService = productService;- }+ public DeleteProductCategoryCommandHandler(+ IProductCategoryService productcategoryService,+ IProductService productService)+ {+ _productcategoryService = productcategoryService;+ _productService = productService;+ }- public async Task<bool> Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.CategoryId);- if (productCategory == null)- throw new ArgumentException("No product category mapping found with the specified id");+ public async Task<bool> Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.CategoryId);+ if (productCategory == null)+ throw new ArgumentException("No product category mapping found with the specified id");- await _productcategoryService.DeleteProductCategory(productCategory, product.Id);+ await _productcategoryService.DeleteProductCategory(productCategory, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.csindex 1e1e3d455..831814afe 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs@@ -3,29 +3,29 @@ using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductCollectionCommandHandler : IRequestHandler<DeleteProductCollectionCommand, bool>{- public class DeleteProductCollectionCommandHandler : IRequestHandler<DeleteProductCollectionCommand, bool>- {- private readonly IProductCollectionService _productcollectionService;- private readonly IProductService _productService;+ private readonly IProductCollectionService _productcollectionService;+ private readonly IProductService _productService;- public DeleteProductCollectionCommandHandler(IProductCollectionService productcollectionService, IProductService productService)- {- _productcollectionService = productcollectionService;- _productService = productService;- }+ public DeleteProductCollectionCommandHandler(IProductCollectionService productcollectionService,+ IProductService productService)+ {+ _productcollectionService = productcollectionService;+ _productService = productService;+ }- public async Task<bool> Handle(DeleteProductCollectionCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var productCollection = product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.CollectionId);- if (productCollection == null)- throw new ArgumentException("No product collection mapping found with the specified id");+ public async Task<bool> Handle(DeleteProductCollectionCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var productCollection = product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.CollectionId);+ if (productCollection == null)+ throw new ArgumentException("No product collection mapping found with the specified id");- await _productcollectionService.DeleteProductCollection(productCollection, product.Id);+ await _productcollectionService.DeleteProductCollection(productCollection, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.csindex 81aeef821..1b6ea65fb 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand, bool>{- public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand, bool>- {- private readonly IProductService _productService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IProductService _productService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteProductCommandHandler(- IProductService productService,- ITranslationService translationService,- IWorkContext workContext)- {- _productService = productService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteProductCommandHandler(+ IProductService productService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _productService = productService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Model.Id);- if (product != null)- {- await _productService.DeleteProduct(product);- }- return true;- }+ public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Model.Id);+ if (product != null) await _productService.DeleteProduct(product);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.csindex b2376dc46..09d5c2200 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs@@ -2,29 +2,28 @@using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductPictureCommandHandler : IRequestHandler<DeleteProductPictureCommand, bool>{- public class DeleteProductPictureCommandHandler : IRequestHandler<DeleteProductPictureCommand, bool>- {- private readonly IProductService _productService;+ private readonly IProductService _productService;- public DeleteProductPictureCommandHandler(- IProductService productService)- {- _productService = productService;- }+ public DeleteProductPictureCommandHandler(+ IProductService productService)+ {+ _productService = productService;+ }- public async Task<bool> Handle(DeleteProductPictureCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id);+ public async Task<bool> Handle(DeleteProductPictureCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id);- var productPicture = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.PictureId);- if (productPicture == null)- throw new ArgumentException("No product picture found with the specified pictureid");+ var productPicture = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.PictureId);+ if (productPicture == null)+ throw new ArgumentException("No product picture found with the specified pictureid");- await _productService.DeleteProductPicture(productPicture, product.Id);+ await _productService.DeleteProductPicture(productPicture, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.csindex 72e5a601c..71066ce64 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs@@ -2,30 +2,26 @@using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductSpecificationCommandHandler : IRequestHandler<DeleteProductSpecificationCommand, bool>{- public class DeleteProductSpecificationCommandHandler : IRequestHandler<DeleteProductSpecificationCommand, bool>- {- private readonly ISpecificationAttributeService _specificationAttributeService;- private readonly IProductService _productService;+ private readonly IProductService _productService;+ private readonly ISpecificationAttributeService _specificationAttributeService;- public DeleteProductSpecificationCommandHandler(ISpecificationAttributeService specificationAttributeService,- IProductService productService)- {- _specificationAttributeService = specificationAttributeService;- _productService = productService;- }+ public DeleteProductSpecificationCommandHandler(ISpecificationAttributeService specificationAttributeService,+ IProductService productService)+ {+ _specificationAttributeService = specificationAttributeService;+ _productService = productService;+ }- public async Task<bool> Handle(DeleteProductSpecificationCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Id);- if (psa != null)- {- await _specificationAttributeService.DeleteProductSpecificationAttribute(psa, product.Id);- }+ public async Task<bool> Handle(DeleteProductSpecificationCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Id);+ if (psa != null) await _specificationAttributeService.DeleteProductSpecificationAttribute(psa, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.csindex 005a99617..3b596f8e4 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs@@ -2,25 +2,24 @@using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteProductTierPriceCommandHandler : IRequestHandler<DeleteProductTierPriceCommand, bool>{- public class DeleteProductTierPriceCommandHandler : IRequestHandler<DeleteProductTierPriceCommand, bool>- {- private readonly IProductService _productService;+ private readonly IProductService _productService;- public DeleteProductTierPriceCommandHandler(IProductService productService)- {- _productService = productService;- }+ public DeleteProductTierPriceCommandHandler(IProductService productService)+ {+ _productService = productService;+ }- public async Task<bool> Handle(DeleteProductTierPriceCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var tierPrice = product.TierPrices.FirstOrDefault(x => x.Id == request.Id);+ public async Task<bool> Handle(DeleteProductTierPriceCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var tierPrice = product.TierPrices.FirstOrDefault(x => x.Id == request.Id);- await _productService.DeleteTierPrice(tierPrice, product.Id);+ await _productService.DeleteTierPrice(tierPrice, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.csindex 548be3d76..95bc422bd 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs@@ -4,32 +4,30 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class DeleteSpecificationAttributeCommandHandler : IRequestHandler<DeleteSpecificationAttributeCommand, bool>{- public class DeleteSpecificationAttributeCommandHandler : IRequestHandler<DeleteSpecificationAttributeCommand, bool>- {- private readonly ISpecificationAttributeService _specificationAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly ISpecificationAttributeService _specificationAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteSpecificationAttributeCommandHandler(- ISpecificationAttributeService specificationAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _specificationAttributeService = specificationAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteSpecificationAttributeCommandHandler(+ ISpecificationAttributeService specificationAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _specificationAttributeService = specificationAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteSpecificationAttributeCommand request, CancellationToken cancellationToken)- {- var specificationAttribute = await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id);- if (specificationAttribute != null)- {- await _specificationAttributeService.DeleteSpecificationAttribute(specificationAttribute);- }- return true;- }+ public async Task<bool> Handle(DeleteSpecificationAttributeCommand request, CancellationToken cancellationToken)+ {+ var specificationAttribute =+ await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id);+ if (specificationAttribute != null)+ await _specificationAttributeService.DeleteSpecificationAttribute(specificationAttribute);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.csindex e6a0fb1c5..7c2278082 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs@@ -10,63 +10,65 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateBrandCommandHandler : IRequestHandler<UpdateBrandCommand, BrandDto>{- public class UpdateBrandCommandHandler : IRequestHandler<UpdateBrandCommand, BrandDto>- {- private readonly IBrandService _brandService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly ITranslationService _translationService;- private readonly IPictureService _pictureService;- private readonly IWorkContext _workContext;+ private readonly IBrandService _brandService;+ private readonly ILanguageService _languageService;+ private readonly IPictureService _pictureService;- private readonly SeoSettings _seoSettings;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateBrandCommandHandler(- IBrandService brandService,- ISlugService slugService,- ILanguageService languageService,- ITranslationService translationService,- IPictureService pictureService,- IWorkContext workContext,- SeoSettings seoSettings)+ public UpdateBrandCommandHandler(+ IBrandService brandService,+ ISlugService slugService,+ ILanguageService languageService,+ ITranslationService translationService,+ IPictureService pictureService,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _brandService = brandService;+ _slugService = slugService;+ _languageService = languageService;+ _translationService = translationService;+ _pictureService = pictureService;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }++ public async Task<BrandDto> Handle(UpdateBrandCommand request, CancellationToken cancellationToken)+ {+ var brand = await _brandService.GetBrandById(request.Model.Id);+ var prevPictureId = brand.PictureId;+ brand = request.Model.ToEntity(brand);+ request.Model.SeName = await brand.ValidateSeName(request.Model.SeName, brand.Name, true, _seoSettings,+ _slugService, _languageService);+ brand.SeName = request.Model.SeName;+ await _brandService.UpdateBrand(brand);+ //search engine name+ await _slugService.SaveSlug(brand, request.Model.SeName, "");+ await _brandService.UpdateBrand(brand);+ //delete an old picture (if deleted or updated)+ if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != brand.PictureId){- _brandService = brandService;- _slugService = slugService;- _languageService = languageService;- _translationService = translationService;- _pictureService = pictureService;- _workContext = workContext;- _seoSettings = seoSettings;+ var prevPicture = await _pictureService.GetPictureById(prevPictureId);+ if (prevPicture != null)+ await _pictureService.DeletePicture(prevPicture);}- public async Task<BrandDto> Handle(UpdateBrandCommand request, CancellationToken cancellationToken)+ //update picture seo file name+ if (!string.IsNullOrEmpty(brand.PictureId)){- var brand = await _brandService.GetBrandById(request.Model.Id);- var prevPictureId = brand.PictureId;- brand = request.Model.ToEntity(brand);- request.Model.SeName = await brand.ValidateSeName(request.Model.SeName, brand.Name, true, _seoSettings, _slugService, _languageService);- brand.SeName = request.Model.SeName;- await _brandService.UpdateBrand(brand);- //search engine name- await _slugService.SaveSlug(brand, request.Model.SeName, "");- await _brandService.UpdateBrand(brand);- //delete an old picture (if deleted or updated)- if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != brand.PictureId)- {- var prevPicture = await _pictureService.GetPictureById(prevPictureId);- if (prevPicture != null)- await _pictureService.DeletePicture(prevPicture);- }- //update picture seo file name- if (!string.IsNullOrEmpty(brand.PictureId))- {- var picture = await _pictureService.GetPictureById(brand.PictureId);- if (picture != null)- await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(brand.Name));- }- return brand.ToModel();+ var picture = await _pictureService.GetPictureById(brand.PictureId);+ if (picture != null)+ await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(brand.Name));}++ return brand.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.csindex 33d122e33..af4df615c 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs@@ -10,63 +10,65 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateCategoryCommandHandler : IRequestHandler<UpdateCategoryCommand, CategoryDto>{- public class UpdateCategoryCommandHandler : IRequestHandler<UpdateCategoryCommand, CategoryDto>- {- private readonly ICategoryService _categoryService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly ITranslationService _translationService;- private readonly IPictureService _pictureService;- private readonly IWorkContext _workContext;+ private readonly ICategoryService _categoryService;+ private readonly ILanguageService _languageService;+ private readonly IPictureService _pictureService;- private readonly SeoSettings _seoSettings;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateCategoryCommandHandler(- ICategoryService categoryService,- ISlugService slugService,- ILanguageService languageService,- ITranslationService translationService,- IPictureService pictureService,- IWorkContext workContext,- SeoSettings seoSettings)+ public UpdateCategoryCommandHandler(+ ICategoryService categoryService,+ ISlugService slugService,+ ILanguageService languageService,+ ITranslationService translationService,+ IPictureService pictureService,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _categoryService = categoryService;+ _slugService = slugService;+ _languageService = languageService;+ _translationService = translationService;+ _pictureService = pictureService;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }++ public async Task<CategoryDto> Handle(UpdateCategoryCommand request, CancellationToken cancellationToken)+ {+ var category = await _categoryService.GetCategoryById(request.Model.Id);+ var prevPictureId = category.PictureId;+ category = request.Model.ToEntity(category);+ request.Model.SeName = await category.ValidateSeName(request.Model.SeName, category.Name, true, _seoSettings,+ _slugService, _languageService);+ category.SeName = request.Model.SeName;+ await _categoryService.UpdateCategory(category);+ //search engine name+ await _slugService.SaveSlug(category, request.Model.SeName, "");+ await _categoryService.UpdateCategory(category);+ //delete an old picture (if deleted or updated)+ if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != category.PictureId){- _categoryService = categoryService;- _slugService = slugService;- _languageService = languageService;- _translationService = translationService;- _pictureService = pictureService;- _workContext = workContext;- _seoSettings = seoSettings;+ var prevPicture = await _pictureService.GetPictureById(prevPictureId);+ if (prevPicture != null)+ await _pictureService.DeletePicture(prevPicture);}- public async Task<CategoryDto> Handle(UpdateCategoryCommand request, CancellationToken cancellationToken)+ //update picture seo file name+ if (!string.IsNullOrEmpty(category.PictureId)){- var category = await _categoryService.GetCategoryById(request.Model.Id);- var prevPictureId = category.PictureId;- category = request.Model.ToEntity(category);- request.Model.SeName = await category.ValidateSeName(request.Model.SeName, category.Name, true, _seoSettings, _slugService, _languageService);- category.SeName = request.Model.SeName;- await _categoryService.UpdateCategory(category);- //search engine name- await _slugService.SaveSlug(category, request.Model.SeName, "");- await _categoryService.UpdateCategory(category);- //delete an old picture (if deleted or updated)- if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != category.PictureId)- {- var prevPicture = await _pictureService.GetPictureById(prevPictureId);- if (prevPicture != null)- await _pictureService.DeletePicture(prevPicture);- }- //update picture seo file name- if (!string.IsNullOrEmpty(category.PictureId))- {- var picture = await _pictureService.GetPictureById(category.PictureId);- if (picture != null)- await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(category.Name));- }- return category.ToModel();+ var picture = await _pictureService.GetPictureById(category.PictureId);+ if (picture != null)+ await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(category.Name));}++ return category.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.csindex 2bf451444..5f10cc235 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs@@ -10,63 +10,65 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateCollectionCommandHandler : IRequestHandler<UpdateCollectionCommand, CollectionDto>{- public class UpdateCollectionCommandHandler : IRequestHandler<UpdateCollectionCommand, CollectionDto>- {- private readonly ICollectionService _collectionService;- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly ITranslationService _translationService;- private readonly IPictureService _pictureService;- private readonly IWorkContext _workContext;+ private readonly ICollectionService _collectionService;+ private readonly ILanguageService _languageService;+ private readonly IPictureService _pictureService;- private readonly SeoSettings _seoSettings;+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateCollectionCommandHandler(- ICollectionService collectionService,- ISlugService slugService,- ILanguageService languageService,- ITranslationService translationService,- IPictureService pictureService,- IWorkContext workContext,- SeoSettings seoSettings)+ public UpdateCollectionCommandHandler(+ ICollectionService collectionService,+ ISlugService slugService,+ ILanguageService languageService,+ ITranslationService translationService,+ IPictureService pictureService,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _collectionService = collectionService;+ _slugService = slugService;+ _languageService = languageService;+ _translationService = translationService;+ _pictureService = pictureService;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }++ public async Task<CollectionDto> Handle(UpdateCollectionCommand request, CancellationToken cancellationToken)+ {+ var collection = await _collectionService.GetCollectionById(request.Model.Id);+ var prevPictureId = collection.PictureId;+ collection = request.Model.ToEntity(collection);+ request.Model.SeName = await collection.ValidateSeName(request.Model.SeName, collection.Name, true,+ _seoSettings, _slugService, _languageService);+ collection.SeName = request.Model.SeName;+ await _collectionService.UpdateCollection(collection);+ //search engine name+ await _slugService.SaveSlug(collection, request.Model.SeName, "");+ await _collectionService.UpdateCollection(collection);+ //delete an old picture (if deleted or updated)+ if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != collection.PictureId){- _collectionService = collectionService;- _slugService = slugService;- _languageService = languageService;- _translationService = translationService;- _pictureService = pictureService;- _workContext = workContext;- _seoSettings = seoSettings;+ var prevPicture = await _pictureService.GetPictureById(prevPictureId);+ if (prevPicture != null)+ await _pictureService.DeletePicture(prevPicture);}- public async Task<CollectionDto> Handle(UpdateCollectionCommand request, CancellationToken cancellationToken)+ //update picture seo file name+ if (!string.IsNullOrEmpty(collection.PictureId)){- var collection = await _collectionService.GetCollectionById(request.Model.Id);- var prevPictureId = collection.PictureId;- collection = request.Model.ToEntity(collection);- request.Model.SeName = await collection.ValidateSeName(request.Model.SeName, collection.Name, true, _seoSettings, _slugService, _languageService);- collection.SeName = request.Model.SeName;- await _collectionService.UpdateCollection(collection);- //search engine name- await _slugService.SaveSlug(collection, request.Model.SeName, "");- await _collectionService.UpdateCollection(collection);- //delete an old picture (if deleted or updated)- if (!string.IsNullOrEmpty(prevPictureId) && prevPictureId != collection.PictureId)- {- var prevPicture = await _pictureService.GetPictureById(prevPictureId);- if (prevPicture != null)- await _pictureService.DeletePicture(prevPicture);- }- //update picture seo file name- if (!string.IsNullOrEmpty(collection.PictureId))- {- var picture = await _pictureService.GetPictureById(collection.PictureId);- if (picture != null)- await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(collection.Name));- }- return collection.ToModel();+ var picture = await _pictureService.GetPictureById(collection.PictureId);+ if (picture != null)+ await _pictureService.SetSeoFilename(picture, _pictureService.GetPictureSeName(collection.Name));}++ return collection.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.csindex 07510c0ab..5b84d4fff 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs@@ -6,32 +6,32 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductAttributeCommandHandler : IRequestHandler<UpdateProductAttributeCommand, ProductAttributeDto>{- public class UpdateProductAttributeCommandHandler : IRequestHandler<UpdateProductAttributeCommand, ProductAttributeDto>- {- private readonly IProductAttributeService _productAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IProductAttributeService _productAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateProductAttributeCommandHandler(- IProductAttributeService productAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _productAttributeService = productAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public UpdateProductAttributeCommandHandler(+ IProductAttributeService productAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _productAttributeService = productAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<ProductAttributeDto> Handle(UpdateProductAttributeCommand request, CancellationToken cancellationToken)- {- var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id);+ public async Task<ProductAttributeDto> Handle(UpdateProductAttributeCommand request,+ CancellationToken cancellationToken)+ {+ var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id);- productAttribute = request.Model.ToEntity(productAttribute);- await _productAttributeService.UpdateProductAttribute(productAttribute);+ productAttribute = request.Model.ToEntity(productAttribute);+ await _productAttributeService.UpdateProductAttribute(productAttribute);- return productAttribute.ToModel();- }+ return productAttribute.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.csindex 58365fb9b..cc290997c 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs@@ -4,24 +4,26 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class+ UpdateProductAttributeMappingCommandHandler : IRequestHandler<UpdateProductAttributeMappingCommand,+ ProductAttributeMappingDto>{- public class UpdateProductAttributeMappingCommandHandler : IRequestHandler<UpdateProductAttributeMappingCommand, ProductAttributeMappingDto>- {- private readonly IProductAttributeService _productAttributeService;+ private readonly IProductAttributeService _productAttributeService;- public UpdateProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)- {- _productAttributeService = productAttributeService;- }+ public UpdateProductAttributeMappingCommandHandler(IProductAttributeService productAttributeService)+ {+ _productAttributeService = productAttributeService;+ }- public async Task<ProductAttributeMappingDto> Handle(UpdateProductAttributeMappingCommand request, CancellationToken cancellationToken)- {- //insert mapping- var productAttributeMapping = request.Model.ToEntity();- await _productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, request.Product.Id, true);+ public async Task<ProductAttributeMappingDto> Handle(UpdateProductAttributeMappingCommand request,+ CancellationToken cancellationToken)+ {+ //insert mapping+ var productAttributeMapping = request.Model.ToEntity();+ await _productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, request.Product.Id, true);- return productAttributeMapping.ToModel();- }+ return productAttributeMapping.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.csindex f7bd2c12e..bd66fac22 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs@@ -3,34 +3,33 @@ using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductCategoryCommandHandler : IRequestHandler<UpdateProductCategoryCommand, bool>{- public class UpdateProductCategoryCommandHandler : IRequestHandler<UpdateProductCategoryCommand, bool>- {- private readonly IProductCategoryService _productCategoryService;- private readonly IProductService _productService;+ private readonly IProductCategoryService _productCategoryService;+ private readonly IProductService _productService;- public UpdateProductCategoryCommandHandler(- IProductCategoryService productCategoryService,- IProductService productService)- {- _productCategoryService = productCategoryService;- _productService = productService;- }+ public UpdateProductCategoryCommandHandler(+ IProductCategoryService productCategoryService,+ IProductService productService)+ {+ _productCategoryService = productCategoryService;+ _productService = productService;+ }- public async Task<bool> Handle(UpdateProductCategoryCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.Model.CategoryId);- if (productCategory == null)- throw new ArgumentException("No product category mapping found with the specified id");+ public async Task<bool> Handle(UpdateProductCategoryCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.Model.CategoryId);+ if (productCategory == null)+ throw new ArgumentException("No product category mapping found with the specified id");- productCategory.CategoryId = request.Model.CategoryId;- productCategory.IsFeaturedProduct = request.Model.IsFeaturedProduct;+ productCategory.CategoryId = request.Model.CategoryId;+ productCategory.IsFeaturedProduct = request.Model.IsFeaturedProduct;- await _productCategoryService.UpdateProductCategory(productCategory, product.Id);+ await _productCategoryService.UpdateProductCategory(productCategory, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.csindex 39809037d..6de3cc425 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs@@ -3,32 +3,33 @@ using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductCollectionCommandHandler : IRequestHandler<UpdateProductCollectionCommand, bool>{- public class UpdateProductCollectionCommandHandler : IRequestHandler<UpdateProductCollectionCommand, bool>- {- private readonly IProductCollectionService _productCollectionService;- private readonly IProductService _productService;+ private readonly IProductCollectionService _productCollectionService;+ private readonly IProductService _productService;- public UpdateProductCollectionCommandHandler(IProductCollectionService productCollectionService, IProductService productService)- {- _productCollectionService = productCollectionService;- _productService = productService;- }+ public UpdateProductCollectionCommandHandler(IProductCollectionService productCollectionService,+ IProductService productService)+ {+ _productCollectionService = productCollectionService;+ _productService = productService;+ }- public async Task<bool> Handle(UpdateProductCollectionCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var productCollection = product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.Model.CollectionId);- if (productCollection == null)- throw new ArgumentException("No product collection mapping found with the specified id");+ public async Task<bool> Handle(UpdateProductCollectionCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var productCollection =+ product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.Model.CollectionId);+ if (productCollection == null)+ throw new ArgumentException("No product collection mapping found with the specified id");- productCollection.CollectionId = request.Model.CollectionId;- productCollection.IsFeaturedProduct = request.Model.IsFeaturedProduct;+ productCollection.CollectionId = request.Model.CollectionId;+ productCollection.IsFeaturedProduct = request.Model.IsFeaturedProduct;- await _productCollectionService.UpdateProductCollection(productCollection, product.Id);+ await _productCollectionService.UpdateProductCollection(productCollection, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.csindex 9d229ad85..f5e600cf7 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs@@ -11,79 +11,77 @@ using Grand.Domain.Seo;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog-{- public class UpdateProductCommandHandler : IRequestHandler<UpdateProductCommand, ProductDto>- {- private readonly IProductService _productService;- private readonly IStockQuantityService _stockQuantityService;- private readonly ISlugService _slugService;- private readonly ITranslationService _translationService;- private readonly ILanguageService _languageService;- private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;- private readonly IMediator _mediator;- private readonly IWorkContext _workContext;+namespace Grand.Api.Commands.Handlers.Catalog;- private readonly SeoSettings _seoSettings;+public class UpdateProductCommandHandler : IRequestHandler<UpdateProductCommand, ProductDto>+{+ private readonly ILanguageService _languageService;+ private readonly IMediator _mediator;+ private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;+ private readonly IProductService _productService;- public UpdateProductCommandHandler(- IProductService productService,- ISlugService slugService,- ITranslationService translationService,- ILanguageService languageService,- IOutOfStockSubscriptionService outOfStockSubscriptionService,- IStockQuantityService stockQuantityService,- IMediator mediator,- IWorkContext workContext,- SeoSettings seoSettings)- {- _productService = productService;- _slugService = slugService;- _translationService = translationService;- _languageService = languageService;- _outOfStockSubscriptionService = outOfStockSubscriptionService;- _stockQuantityService = stockQuantityService;- _mediator = mediator;- _workContext = workContext;- _seoSettings = seoSettings;- }+ private readonly SeoSettings _seoSettings;+ private readonly ISlugService _slugService;+ private readonly IStockQuantityService _stockQuantityService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public async Task<ProductDto> Handle(UpdateProductCommand request, CancellationToken cancellationToken)- {- //product- var product = await _productService.GetProductById(request.Model.Id);- var prevStockQuantity = product.StockQuantity;- var prevPublished = product.Published;+ public UpdateProductCommandHandler(+ IProductService productService,+ ISlugService slugService,+ ITranslationService translationService,+ ILanguageService languageService,+ IOutOfStockSubscriptionService outOfStockSubscriptionService,+ IStockQuantityService stockQuantityService,+ IMediator mediator,+ IWorkContext workContext,+ SeoSettings seoSettings)+ {+ _productService = productService;+ _slugService = slugService;+ _translationService = translationService;+ _languageService = languageService;+ _outOfStockSubscriptionService = outOfStockSubscriptionService;+ _stockQuantityService = stockQuantityService;+ _mediator = mediator;+ _workContext = workContext;+ _seoSettings = seoSettings;+ }- product = request.Model.ToEntity(product);- request.Model.SeName = await product.ValidateSeName(request.Model.SeName, product.Name, true, _seoSettings, _slugService, _languageService);- product.SeName = request.Model.SeName;- //search engine name- await _slugService.SaveSlug(product, request.Model.SeName, "");- //update product- await _productService.UpdateProduct(product);+ public async Task<ProductDto> Handle(UpdateProductCommand request, CancellationToken cancellationToken)+ {+ //product+ var product = await _productService.GetProductById(request.Model.Id);+ var prevStockQuantity = product.StockQuantity;+ var prevPublished = product.Published;- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&- product.BackorderModeId == BackorderMode.NoBackorders &&- product.AllowOutOfStockSubscriptions &&- _stockQuantityService.GetTotalStockQuantity(product) > 0 &&- prevStockQuantity <= 0 && product.Published)- {- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");- }+ product = request.Model.ToEntity(product);+ request.Model.SeName = await product.ValidateSeName(request.Model.SeName, product.Name, true, _seoSettings,+ _slugService, _languageService);+ product.SeName = request.Model.SeName;+ //search engine name+ await _slugService.SaveSlug(product, request.Model.SeName, "");+ //update product+ await _productService.UpdateProduct(product);- switch (prevPublished)- {- //raise event- case false when product.Published:- await _mediator.Publish(new ProductPublishEvent(product), cancellationToken);- break;- case true when !product.Published:- await _mediator.Publish(new ProductUnPublishEvent(product), cancellationToken);- break;- }+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&+ product.BackorderModeId == BackorderMode.NoBackorders &&+ product.AllowOutOfStockSubscriptions &&+ _stockQuantityService.GetTotalStockQuantity(product) > 0 &&+ prevStockQuantity <= 0 && product.Published)+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");- return product.ToModel();+ switch (prevPublished)+ {+ //raise event+ case false when product.Published:+ await _mediator.Publish(new ProductPublishEvent(product), cancellationToken);+ break;+ case true when !product.Published:+ await _mediator.Publish(new ProductUnPublishEvent(product), cancellationToken);+ break;}++ return product.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.csindex b2668c84e..acc715e5f 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs@@ -2,28 +2,28 @@using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductPictureCommandHandler : IRequestHandler<UpdateProductPictureCommand, bool>{- public class UpdateProductPictureCommandHandler : IRequestHandler<UpdateProductPictureCommand, bool>+ private readonly IProductService _productService;++ public UpdateProductPictureCommandHandler(+ IProductService productService){- private readonly IProductService _productService;+ _productService = productService;+ }- public UpdateProductPictureCommandHandler(- IProductService productService)+ public async Task<bool> Handle(UpdateProductPictureCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id);+ var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.Model.PictureId);+ if (pp != null){- _productService = productService;+ pp.DisplayOrder = request.Model.DisplayOrder;+ await _productService.UpdateProductPicture(pp, request.Product.Id);}- public async Task<bool> Handle(UpdateProductPictureCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id);- var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.Model.PictureId);- if (pp != null)- {- pp.DisplayOrder = request.Model.DisplayOrder;- await _productService.UpdateProductPicture(pp, request.Product.Id);- }- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.csindex 5684be009..6eaa725d0 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs@@ -3,46 +3,46 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductSpecificationCommandHandler : IRequestHandler<UpdateProductSpecificationCommand, bool>{- public class UpdateProductSpecificationCommandHandler : IRequestHandler<UpdateProductSpecificationCommand, bool>- {- private readonly ISpecificationAttributeService _specificationAttributeService;- private readonly IProductService _productService;+ private readonly IProductService _productService;+ private readonly ISpecificationAttributeService _specificationAttributeService;- public UpdateProductSpecificationCommandHandler(- ISpecificationAttributeService specificationAttributeService,- IProductService productService)- {- _specificationAttributeService = specificationAttributeService;- _productService = productService;- }+ public UpdateProductSpecificationCommandHandler(+ ISpecificationAttributeService specificationAttributeService,+ IProductService productService)+ {+ _specificationAttributeService = specificationAttributeService;+ _productService = productService;+ }- public async Task<bool> Handle(UpdateProductSpecificationCommand request, CancellationToken cancellationToken)+ public async Task<bool> Handle(UpdateProductSpecificationCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Model.Id);+ if (psa != null){- var product = await _productService.GetProductById(request.Product.Id, true);- var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Model.Id);- if (psa != null)+ if (request.Model.AttributeTypeId == SpecificationAttributeType.Option){- if (request.Model.AttributeTypeId == SpecificationAttributeType.Option)- {- psa.AllowFiltering = request.Model.AllowFiltering;- psa.SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId;- }- else- {- psa.CustomName = request.Model.CustomName;- psa.CustomValue = request.Model.CustomValue;- }- psa.SpecificationAttributeId = request.Model.SpecificationAttributeId;+ psa.AllowFiltering = request.Model.AllowFiltering;psa.SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId;- psa.AttributeTypeId = request.Model.AttributeTypeId;- psa.ShowOnProductPage = request.Model.ShowOnProductPage;- psa.DisplayOrder = request.Model.DisplayOrder;- await _specificationAttributeService.UpdateProductSpecificationAttribute(psa, product.Id);+ }+ else+ {+ psa.CustomName = request.Model.CustomName;+ psa.CustomValue = request.Model.CustomValue;}- return true;+ psa.SpecificationAttributeId = request.Model.SpecificationAttributeId;+ psa.SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId;+ psa.AttributeTypeId = request.Model.AttributeTypeId;+ psa.ShowOnProductPage = request.Model.ShowOnProductPage;+ psa.DisplayOrder = request.Model.DisplayOrder;+ await _specificationAttributeService.UpdateProductSpecificationAttribute(psa, product.Id);}++ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.csindex cf322866d..bdc64a5d8 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs@@ -5,121 +5,117 @@ using Grand.Domain.Catalog;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductStockCommandHandler : IRequestHandler<UpdateProductStockCommand, bool>{- public class UpdateProductStockCommandHandler : IRequestHandler<UpdateProductStockCommand, bool>+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;+ private readonly IProductService _productService;+ private readonly IStockQuantityService _stockQuantityService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;++ public UpdateProductStockCommandHandler(+ IProductService productService,+ IInventoryManageService inventoryManageService,+ IStockQuantityService stockQuantityService,+ ITranslationService translationService,+ IOutOfStockSubscriptionService outOfStockSubscriptionService,+ IWorkContext workContext){- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;- private readonly IStockQuantityService _stockQuantityService;- private readonly ITranslationService _translationService;- private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;- private readonly IWorkContext _workContext;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ _stockQuantityService = stockQuantityService;+ _translationService = translationService;+ _outOfStockSubscriptionService = outOfStockSubscriptionService;+ _workContext = workContext;+ }- public UpdateProductStockCommandHandler(- IProductService productService,- IInventoryManageService inventoryManageService,- IStockQuantityService stockQuantityService,- ITranslationService translationService,- IOutOfStockSubscriptionService outOfStockSubscriptionService,- IWorkContext workContext)+ public async Task<bool> Handle(UpdateProductStockCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id);+ if (product != null){- _productService = productService;- _inventoryManageService = inventoryManageService;- _stockQuantityService = stockQuantityService;- _translationService = translationService;- _outOfStockSubscriptionService = outOfStockSubscriptionService;- _workContext = workContext;- }+ var prevStockQuantity = _stockQuantityService.GetTotalStockQuantity(product);+ var prevMultiWarehouseStock = product.ProductWarehouseInventory.Select(i => new ProductWarehouseInventory {+ WarehouseId = i.WarehouseId, StockQuantity = i.StockQuantity, ReservedQuantity = i.ReservedQuantity+ })+ .ToList();- public async Task<bool> Handle(UpdateProductStockCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id);- if (product != null)+ if (string.IsNullOrEmpty(request.WarehouseId)){- var prevStockQuantity = _stockQuantityService.GetTotalStockQuantity(product);- var prevMultiWarehouseStock = product.ProductWarehouseInventory.Select(i => new ProductWarehouseInventory { WarehouseId = i.WarehouseId, StockQuantity = i.StockQuantity, ReservedQuantity = i.ReservedQuantity }).ToList();-- if (string.IsNullOrEmpty(request.WarehouseId))- {- product.StockQuantity = request.Stock;- await _inventoryManageService.UpdateStockProduct(product, false);- }- else+ product.StockQuantity = request.Stock;+ await _inventoryManageService.UpdateStockProduct(product, false);+ }+ else+ {+ if (product.UseMultipleWarehouses){- if (product.UseMultipleWarehouses)+ var existingPwI =+ product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == request.WarehouseId);+ if (existingPwI != null){- var existingPwI = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == request.WarehouseId);- if (existingPwI != null)- {- existingPwI.StockQuantity = request.Stock;- await _productService.UpdateProductWarehouseInventory(existingPwI, product.Id);- }- else- {- var newPwI = new ProductWarehouseInventory- {- WarehouseId = request.WarehouseId,- StockQuantity = request.Stock,- ReservedQuantity = 0- };- await _productService.InsertProductWarehouseInventory(newPwI, product.Id);- }-- product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);- product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);- await _inventoryManageService.UpdateStockProduct(product, false);+ existingPwI.StockQuantity = request.Stock;+ await _productService.UpdateProductWarehouseInventory(existingPwI, product.Id);}else{- throw new ArgumentException("Product don't support multiple warehouses (warehouseId should be null or empty)");+ var newPwI = new ProductWarehouseInventory {+ WarehouseId = request.WarehouseId,+ StockQuantity = request.Stock,+ ReservedQuantity = 0+ };+ await _productService.InsertProductWarehouseInventory(newPwI, product.Id);}- }- await OutOfStockNotifications(product, prevStockQuantity, prevMultiWarehouseStock);- }- return true;- }- protected async Task OutOfStockNotifications(Product product, int prevStockQuantity, List<ProductWarehouseInventory> prevMultiWarehouseStock)- {- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&- product.BackorderModeId == BackorderMode.NoBackorders &&- product.AllowOutOfStockSubscriptions &&- _stockQuantityService.GetTotalStockQuantity(product) > 0 &&- prevStockQuantity <= 0 && !product.UseMultipleWarehouses &&- product.Published)- {- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");- }- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&- product.BackorderModeId == BackorderMode.NoBackorders &&- product.AllowOutOfStockSubscriptions &&- product.UseMultipleWarehouses &&- product.Published)- {- foreach (var prevstock in prevMultiWarehouseStock)- {- if (prevstock.StockQuantity - prevstock.ReservedQuantity <= 0)- {- var actualStock = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == prevstock.WarehouseId);- if (actualStock != null)- {- if (actualStock.StockQuantity - actualStock.ReservedQuantity > 0)- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, prevstock.WarehouseId);- }- }+ product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);+ product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);+ await _inventoryManageService.UpdateStockProduct(product, false);}- if (product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) > 0)+ else{- if (prevMultiWarehouseStock.Sum(x => x.StockQuantity - x.ReservedQuantity) <= 0)- {- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");- }+ throw new ArgumentException(+ "Product don't support multiple warehouses (warehouseId should be null or empty)");}}++ await OutOfStockNotifications(product, prevStockQuantity, prevMultiWarehouseStock);}+ return true;+ }+ protected async Task OutOfStockNotifications(Product product, int prevStockQuantity,+ List<ProductWarehouseInventory> prevMultiWarehouseStock)+ {+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&+ product.BackorderModeId == BackorderMode.NoBackorders &&+ product.AllowOutOfStockSubscriptions &&+ _stockQuantityService.GetTotalStockQuantity(product) > 0 &&+ prevStockQuantity <= 0 && !product.UseMultipleWarehouses &&+ product.Published)+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock &&+ product.BackorderModeId == BackorderMode.NoBackorders &&+ product.AllowOutOfStockSubscriptions &&+ product.UseMultipleWarehouses &&+ product.Published)+ {+ foreach (var prevstock in prevMultiWarehouseStock)+ if (prevstock.StockQuantity - prevstock.ReservedQuantity <= 0)+ {+ var actualStock =+ product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == prevstock.WarehouseId);+ if (actualStock != null)+ if (actualStock.StockQuantity - actualStock.ReservedQuantity > 0)+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product,+ prevstock.WarehouseId);+ }+ if (product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity) > 0)+ if (prevMultiWarehouseStock.Sum(x => x.StockQuantity - x.ReservedQuantity) <= 0)+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(product, "");+ }}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.csindex fd49c10ae..1d9c74f21 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs@@ -3,24 +3,23 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Catalog.Products;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class UpdateProductTierPriceCommandHandler : IRequestHandler<UpdateProductTierPriceCommand, bool>{- public class UpdateProductTierPriceCommandHandler : IRequestHandler<UpdateProductTierPriceCommand, bool>- {- private readonly IProductService _productService;+ private readonly IProductService _productService;- public UpdateProductTierPriceCommandHandler(IProductService productService)- {- _productService = productService;- }+ public UpdateProductTierPriceCommandHandler(IProductService productService)+ {+ _productService = productService;+ }- public async Task<bool> Handle(UpdateProductTierPriceCommand request, CancellationToken cancellationToken)- {- var product = await _productService.GetProductById(request.Product.Id, true);- var tierPrice = request.Model.ToEntity();- await _productService.UpdateTierPrice(tierPrice, product.Id);+ public async Task<bool> Handle(UpdateProductTierPriceCommand request, CancellationToken cancellationToken)+ {+ var product = await _productService.GetProductById(request.Product.Id, true);+ var tierPrice = request.Model.ToEntity();+ await _productService.UpdateTierPrice(tierPrice, product.Id);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.csindex f868b737e..a181a398c 100644--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs@@ -6,37 +6,36 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Catalog+namespace Grand.Api.Commands.Handlers.Catalog;++public class+ UpdateSpecificationAttributeCommandHandler : IRequestHandler<UpdateSpecificationAttributeCommand,+ SpecificationAttributeDto>{- public class UpdateSpecificationAttributeCommandHandler : IRequestHandler<UpdateSpecificationAttributeCommand, SpecificationAttributeDto>- {- private readonly ISpecificationAttributeService _specificationAttributeService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly ISpecificationAttributeService _specificationAttributeService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateSpecificationAttributeCommandHandler(- ISpecificationAttributeService specificationAttributeService,- ITranslationService translationService,- IWorkContext workContext)- {- _specificationAttributeService = specificationAttributeService;- _translationService = translationService;- _workContext = workContext;- }+ public UpdateSpecificationAttributeCommandHandler(+ ISpecificationAttributeService specificationAttributeService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _specificationAttributeService = specificationAttributeService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<SpecificationAttributeDto> Handle(UpdateSpecificationAttributeCommand request, CancellationToken cancellationToken)- {- var specificationAttribute = await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id);- foreach (var option in specificationAttribute.SpecificationAttributeOptions)- {- if (request.Model.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == option.Id) == null)- {- await _specificationAttributeService.DeleteSpecificationAttributeOption(option);- }- }- specificationAttribute = request.Model.ToEntity(specificationAttribute);- await _specificationAttributeService.UpdateSpecificationAttribute(specificationAttribute);- return specificationAttribute.ToModel();- }+ public async Task<SpecificationAttributeDto> Handle(UpdateSpecificationAttributeCommand request,+ CancellationToken cancellationToken)+ {+ var specificationAttribute =+ await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id);+ foreach (var option in specificationAttribute.SpecificationAttributeOptions)+ if (request.Model.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == option.Id) == null)+ await _specificationAttributeService.DeleteSpecificationAttributeOption(option);+ specificationAttribute = request.Model.ToEntity(specificationAttribute);+ await _specificationAttributeService.UpdateSpecificationAttribute(specificationAttribute);+ return specificationAttribute.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/AddPictureCommandHandler.csindex 6ea9ba4bd..0137d4940 100644--- a/src/API/Grand.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs@@ -4,29 +4,27 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Storage;using MediatR;-namespace Grand.Api.Commands.Handlers.Common-{- public class AddPictureCommandHandler : IRequestHandler<AddPictureCommand, PictureDto>- {- private readonly IPictureService _pictureService;+namespace Grand.Api.Commands.Handlers.Common;- public AddPictureCommandHandler(IPictureService pictureService)- {- _pictureService = pictureService;- }+public class AddPictureCommandHandler : IRequestHandler<AddPictureCommand, PictureDto>+{+ private readonly IPictureService _pictureService;- public async Task<PictureDto> Handle(AddPictureCommand request, CancellationToken cancellationToken)- {- var picture = await _pictureService.InsertPicture(request.PictureDto.PictureBinary, request.PictureDto.MimeType,- request.PictureDto.SeoFilename,- request.PictureDto.AltAttribute,- request.PictureDto.TitleAttribute,- request.PictureDto.IsNew,- request.PictureDto.Reference,- request.PictureDto.ObjectId);+ public AddPictureCommandHandler(IPictureService pictureService)+ {+ _pictureService = pictureService;+ }- return picture.ToModel();+ public async Task<PictureDto> Handle(AddPictureCommand request, CancellationToken cancellationToken)+ {+ var picture = await _pictureService.InsertPicture(request.PictureDto.PictureBinary, request.PictureDto.MimeType,+ request.PictureDto.SeoFilename,+ request.PictureDto.AltAttribute,+ request.PictureDto.TitleAttribute,+ request.PictureDto.IsNew,+ request.PictureDto.Reference,+ request.PictureDto.ObjectId);- }+ return picture.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Common/DeletePictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/DeletePictureCommandHandler.csindex b061a2a01..fb15a8f19 100644--- a/src/API/Grand.Api/Commands/Handlers/Common/DeletePictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Common/DeletePictureCommandHandler.cs@@ -2,27 +2,22 @@using Grand.Business.Core.Interfaces.Storage;using MediatR;-namespace Grand.Api.Commands.Handlers.Common-{- public class DeletePictureCommandHandler : IRequestHandler<DeletePictureCommand, bool>- {- private readonly IPictureService _pictureService;+namespace Grand.Api.Commands.Handlers.Common;- public DeletePictureCommandHandler(IPictureService pictureService)- {- _pictureService = pictureService;- }+public class DeletePictureCommandHandler : IRequestHandler<DeletePictureCommand, bool>+{+ private readonly IPictureService _pictureService;- public async Task<bool> Handle(DeletePictureCommand request, CancellationToken cancellationToken)- {- var picture = await _pictureService.GetPictureById(request.PictureDto.Id);- if (picture != null)- {- await _pictureService.DeletePicture(picture);- }+ public DeletePictureCommandHandler(IPictureService pictureService)+ {+ _pictureService = pictureService;+ }- return true;+ public async Task<bool> Handle(DeletePictureCommand request, CancellationToken cancellationToken)+ {+ var picture = await _pictureService.GetPictureById(request.PictureDto.Id);+ if (picture != null) await _pictureService.DeletePicture(picture);- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenCommandHandler.csindex 5f8899c47..0294a9392 100644--- a/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenCommandHandler.cs@@ -4,31 +4,31 @@ using Grand.Api.Jwt;using Grand.Infrastructure.Configuration;using MediatR;-namespace Grand.Api.Commands.Handlers.Common+namespace Grand.Api.Commands.Handlers.Common;++public class GenerateTokenCommandHandler : IRequestHandler<GenerateTokenCommand, string>{- public class GenerateTokenCommandHandler : IRequestHandler<GenerateTokenCommand, string>+ private readonly BackendAPIConfig _apiConfig;++ public GenerateTokenCommandHandler(BackendAPIConfig apiConfig){- private readonly BackendAPIConfig _apiConfig;+ _apiConfig = apiConfig;+ }- public GenerateTokenCommandHandler(BackendAPIConfig apiConfig)- {- _apiConfig = apiConfig;- }- public async Task<string> Handle(GenerateTokenCommand request, CancellationToken cancellationToken)- {- var token = new JwtTokenBuilder();- token.AddSecurityKey(JwtSecurityKey.Create(_apiConfig.SecretKey));+ public async Task<string> Handle(GenerateTokenCommand request, CancellationToken cancellationToken)+ {+ var token = new JwtTokenBuilder();+ token.AddSecurityKey(JwtSecurityKey.Create(_apiConfig.SecretKey));- if (_apiConfig.ValidateIssuer)- token.AddIssuer(_apiConfig.ValidIssuer);- if (_apiConfig.ValidateAudience)- token.AddAudience(_apiConfig.ValidAudience);+ if (_apiConfig.ValidateIssuer)+ token.AddIssuer(_apiConfig.ValidIssuer);+ if (_apiConfig.ValidateAudience)+ token.AddAudience(_apiConfig.ValidAudience);- token.AddClaims(request.Claims);- token.AddExpiry(_apiConfig.ExpiryInMinutes);- token.Build();+ token.AddClaims(request.Claims);+ token.AddExpiry(_apiConfig.ExpiryInMinutes);+ token.Build();- return await Task.FromResult(token.Build().Value);- }+ return await Task.FromResult(token.Build().Value);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenWebCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenWebCommandHandler.csindex a1294fdf6..c658ebb67 100644--- a/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenWebCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Common/GenerateTokenWebCommandHandler.cs@@ -4,32 +4,31 @@ using Grand.Api.Jwt;using Grand.Infrastructure.Configuration;using MediatR;-namespace Grand.Api.Commands.Handlers.Common+namespace Grand.Api.Commands.Handlers.Common;++public class GenerateTokenWebCommandHandler : IRequestHandler<GenerateTokenWebCommand, string>{- public class GenerateTokenWebCommandHandler : IRequestHandler<GenerateTokenWebCommand, string>- {- private readonly FrontendAPIConfig _frontendApiConfig;+ private readonly FrontendAPIConfig _frontendApiConfig;- public GenerateTokenWebCommandHandler(FrontendAPIConfig frontedApiConfig)- {- _frontendApiConfig = frontedApiConfig;- }+ public GenerateTokenWebCommandHandler(FrontendAPIConfig frontedApiConfig)+ {+ _frontendApiConfig = frontedApiConfig;+ }- public async Task<string> Handle(GenerateTokenWebCommand request, CancellationToken cancellationToken)- {- var token = new JwtTokenBuilder();- token.AddSecurityKey(JwtSecurityKey.Create(_frontendApiConfig.SecretKey));+ public async Task<string> Handle(GenerateTokenWebCommand request, CancellationToken cancellationToken)+ {+ var token = new JwtTokenBuilder();+ token.AddSecurityKey(JwtSecurityKey.Create(_frontendApiConfig.SecretKey));- if (_frontendApiConfig.ValidateIssuer)- token.AddIssuer(_frontendApiConfig.ValidIssuer);- if (_frontendApiConfig.ValidateAudience)- token.AddAudience(_frontendApiConfig.ValidAudience);+ if (_frontendApiConfig.ValidateIssuer)+ token.AddIssuer(_frontendApiConfig.ValidIssuer);+ if (_frontendApiConfig.ValidateAudience)+ token.AddAudience(_frontendApiConfig.ValidAudience);- token.AddClaims(request.Claims);- token.AddExpiry(_frontendApiConfig.ExpiryInMinutes);- token.Build();+ token.AddClaims(request.Claims);+ token.AddExpiry(_frontendApiConfig.ExpiryInMinutes);+ token.Build();- return await Task.FromResult(token.Build().Value);- }+ return await Task.FromResult(token.Build().Value);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Common/UpdatePictureCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/UpdatePictureCommandHandler.csindex 7dddf5ea3..4c0dbce79 100644--- a/src/API/Grand.Api/Commands/Handlers/Common/UpdatePictureCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Common/UpdatePictureCommandHandler.cs@@ -2,29 +2,28 @@using Grand.Business.Core.Interfaces.Storage;using MediatR;-namespace Grand.Api.Commands.Handlers.Common+namespace Grand.Api.Commands.Handlers.Common;++public class UpdatePictureCommandHandler : IRequestHandler<UpdatePictureCommand, bool>{- public class UpdatePictureCommandHandler : IRequestHandler<UpdatePictureCommand, bool>- {- private readonly IPictureService _pictureService;+ private readonly IPictureService _pictureService;- public UpdatePictureCommandHandler(- IPictureService pictureService)- {- _pictureService = pictureService;- }+ public UpdatePictureCommandHandler(+ IPictureService pictureService)+ {+ _pictureService = pictureService;+ }- public async Task<bool> Handle(UpdatePictureCommand request, CancellationToken cancellationToken)- {- var picture = await _pictureService.GetPictureById(request.Model.Id);- if (picture == null)- return false;+ public async Task<bool> Handle(UpdatePictureCommand request, CancellationToken cancellationToken)+ {+ var picture = await _pictureService.GetPictureById(request.Model.Id);+ if (picture == null)+ return false;- await _pictureService.UpdatePicture(picture.Id, request.Model.PictureBinary,- request.Model.MimeType, request.Model.SeoFilename, request.Model.AltAttribute, request.Model.TitleAttribute,- request.Model.Style, request.Model.ExtraField);+ await _pictureService.UpdatePicture(picture.Id, request.Model.PictureBinary,+ request.Model.MimeType, request.Model.SeoFilename, request.Model.AltAttribute, request.Model.TitleAttribute,+ request.Model.Style, request.Model.ExtraField);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.csindex 530900f3d..802f2ab26 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs@@ -4,23 +4,22 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class AddCustomerAddressCommandHandler : IRequestHandler<AddCustomerAddressCommand, AddressDto>{- public class AddCustomerAddressCommandHandler : IRequestHandler<AddCustomerAddressCommand, AddressDto>- {- private readonly ICustomerService _customerService;+ private readonly ICustomerService _customerService;- public AddCustomerAddressCommandHandler(ICustomerService customerService)- {- _customerService = customerService;- }+ public AddCustomerAddressCommandHandler(ICustomerService customerService)+ {+ _customerService = customerService;+ }- public async Task<AddressDto> Handle(AddCustomerAddressCommand request, CancellationToken cancellationToken)- {- var address = request.Address.ToEntity();- address.Id = "";- await _customerService.InsertAddress(address, request.Customer.Id);- return address.ToModel();- }+ public async Task<AddressDto> Handle(AddCustomerAddressCommand request, CancellationToken cancellationToken)+ {+ var address = request.Address.ToEntity();+ address.Id = "";+ await _customerService.InsertAddress(address, request.Customer.Id);+ return address.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.csindex e380f1b38..656fdf871 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs@@ -8,85 +8,86 @@ using Grand.Domain.Customers;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class AddCustomerCommandHandler : IRequestHandler<AddCustomerCommand, CustomerDto>{- public class AddCustomerCommandHandler : IRequestHandler<AddCustomerCommand, CustomerDto>+ private readonly ICustomerService _customerService;+ private readonly IGroupService _groupService;+ private readonly ITranslationService _translationService;+ private readonly IUserFieldService _userFieldsService;+ private readonly IWorkContext _workContext;++ public AddCustomerCommandHandler(+ ICustomerService customerService,+ IGroupService groupService,+ ITranslationService translationService,+ IUserFieldService userFieldsService,+ IWorkContext workContext){- private readonly ICustomerService _customerService;- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IUserFieldService _userFieldsService;- private readonly IWorkContext _workContext;+ _customerService = customerService;+ _groupService = groupService;+ _translationService = translationService;+ _userFieldsService = userFieldsService;+ _workContext = workContext;+ }- public AddCustomerCommandHandler(- ICustomerService customerService,- IGroupService groupService,- ITranslationService translationService,- IUserFieldService userFieldsService,- IWorkContext workContext)- {- _customerService = customerService;- _groupService = groupService;- _translationService = translationService;- _userFieldsService = userFieldsService;- _workContext = workContext;- }+ public async Task<CustomerDto> Handle(AddCustomerCommand request, CancellationToken cancellationToken)+ {+ var customer = request.Model.ToEntity();+ customer.LastActivityDateUtc = DateTime.UtcNow;+ if (string.IsNullOrEmpty(customer.Username))+ customer.Username = customer.Email;- public async Task<CustomerDto> Handle(AddCustomerCommand request, CancellationToken cancellationToken)- {- var customer = request.Model.ToEntity();- customer.LastActivityDateUtc = DateTime.UtcNow;- if (string.IsNullOrEmpty(customer.Username))- customer.Username = customer.Email;+ await _customerService.InsertCustomer(customer);+ await SaveCustomerAttributes(request.Model, customer);+ await SaveCustomerGroups(request.Model, customer);- await _customerService.InsertCustomer(customer);- await SaveCustomerAttributes(request.Model, customer);- await SaveCustomerGroups(request.Model, customer);-- return customer.ToModel();- }+ return customer.ToModel();+ }- protected async Task SaveCustomerAttributes(CustomerDto model, Customer customer)- {- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumber, model.VatNumber);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumberStatusId, model.VatNumberStatusId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Gender, model.Gender);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.FirstName, model.FirstName);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.LastName, model.LastName);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.DateOfBirth, model.DateOfBirth);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Company, model.Company);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress, model.StreetAddress);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress2, model.StreetAddress2);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.ZipPostalCode, model.ZipPostalCode);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.City, model.City);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.CountryId, model.CountryId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StateProvinceId, model.StateProvinceId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Phone, model.Phone);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Fax, model.Fax);- }+ protected async Task SaveCustomerAttributes(CustomerDto model, Customer customer)+ {+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumber, model.VatNumber);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumberStatusId,+ model.VatNumberStatusId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Gender, model.Gender);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.FirstName, model.FirstName);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.LastName, model.LastName);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.DateOfBirth, model.DateOfBirth);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Company, model.Company);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress, model.StreetAddress);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress2, model.StreetAddress2);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.ZipPostalCode, model.ZipPostalCode);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.City, model.City);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.CountryId, model.CountryId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StateProvinceId, model.StateProvinceId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Phone, model.Phone);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Fax, model.Fax);+ }- protected async Task SaveCustomerGroups(CustomerDto model, Customer customer)+ protected async Task SaveCustomerGroups(CustomerDto model, Customer customer)+ {+ var insertgroup = model.Groups.Except(customer.Groups.Select(x => x)).ToList();+ foreach (var item in insertgroup){- var insertgroup = model.Groups.Except(customer.Groups.Select(x => x)).ToList();- foreach (var item in insertgroup)+ var group = await _groupService.GetCustomerGroupById(item);+ if (group != null){- var group = await _groupService.GetCustomerGroupById(item);- if (group != null)- {- customer.Groups.Add(item);- await _customerService.InsertCustomerGroupInCustomer(group, customer.Id);- }+ customer.Groups.Add(item);+ await _customerService.InsertCustomerGroupInCustomer(group, customer.Id);}- var deletegroup = customer.Groups.Select(x => x).Except(model.Groups).ToList();- foreach (var item in deletegroup)+ }++ var deletegroup = customer.Groups.Select(x => x).Except(model.Groups).ToList();+ foreach (var item in deletegroup)+ {+ var group = await _groupService.GetCustomerGroupById(item);+ if (group != null){- var group = await _groupService.GetCustomerGroupById(item);- if (group != null)- {- customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item));- await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id);- }+ customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item));+ await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id);}}}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.csindex f4fcdcf03..1997f744b 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs@@ -6,30 +6,29 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class AddCustomerGroupCommandHandler : IRequestHandler<AddCustomerGroupCommand, CustomerGroupDto>{- public class AddCustomerGroupCommandHandler : IRequestHandler<AddCustomerGroupCommand, CustomerGroupDto>- {- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IGroupService _groupService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public AddCustomerGroupCommandHandler(- IGroupService groupService,- ITranslationService translationService,- IWorkContext workContext)- {- _groupService = groupService;- _translationService = translationService;- _workContext = workContext;- }+ public AddCustomerGroupCommandHandler(+ IGroupService groupService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _groupService = groupService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<CustomerGroupDto> Handle(AddCustomerGroupCommand request, CancellationToken cancellationToken)- {- var customergroup = request.Model.ToEntity();- await _groupService.InsertCustomerGroup(customergroup);+ public async Task<CustomerGroupDto> Handle(AddCustomerGroupCommand request, CancellationToken cancellationToken)+ {+ var customergroup = request.Model.ToEntity();+ await _groupService.InsertCustomerGroup(customergroup);- return customergroup.ToModel();- }+ return customergroup.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.csindex 700641df3..c8ccf8419 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs@@ -2,29 +2,26 @@using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class DeleteCustomerAddressCommandHandler : IRequestHandler<DeleteCustomerAddressCommand, bool>{- public class DeleteCustomerAddressCommandHandler : IRequestHandler<DeleteCustomerAddressCommand, bool>+ private readonly ICustomerService _customerService;++ public DeleteCustomerAddressCommandHandler(ICustomerService customerService){- private readonly ICustomerService _customerService;+ _customerService = customerService;+ }- public DeleteCustomerAddressCommandHandler(ICustomerService customerService)+ public async Task<bool> Handle(DeleteCustomerAddressCommand request, CancellationToken cancellationToken)+ {+ var customer = await _customerService.GetCustomerById(request.Customer.Id);+ if (customer != null){- _customerService = customerService;+ var address = customer.Addresses.FirstOrDefault(x => x.Id == request.Address.Id);+ if (address != null) await _customerService.DeleteAddress(address, request.Customer.Id);}- public async Task<bool> Handle(DeleteCustomerAddressCommand request, CancellationToken cancellationToken)- {- var customer = await _customerService.GetCustomerById(request.Customer.Id);- if (customer != null)- {- var address = customer.Addresses.FirstOrDefault(x => x.Id == request.Address.Id);- if (address != null)- {- await _customerService.DeleteAddress(address, request.Customer.Id);- }- }- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.csindex 6d5fbb8d5..bd9230ebd 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs@@ -4,34 +4,29 @@ using Grand.Business.Core.Interfaces.Customers;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers-{- public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommand, bool>- {- private readonly ICustomerService _customerService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+namespace Grand.Api.Commands.Handlers.Customers;- public DeleteCustomerCommandHandler(- ICustomerService customerService,- ITranslationService translationService,- IWorkContext workContext)- {- _customerService = customerService;- _translationService = translationService;- _workContext = workContext;- }+public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommand, bool>+{+ private readonly ICustomerService _customerService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public async Task<bool> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken)- {- var customer = await _customerService.GetCustomerByEmail(request.Email);- if (customer != null)- {- await _customerService.DeleteCustomer(customer);- }+ public DeleteCustomerCommandHandler(+ ICustomerService customerService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _customerService = customerService;+ _translationService = translationService;+ _workContext = workContext;+ }- return true;- }+ public async Task<bool> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken)+ {+ var customer = await _customerService.GetCustomerByEmail(request.Email);+ if (customer != null) await _customerService.DeleteCustomer(customer);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.csindex 26454e2b2..47e31e450 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs@@ -4,32 +4,28 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class DeleteCustomerGroupCommandHandler : IRequestHandler<DeleteCustomerGroupCommand, bool>{- public class DeleteCustomerGroupCommandHandler : IRequestHandler<DeleteCustomerGroupCommand, bool>- {- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IGroupService _groupService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public DeleteCustomerGroupCommandHandler(- IGroupService groupService,- ITranslationService translationService,- IWorkContext workContext)- {- _groupService = groupService;- _translationService = translationService;- _workContext = workContext;- }+ public DeleteCustomerGroupCommandHandler(+ IGroupService groupService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _groupService = groupService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<bool> Handle(DeleteCustomerGroupCommand request, CancellationToken cancellationToken)- {- var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id);- if (customerGroup != null)- {- await _groupService.DeleteCustomerGroup(customerGroup);- }- return true;- }+ public async Task<bool> Handle(DeleteCustomerGroupCommand request, CancellationToken cancellationToken)+ {+ var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id);+ if (customerGroup != null) await _groupService.DeleteCustomerGroup(customerGroup);+ return true;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.csindex 2b07becb2..28a8dce3f 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs@@ -4,31 +4,31 @@ using Grand.Api.Extensions;using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class UpdateCustomerAddressCommandHandler : IRequestHandler<UpdateCustomerAddressCommand, AddressDto>{- public class UpdateCustomerAddressCommandHandler : IRequestHandler<UpdateCustomerAddressCommand, AddressDto>- {- private readonly ICustomerService _customerService;+ private readonly ICustomerService _customerService;- public UpdateCustomerAddressCommandHandler(ICustomerService customerService)- {- _customerService = customerService;- }+ public UpdateCustomerAddressCommandHandler(ICustomerService customerService)+ {+ _customerService = customerService;+ }- public async Task<AddressDto> Handle(UpdateCustomerAddressCommand request, CancellationToken cancellationToken)+ public async Task<AddressDto> Handle(UpdateCustomerAddressCommand request, CancellationToken cancellationToken)+ {+ var customer = await _customerService.GetCustomerById(request.Customer.Id);+ if (customer != null){- var customer = await _customerService.GetCustomerById(request.Customer.Id);- if (customer != null)+ var address = customer.Addresses.FirstOrDefault(x => x.Id == request.Address.Id);+ if (address != null){- var address = customer.Addresses.FirstOrDefault(x => x.Id == request.Address.Id);- if (address != null)- {- address = request.Address.ToEntity(address);- await _customerService.UpdateAddress(address, request.Customer.Id);- return address.ToModel();- }+ address = request.Address.ToEntity(address);+ await _customerService.UpdateAddress(address, request.Customer.Id);+ return address.ToModel();}- return null;}++ return null;}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.csindex e0c58c521..5ba565073 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs@@ -8,81 +8,82 @@ using Grand.Domain.Customers;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, CustomerDto>{- public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, CustomerDto>+ private readonly ICustomerService _customerService;+ private readonly IGroupService _groupService;+ private readonly ITranslationService _translationService;+ private readonly IUserFieldService _userFieldsService;+ private readonly IWorkContext _workContext;++ public UpdateCustomerCommandHandler(+ ICustomerService customerService,+ IGroupService groupService,+ ITranslationService translationService,+ IUserFieldService userFieldsService,+ IWorkContext workContext){- private readonly ICustomerService _customerService;- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IUserFieldService _userFieldsService;- private readonly IWorkContext _workContext;+ _customerService = customerService;+ _groupService = groupService;+ _translationService = translationService;+ _userFieldsService = userFieldsService;+ _workContext = workContext;+ }- public UpdateCustomerCommandHandler(- ICustomerService customerService,- IGroupService groupService,- ITranslationService translationService,- IUserFieldService userFieldsService,- IWorkContext workContext)- {- _customerService = customerService;- _groupService = groupService;- _translationService = translationService;- _userFieldsService = userFieldsService;- _workContext = workContext;- }+ public async Task<CustomerDto> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)+ {+ var customer = await _customerService.GetCustomerById(request.Model.Id);+ customer = request.Model.ToEntity(customer);+ await _customerService.UpdateCustomer(customer);+ await SaveCustomerAttributes(request.Model, customer);+ await SaveCustomerGroups(request.Model, customer);+ return customer.ToModel();+ }- public async Task<CustomerDto> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)- {- var customer = await _customerService.GetCustomerById(request.Model.Id);- customer = request.Model.ToEntity(customer);- await _customerService.UpdateCustomer(customer);- await SaveCustomerAttributes(request.Model, customer);- await SaveCustomerGroups(request.Model, customer);- return customer.ToModel();- }+ protected async Task SaveCustomerAttributes(CustomerDto model, Customer customer)+ {+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumber, model.VatNumber);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumberStatusId,+ model.VatNumberStatusId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Gender, model.Gender);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.FirstName, model.FirstName);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.LastName, model.LastName);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.DateOfBirth, model.DateOfBirth);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Company, model.Company);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress, model.StreetAddress);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress2, model.StreetAddress2);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.ZipPostalCode, model.ZipPostalCode);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.City, model.City);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.CountryId, model.CountryId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StateProvinceId, model.StateProvinceId);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Phone, model.Phone);+ await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Fax, model.Fax);+ }- protected async Task SaveCustomerAttributes(CustomerDto model, Customer customer)+ protected async Task SaveCustomerGroups(CustomerDto model, Customer customer)+ {+ var insertgroup = model.Groups.Except(customer.Groups.Select(x => x)).ToList();+ foreach (var item in insertgroup){- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumber, model.VatNumber);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.VatNumberStatusId, model.VatNumberStatusId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Gender, model.Gender);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.FirstName, model.FirstName);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.LastName, model.LastName);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.DateOfBirth, model.DateOfBirth);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Company, model.Company);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress, model.StreetAddress);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StreetAddress2, model.StreetAddress2);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.ZipPostalCode, model.ZipPostalCode);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.City, model.City);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.CountryId, model.CountryId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.StateProvinceId, model.StateProvinceId);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Phone, model.Phone);- await _userFieldsService.SaveField(customer, SystemCustomerFieldNames.Fax, model.Fax);+ var group = await _groupService.GetCustomerGroupById(item);+ if (group != null)+ {+ customer.Groups.Add(item);+ await _customerService.InsertCustomerGroupInCustomer(group, customer.Id);+ }}- protected async Task SaveCustomerGroups(CustomerDto model, Customer customer)+ var deletegroup = customer.Groups.Select(x => x).Except(model.Groups).ToList();+ foreach (var item in deletegroup){- var insertgroup = model.Groups.Except(customer.Groups.Select(x => x)).ToList();- foreach (var item in insertgroup)- {- var group = await _groupService.GetCustomerGroupById(item);- if (group != null)- {- customer.Groups.Add(item);- await _customerService.InsertCustomerGroupInCustomer(group, customer.Id);- }- }- var deletegroup = customer.Groups.Select(x => x).Except(model.Groups).ToList();- foreach (var item in deletegroup)+ var group = await _groupService.GetCustomerGroupById(item);+ if (group != null){- var group = await _groupService.GetCustomerGroupById(item);- if (group != null)- {- customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item));- await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id);- }+ customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item));+ await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id);}}}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.csindex 38a921dbc..9a026e37e 100644--- a/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs+++ b/src/API/Grand.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs@@ -6,31 +6,30 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure;using MediatR;-namespace Grand.Api.Commands.Handlers.Customers+namespace Grand.Api.Commands.Handlers.Customers;++public class UpdateCustomerGroupCommandHandler : IRequestHandler<UpdateCustomerGroupCommand, CustomerGroupDto>{- public class UpdateCustomerGroupCommandHandler : IRequestHandler<UpdateCustomerGroupCommand, CustomerGroupDto>- {- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IWorkContext _workContext;+ private readonly IGroupService _groupService;+ private readonly ITranslationService _translationService;+ private readonly IWorkContext _workContext;- public UpdateCustomerGroupCommandHandler(- IGroupService groupService,- ITranslationService translationService,- IWorkContext workContext)- {- _groupService = groupService;- _translationService = translationService;- _workContext = workContext;- }+ public UpdateCustomerGroupCommandHandler(+ IGroupService groupService,+ ITranslationService translationService,+ IWorkContext workContext)+ {+ _groupService = groupService;+ _translationService = translationService;+ _workContext = workContext;+ }- public async Task<CustomerGroupDto> Handle(UpdateCustomerGroupCommand request, CancellationToken cancellationToken)- {- var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id);- customerGroup = request.Model.ToEntity(customerGroup);- await _groupService.UpdateCustomerGroup(customerGroup);+ public async Task<CustomerGroupDto> Handle(UpdateCustomerGroupCommand request, CancellationToken cancellationToken)+ {+ var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id);+ customerGroup = request.Model.ToEntity(customerGroup);+ await _groupService.UpdateCustomerGroup(customerGroup);- return customerGroup.ToModel();- }+ return customerGroup.ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddBrandCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddBrandCommand.csindex fec0150c1..726f0a662 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddBrandCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddBrandCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddBrandCommand : IRequest<BrandDto>{- public class AddBrandCommand : IRequest<BrandDto>- {- public BrandDto Model { get; set; }- }-}+ public BrandDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddCategoryCommand.csindex 35f7da578..d48bedf9f 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddCategoryCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddCategoryCommand : IRequest<CategoryDto>{- public class AddCategoryCommand : IRequest<CategoryDto>- {- public CategoryDto Model { get; set; }- }-}+ public CategoryDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddCollectionCommand.csindex 4190ac3b2..17f2d311b 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddCollectionCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddCollectionCommand : IRequest<CollectionDto>{- public class AddCollectionCommand : IRequest<CollectionDto>- {- public CollectionDto Model { get; set; }- }-}+ public CollectionDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeCommand.csindex 152f23f8c..77099c371 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductAttributeCommand : IRequest<ProductAttributeDto>{- public class AddProductAttributeCommand : IRequest<ProductAttributeDto>- {- public ProductDto Product { get; set; }- public ProductAttributeDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.csindex b98490ac8..8917e4370 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductAttributeMappingCommand : IRequest<ProductAttributeMappingDto>{- public class AddProductAttributeMappingCommand : IRequest<ProductAttributeMappingDto>- {- public ProductDto Product { get; set; }- public ProductAttributeMappingDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductAttributeMappingDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCategoryCommand.csindex e0b33d7f1..d0c6f0e3a 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductCategoryCommand : IRequest<bool>{- public class AddProductCategoryCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductCategoryDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductCategoryDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCollectionCommand.csindex f65239206..2592feb99 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductCollectionCommand : IRequest<bool>{- public class AddProductCollectionCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductCollectionDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductCollectionDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCommand.csindex e20dd53ad..831800b11 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductCommand : IRequest<ProductDto>{- public class AddProductCommand : IRequest<ProductDto>- {- public ProductDto Model { get; set; }- }-}+ public ProductDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductPictureCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductPictureCommand.csindex 70b12cd5e..8271cc5f1 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductPictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductPictureCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductPictureCommand : IRequest<bool>{- public class AddProductPictureCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductPictureDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductPictureDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductSpecificationCommand.csindex 9c5811b03..fb1703431 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductSpecificationCommand : IRequest<bool>{- public class AddProductSpecificationCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductSpecificationAttributeDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductSpecificationAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddProductTierPriceCommand.csindex 798c19278..117bc67c6 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddProductTierPriceCommand : IRequest<bool>{- public class AddProductTierPriceCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductTierPriceDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductTierPriceDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.csindex 472260226..64d436798 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class AddSpecificationAttributeCommand : IRequest<SpecificationAttributeDto>{- public class AddSpecificationAttributeCommand : IRequest<SpecificationAttributeDto>- {- public SpecificationAttributeDto Model { get; set; }- }-}+ public SpecificationAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteBrandCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteBrandCommand.csindex abc093956..277c5d8ef 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteBrandCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteBrandCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteBrandCommand : IRequest<bool>{- public class DeleteBrandCommand : IRequest<bool>- {- public BrandDto Model { get; set; }- }-}+ public BrandDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteCategoryCommand.csindex 5932a1f11..0b91f382b 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteCategoryCommand : IRequest<bool>{- public class DeleteCategoryCommand : IRequest<bool>- {- public CategoryDto Model { get; set; }- }-}+ public CategoryDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteCollectionCommand.csindex 2a5b2be84..a39aed343 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteCollectionCommand : IRequest<bool>{- public class DeleteCollectionCommand : IRequest<bool>- {- public CollectionDto Model { get; set; }- }-}+ public CollectionDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.csindex 4e084b54b..7fbc5fe95 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductAttributeCommand : IRequest<bool>{- public class DeleteProductAttributeCommand : IRequest<bool>- {- public ProductAttributeDto Model { get; set; }- }-}+ public ProductAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.csindex a2d104409..b01919436 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductAttributeMappingCommand : IRequest<bool>{- public class DeleteProductAttributeMappingCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductAttributeMappingDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductAttributeMappingDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.csindex 4b4c4e5f3..f1d957457 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductCategoryCommand : IRequest<bool>{- public class DeleteProductCategoryCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string CategoryId { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string CategoryId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.csindex 53f2c3423..b4e797a25 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductCollectionCommand : IRequest<bool>{- public class DeleteProductCollectionCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string CollectionId { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string CollectionId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCommand.csindex c4a20c767..b62ebc8fc 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductCommand : IRequest<bool>{- public class DeleteProductCommand : IRequest<bool>- {- public ProductDto Model { get; set; }- }-}+ public ProductDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductPictureCommand.csindex f066ee234..523541b6e 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductPictureCommand : IRequest<bool>{- public class DeleteProductPictureCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string PictureId { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string PictureId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.csindex a34239036..3280ce097 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductSpecificationCommand : IRequest<bool>{- public class DeleteProductSpecificationCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string Id { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.csindex 174550622..ead89ce4e 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteProductTierPriceCommand : IRequest<bool>{- public class DeleteProductTierPriceCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string Id { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.csindex 008cc7f79..d1e5f38bd 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class DeleteSpecificationAttributeCommand : IRequest<bool>{- public class DeleteSpecificationAttributeCommand : IRequest<bool>- {- public SpecificationAttributeDto Model { get; set; }- }-}+ public SpecificationAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateBrandCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateBrandCommand.csindex d240ce2a8..4c52f3c79 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateBrandCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateBrandCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateBrandCommand : IRequest<BrandDto>{- public class UpdateBrandCommand : IRequest<BrandDto>- {- public BrandDto Model { get; set; }- }-}+ public BrandDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateCategoryCommand.csindex ba5d0bd82..4cd1d8129 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateCategoryCommand : IRequest<CategoryDto>{- public class UpdateCategoryCommand : IRequest<CategoryDto>- {- public CategoryDto Model { get; set; }- }-}+ public CategoryDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateCollectionCommand.csindex 86564109d..698efb19d 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateCollectionCommand : IRequest<CollectionDto>{- public class UpdateCollectionCommand : IRequest<CollectionDto>- {- public CollectionDto Model { get; set; }- }-}+ public CollectionDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.csindex eca9ae702..a5795c2d8 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductAttributeCommand : IRequest<ProductAttributeDto>{- public class UpdateProductAttributeCommand : IRequest<ProductAttributeDto>- {- public ProductAttributeDto Model { get; set; }- }-}+ public ProductAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.csindex bcac2ff66..597ec826f 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductAttributeMappingCommand : IRequest<ProductAttributeMappingDto>{- public class UpdateProductAttributeMappingCommand : IRequest<ProductAttributeMappingDto>- {- public ProductDto Product { get; set; }- public ProductAttributeMappingDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductAttributeMappingDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.csindex b2df81636..d0173cfe5 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductCategoryCommand : IRequest<bool>{- public class UpdateProductCategoryCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductCategoryDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductCategoryDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.csindex cbd660ecb..4a98889f8 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductCollectionCommand : IRequest<bool>{- public class UpdateProductCollectionCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductCollectionDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductCollectionDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCommand.csindex 0caba60e1..6deb558ae 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductCommand : IRequest<ProductDto>{- public class UpdateProductCommand : IRequest<ProductDto>- {- public ProductDto Model { get; set; }- }-}+ public ProductDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductPictureCommand.csindex e399e7973..aac5f4ebb 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductPictureCommand : IRequest<bool>{- public class UpdateProductPictureCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductPictureDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductPictureDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.csindex c72b778bb..4f7c1d7a4 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductSpecificationCommand : IRequest<bool>{- public class UpdateProductSpecificationCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductSpecificationAttributeDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductSpecificationAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductStockCommand.csindex 6d1b5bd8d..caaf7e801 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs@@ -1,12 +1,11 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductStockCommand : IRequest<bool>{- public class UpdateProductStockCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public string WarehouseId { get; set; }- public int Stock { get; set; }- }-}+ public ProductDto Product { get; set; }+ public string WarehouseId { get; set; }+ public int Stock { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.csindex 351073e60..4075b3a48 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateProductTierPriceCommand : IRequest<bool>{- public class UpdateProductTierPriceCommand : IRequest<bool>- {- public ProductDto Product { get; set; }- public ProductTierPriceDto Model { get; set; }- }-}+ public ProductDto Product { get; set; }+ public ProductTierPriceDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs b/src/API/Grand.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.csindex 16095af1c..36bfe3aa8 100644--- a/src/API/Grand.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Catalog;using MediatR;-namespace Grand.Api.Commands.Models.Catalog+namespace Grand.Api.Commands.Models.Catalog;++public class UpdateSpecificationAttributeCommand : IRequest<SpecificationAttributeDto>{- public class UpdateSpecificationAttributeCommand : IRequest<SpecificationAttributeDto>- {- public SpecificationAttributeDto Model { get; set; }- }-}+ public SpecificationAttributeDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Common/AddPictureCommand.cs b/src/API/Grand.Api/Commands/Models/Common/AddPictureCommand.csindex e8361f86d..063ebd114 100644--- a/src/API/Grand.Api/Commands/Models/Common/AddPictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Common/AddPictureCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Common;using MediatR;-namespace Grand.Api.Commands.Models.Common+namespace Grand.Api.Commands.Models.Common;++public class AddPictureCommand : IRequest<PictureDto>{- public class AddPictureCommand : IRequest<PictureDto>- {- public PictureDto PictureDto { get; set; }- }-}+ public PictureDto PictureDto { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Common/DeletePictureCommand.cs b/src/API/Grand.Api/Commands/Models/Common/DeletePictureCommand.csindex 416f16677..6cf0b2b63 100644--- a/src/API/Grand.Api/Commands/Models/Common/DeletePictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Common/DeletePictureCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Common;using MediatR;-namespace Grand.Api.Commands.Models.Common+namespace Grand.Api.Commands.Models.Common;++public class DeletePictureCommand : IRequest<bool>{- public class DeletePictureCommand : IRequest<bool>- {- public PictureDto PictureDto { get; set; }- }-}+ public PictureDto PictureDto { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Common/GenerateTokenCommand.cs b/src/API/Grand.Api/Commands/Models/Common/GenerateTokenCommand.csindex 4665dc9ec..6d29b1c23 100644--- a/src/API/Grand.Api/Commands/Models/Common/GenerateTokenCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Common/GenerateTokenCommand.cs@@ -1,9 +1,8 @@using MediatR;-namespace Grand.Api.Commands.Models.Common+namespace Grand.Api.Commands.Models.Common;++public class GenerateTokenCommand : IRequest<string>{- public class GenerateTokenCommand : IRequest<string>- {- public Dictionary<string, string> Claims { get; set; }- }-}+ public Dictionary<string, string> Claims { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Common/GenerateTokenWebCommand.cs b/src/API/Grand.Api/Commands/Models/Common/GenerateTokenWebCommand.csindex 2bf584094..b268abee0 100644--- a/src/API/Grand.Api/Commands/Models/Common/GenerateTokenWebCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Common/GenerateTokenWebCommand.cs@@ -1,9 +1,8 @@using MediatR;-namespace Grand.Api.Commands.Models.Common+namespace Grand.Api.Commands.Models.Common;++public class GenerateTokenWebCommand : IRequest<string>{- public class GenerateTokenWebCommand : IRequest<string>- {- public Dictionary<string, string> Claims { get; set; }- }-}+ public Dictionary<string, string> Claims { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Common/UpdatePictureCommand.cs b/src/API/Grand.Api/Commands/Models/Common/UpdatePictureCommand.csindex 5be820c7d..5ccefa801 100644--- a/src/API/Grand.Api/Commands/Models/Common/UpdatePictureCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Common/UpdatePictureCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Common;using MediatR;-namespace Grand.Api.Commands.Models.Common+namespace Grand.Api.Commands.Models.Common;++public class UpdatePictureCommand : IRequest<bool>{- public class UpdatePictureCommand : IRequest<bool>- {- public PictureDto Model { get; set; }- }-}+ public PictureDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerAddressCommand.csindex 0152ca965..a6ac8901c 100644--- a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class AddCustomerAddressCommand : IRequest<AddressDto>{- public class AddCustomerAddressCommand : IRequest<AddressDto>- {- public CustomerDto Customer { get; set; }- public AddressDto Address { get; set; }- }-}+ public CustomerDto Customer { get; set; }+ public AddressDto Address { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerCommand.csindex 3b8adbea9..e46613772 100644--- a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class AddCustomerCommand : IRequest<CustomerDto>{- public class AddCustomerCommand : IRequest<CustomerDto>- {- public CustomerDto Model { get; set; }- }-}+ public CustomerDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerGroupCommand.csindex d5e594d34..de5a1dcd0 100644--- a/src/API/Grand.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class AddCustomerGroupCommand : IRequest<CustomerGroupDto>{- public class AddCustomerGroupCommand : IRequest<CustomerGroupDto>- {- public CustomerGroupDto Model { get; set; }- }-}+ public CustomerGroupDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.csindex 770260323..9dc2bafc1 100644--- a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class DeleteCustomerAddressCommand : IRequest<bool>{- public class DeleteCustomerAddressCommand : IRequest<bool>- {- public CustomerDto Customer { get; set; }- public AddressDto Address { get; set; }- }-}+ public CustomerDto Customer { get; set; }+ public AddressDto Address { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerCommand.csindex 34d6e0f37..82a032f9e 100644--- a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerCommand.cs@@ -1,9 +1,8 @@using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class DeleteCustomerCommand : IRequest<bool>{- public class DeleteCustomerCommand : IRequest<bool>- {- public string Email { get; set; }- }-}+ public string Email { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.csindex e3630126e..80e875e64 100644--- a/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class DeleteCustomerGroupCommand : IRequest<bool>{- public class DeleteCustomerGroupCommand : IRequest<bool>- {- public CustomerGroupDto Model { get; set; }- }-}+ public CustomerGroupDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.csindex f58733f55..6796af1a6 100644--- a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class UpdateCustomerAddressCommand : IRequest<AddressDto>{- public class UpdateCustomerAddressCommand : IRequest<AddressDto>- {- public CustomerDto Customer { get; set; }- public AddressDto Address { get; set; }- }-}+ public CustomerDto Customer { get; set; }+ public AddressDto Address { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerCommand.csindex f73c16e6c..8bb75d511 100644--- a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class UpdateCustomerCommand : IRequest<CustomerDto>{- public class UpdateCustomerCommand : IRequest<CustomerDto>- {- public CustomerDto Model { get; set; }- }-}+ public CustomerDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.csindex 2cab279d5..dbdbc60f3 100644--- a/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs+++ b/src/API/Grand.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Commands.Models.Customers+namespace Grand.Api.Commands.Models.Customers;++public class UpdateCustomerGroupCommand : IRequest<CustomerGroupDto>{- public class UpdateCustomerGroupCommand : IRequest<CustomerGroupDto>- {- public CustomerGroupDto Model { get; set; }- }-}+ public CustomerGroupDto Model { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Constants/Configurations.cs b/src/API/Grand.Api/Constants/Configurations.csindex a031345c4..8ae78fa1c 100644--- a/src/API/Grand.Api/Constants/Configurations.cs+++ b/src/API/Grand.Api/Constants/Configurations.cs@@ -1,10 +1,9 @@-namespace Grand.Api.Constants+namespace Grand.Api.Constants;++public static class Configurations{- public static class Configurations- {- public const string ODataRoutePrefix = "odata";- public const string ODataModelBuilderNamespace = "Default";- public const string CorsPolicyName = "CorsPolicy";- public const int MaxLimit = 100;- }-}+ public const string ODataRoutePrefix = "odata";+ public const string ODataModelBuilderNamespace = "Default";+ public const string CorsPolicyName = "CorsPolicy";+ public const int MaxLimit = 100;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/BaseODataController.cs b/src/API/Grand.Api/Controllers/BaseODataController.csindex 176e2ec7f..11295a7a2 100644--- a/src/API/Grand.Api/Controllers/BaseODataController.cs+++ b/src/API/Grand.Api/Controllers/BaseODataController.cs@@ -6,17 +6,16 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Routing.Attributes;using Microsoft.AspNetCore.OData.Routing.Controllers;-namespace Grand.Api.Controllers+namespace Grand.Api.Controllers;++[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]+[ODataRouteComponent]+[AuthorizeApiAdmin]+[ServiceFilter(typeof(ModelValidationAttribute))]+public abstract class BaseODataController : ODataController{- [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]- [ODataRouteComponent]- [AuthorizeApiAdmin]- [ServiceFilter(typeof(ModelValidationAttribute))]- public abstract class BaseODataController : ODataController+ public override ForbidResult Forbid(){- public override ForbidResult Forbid()- {- return new ForbidResult(JwtBearerDefaults.AuthenticationScheme);- }+ return new ForbidResult(JwtBearerDefaults.AuthenticationScheme);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/BrandController.cs b/src/API/Grand.Api/Controllers/OData/BrandController.csindex 448986fde..6e9ec2cbd 100644--- a/src/API/Grand.Api/Controllers/OData/BrandController.cs+++ b/src/API/Grand.Api/Controllers/OData/BrandController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -10,113 +11,113 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Brand")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class BrandController : BaseODataController{- [Route("odata/Brand")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class BrandController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public BrandController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entities from Brand", OperationId = "GetBrands")]+ [HttpGet]+ [MongoEnableQuery]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<BrandDto, Brand>()));+ }++ [SwaggerOperation("Get entity from Brand by key", OperationId = "GetBrandById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> GetById([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Brand>(key));+ if (!brand.Any()) return NotFound();++ return Ok(brand.FirstOrDefault());+ }++ [SwaggerOperation("Add new entity to Brand", OperationId = "InsertBrand")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] BrandDto model){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;- public BrandController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entities from Brand", OperationId = "GetBrands")]- [HttpGet]- [MongoEnableQuery]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<BrandDto, Domain.Catalog.Brand>()));- }-- [SwaggerOperation(summary: "Get entity from Brand by key", OperationId = "GetBrandById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> GetById([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Domain.Catalog.Brand>(key));- if (!brand.Any()) return NotFound();-- return Ok(brand.FirstOrDefault());- }-- [SwaggerOperation(summary: "Add new entity to Brand", OperationId = "InsertBrand")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] BrandDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- model = await _mediator.Send(new AddBrandCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in Brand", OperationId = "UpdateBrand")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Put([FromBody] BrandDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Domain.Catalog.Brand>(model.Id));- if (!brand.Any()) return NotFound();-- model = await _mediator.Send(new UpdateBrandCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Partially update entity in Brand", OperationId = "PartiallyUpdateBrand")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<BrandDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Domain.Catalog.Brand>(key));- if (!brand.Any()) return NotFound();-- var man = brand.FirstOrDefault();- model.ApplyTo(man);- await _mediator.Send(new UpdateBrandCommand { Model = man });- return Ok();- }-- [SwaggerOperation(summary: "Delete entity in Brand", OperationId = "DeleteBrand")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();-- var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Domain.Catalog.Brand>(key));- if (!brand.Any()) return NotFound();-- await _mediator.Send(new DeleteBrandCommand { Model = brand.FirstOrDefault() });- return Ok();- }+ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ model = await _mediator.Send(new AddBrandCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in Brand", OperationId = "UpdateBrand")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Put([FromBody] BrandDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Brand>(model.Id));+ if (!brand.Any()) return NotFound();++ model = await _mediator.Send(new UpdateBrandCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Partially update entity in Brand", OperationId = "PartiallyUpdateBrand")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<BrandDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");++ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Brand>(key));+ if (!brand.Any()) return NotFound();++ var man = brand.FirstOrDefault();+ model.ApplyTo(man);+ await _mediator.Send(new UpdateBrandCommand { Model = man });+ return Ok();+ }++ [SwaggerOperation("Delete entity in Brand", OperationId = "DeleteBrand")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();++ var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Brand>(key));+ if (!brand.Any()) return NotFound();++ await _mediator.Send(new DeleteBrandCommand { Model = brand.FirstOrDefault() });+ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/BrandLayoutController.cs b/src/API/Grand.Api/Controllers/OData/BrandLayoutController.csindex 2825b48be..cbb734521 100644--- a/src/API/Grand.Api/Controllers/OData/BrandLayoutController.cs+++ b/src/API/Grand.Api/Controllers/OData/BrandLayoutController.cs@@ -1,6 +1,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -8,46 +9,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/BrandLayout")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class BrandLayoutController : BaseODataController{- [Route("odata/BrandLayout")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class BrandLayoutController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public BrandLayoutController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from BrandLayout by key", OperationId = "GetBrandLayoutById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get(string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public BrandLayoutController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from BrandLayout by key", OperationId = "GetBrandLayoutById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(Domain.Catalog.BrandLayout).Name });- if (!layout.Any()) return NotFound();-- return Ok(layout.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from BrandLayout", OperationId = "GetBrandLayouts")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(Domain.Catalog.BrandLayout).Name }));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(BrandLayout).Name });+ if (!layout.Any()) return NotFound();++ return Ok(layout.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from BrandLayout", OperationId = "GetBrandLayouts")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(BrandLayout).Name }));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CategoryController.cs b/src/API/Grand.Api/Controllers/OData/CategoryController.csindex d4e567726..ced9f4aa6 100644--- a/src/API/Grand.Api/Controllers/OData/CategoryController.cs+++ b/src/API/Grand.Api/Controllers/OData/CategoryController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,113 +12,115 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Category")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CategoryController : BaseODataController{- [Route("odata/Category")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CategoryController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CategoryController(+ IMediator mediator,+ IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Category by key", OperationId = "GetCategoryById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Category>(key));+ if (!category.Any()) return NotFound();++ return Ok(category.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Category", OperationId = "GetCategories")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<CategoryDto, Category>()));+ }++ [SwaggerOperation("Add new entity to Category", OperationId = "InsertCategory")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] CategoryDto model){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;- public CategoryController(- IMediator mediator,- IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Category by key", OperationId = "GetCategoryById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Domain.Catalog.Category>(key));- if (!category.Any()) return NotFound();-- return Ok(category.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Category", OperationId = "GetCategories")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<CategoryDto, Domain.Catalog.Category>()));- }-- [SwaggerOperation(summary: "Add new entity to Category", OperationId = "InsertCategory")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] CategoryDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- model = await _mediator.Send(new AddCategoryCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in Category", OperationId = "UpdateCategory")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Put([FromBody] CategoryDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Domain.Catalog.Category>(model.Id));- if (!category.Any()) return NotFound();-- model = await _mediator.Send(new UpdateCategoryCommand { Model = model });- return Ok(model);- }- [SwaggerOperation(summary: "Update entity in Category (delta)", OperationId = "UpdateCategoryPatch")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CategoryDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Domain.Catalog.Category>(key));- if (!category.Any()) return NotFound();-- var cat = category.FirstOrDefault();- model.ApplyTo(cat);- await _mediator.Send(new UpdateCategoryCommand { Model = cat });- return Ok();- }- [SwaggerOperation(summary: "Delete entity from Category", OperationId = "DeleteCategory")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();-- var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Domain.Catalog.Category>(key));- if (!category.Any()) return NotFound();-- await _mediator.Send(new DeleteCategoryCommand { Model = category.FirstOrDefault() });- return Ok();- }+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ model = await _mediator.Send(new AddCategoryCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in Category", OperationId = "UpdateCategory")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Put([FromBody] CategoryDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Category>(model.Id));+ if (!category.Any()) return NotFound();++ model = await _mediator.Send(new UpdateCategoryCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in Category (delta)", OperationId = "UpdateCategoryPatch")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CategoryDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");++ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Category>(key));+ if (!category.Any()) return NotFound();++ var cat = category.FirstOrDefault();+ model.ApplyTo(cat);+ await _mediator.Send(new UpdateCategoryCommand { Model = cat });+ return Ok();+ }++ [SwaggerOperation("Delete entity from Category", OperationId = "DeleteCategory")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();++ var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Category>(key));+ if (!category.Any()) return NotFound();++ await _mediator.Send(new DeleteCategoryCommand { Model = category.FirstOrDefault() });+ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CategoryLayoutController.cs b/src/API/Grand.Api/Controllers/OData/CategoryLayoutController.csindex a514f5ec3..455f79ee2 100644--- a/src/API/Grand.Api/Controllers/OData/CategoryLayoutController.cs+++ b/src/API/Grand.Api/Controllers/OData/CategoryLayoutController.cs@@ -1,6 +1,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -8,48 +9,47 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/CategoryLayout")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CategoryLayoutController : BaseODataController{- [Route("odata/CategoryLayout")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CategoryLayoutController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CategoryLayoutController(+ IMediator mediator,+ IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from CategoryLayout by key", OperationId = "GetCategoryLayoutById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public CategoryLayoutController(- IMediator mediator,- IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from CategoryLayout by key", OperationId = "GetCategoryLayoutById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(Domain.Catalog.CategoryLayout).Name });- if (!layout.Any()) return NotFound();-- return Ok(layout.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from CategoryLayout", OperationId = "GetCategoryLayout")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(Domain.Catalog.CategoryLayout).Name }));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(CategoryLayout).Name });+ if (!layout.Any()) return NotFound();++ return Ok(layout.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from CategoryLayout", OperationId = "GetCategoryLayout")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(CategoryLayout).Name }));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CollectionController.cs b/src/API/Grand.Api/Controllers/OData/CollectionController.csindex aa8f8ef07..d19b1aeaf 100644--- a/src/API/Grand.Api/Controllers/OData/CollectionController.cs+++ b/src/API/Grand.Api/Controllers/OData/CollectionController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,114 +12,114 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Collection")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CollectionController : BaseODataController{- [Route("odata/Collection")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CollectionController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CollectionController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Collection by key", OperationId = "GetCollectionById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>(key));+ if (!collection.Any()) return NotFound();++ return Ok(collection);+ }++ [SwaggerOperation("Get entities from Collection", OperationId = "GetCollections")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>()));+ }++ [SwaggerOperation("Add new entity to Collection", OperationId = "InsertCollection")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] CollectionDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ model = await _mediator.Send(new AddCollectionCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in Collection", OperationId = "UpdateCollection")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Put([FromBody] CollectionDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>(model.Id));+ if (!collection.Any()) return NotFound();++ model = await _mediator.Send(new UpdateCollectionCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Partially update entity in Collection", OperationId = "PartiallyUpdateCollection")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CollectionDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");++ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>(key));+ if (!collection.Any()) return NotFound();++ var man = collection.FirstOrDefault();+ model.ApplyTo(man);+ await _mediator.Send(new UpdateCollectionCommand { Model = man });+ return Ok();+ }++ [SwaggerOperation("Delete entity in Collection", OperationId = "DeleteCollection")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;- public CollectionController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Collection by key", OperationId = "GetCollectionById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Domain.Catalog.Collection>(key));- if (!collection.Any()) return NotFound();-- return Ok(collection);- }-- [SwaggerOperation(summary: "Get entities from Collection", OperationId = "GetCollections")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<CollectionDto, Domain.Catalog.Collection>()));- }-- [SwaggerOperation(summary: "Add new entity to Collection", OperationId = "InsertCollection")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] CollectionDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- model = await _mediator.Send(new AddCollectionCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in Collection", OperationId = "UpdateCollection")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Put([FromBody] CollectionDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Domain.Catalog.Collection>(model.Id));- if (!collection.Any()) return NotFound();-- model = await _mediator.Send(new UpdateCollectionCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Partially update entity in Collection", OperationId = "PartiallyUpdateCollection")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CollectionDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Domain.Catalog.Collection>(key));- if (!collection.Any()) return NotFound();-- var man = collection.FirstOrDefault();- model.ApplyTo(man);- await _mediator.Send(new UpdateCollectionCommand { Model = man });- return Ok();- }-- [SwaggerOperation(summary: "Delete entity in Collection", OperationId = "DeleteCollection")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();-- var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Domain.Catalog.Collection>(key));- if (!collection.Any()) return NotFound();-- await _mediator.Send(new DeleteCollectionCommand { Model = collection.FirstOrDefault() });-- return Ok();- }+ if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();++ var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>(key));+ if (!collection.Any()) return NotFound();++ await _mediator.Send(new DeleteCollectionCommand { Model = collection.FirstOrDefault() });++ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CollectionLayoutController.cs b/src/API/Grand.Api/Controllers/OData/CollectionLayoutController.csindex 018cf2fa0..41ba933f8 100644--- a/src/API/Grand.Api/Controllers/OData/CollectionLayoutController.cs+++ b/src/API/Grand.Api/Controllers/OData/CollectionLayoutController.cs@@ -1,6 +1,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -8,46 +9,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/CollectionLayout")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CollectionLayoutController : BaseODataController{- [Route("odata/CollectionLayout")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CollectionLayoutController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CollectionLayoutController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from CollectionLayout by key", OperationId = "GetCollectionLayoutById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public CollectionLayoutController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from CollectionLayout by key", OperationId = "GetCollectionLayoutById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(Domain.Catalog.CollectionLayout).Name });- if (!layout.Any()) return NotFound();-- return Ok(layout.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from CollectionLayout", OperationId = "GetCollectionLayouts")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(Domain.Catalog.CollectionLayout).Name }));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(CollectionLayout).Name });+ if (!layout.Any()) return NotFound();++ return Ok(layout.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from CollectionLayout", OperationId = "GetCollectionLayouts")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(CollectionLayout).Name }));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CountryController.cs b/src/API/Grand.Api/Controllers/OData/CountryController.csindex a440f7c72..871a048f8 100644--- a/src/API/Grand.Api/Controllers/OData/CountryController.cs+++ b/src/API/Grand.Api/Controllers/OData/CountryController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Directory;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,47 +10,46 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Country")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CountryController : BaseODataController{- [Route("odata/Country")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CountryController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CountryController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Country by key", OperationId = "GetCountryById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public CountryController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Country by key", OperationId = "GetCountryById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Countries)) return Forbid();-- //Domain.Directory.Country- var country = await _mediator.Send(new GetGenericQuery<CountryDto, Domain.Directory.Country>(key));- if (!country.Any()) return NotFound();-- return Ok(country.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Country", OperationId = "GetCountries")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Countries)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<CountryDto, Domain.Directory.Country>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Countries)) return Forbid();++ //Domain.Directory.Country+ var country = await _mediator.Send(new GetGenericQuery<CountryDto, Country>(key));+ if (!country.Any()) return NotFound();++ return Ok(country.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Country", OperationId = "GetCountries")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Countries)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<CountryDto, Country>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CurrencyController.cs b/src/API/Grand.Api/Controllers/OData/CurrencyController.csindex 0db0044dc..c209addee 100644--- a/src/API/Grand.Api/Controllers/OData/CurrencyController.cs+++ b/src/API/Grand.Api/Controllers/OData/CurrencyController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Directory;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Currency")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CurrencyController : BaseODataController{- [Route("odata/Currency")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CurrencyController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CurrencyController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Currency by key", OperationId = "GetCurrencyById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public CurrencyController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Currency by key", OperationId = "GetCurrencyById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Currencies)) return Forbid();-- var currency = await _mediator.Send(new GetGenericQuery<CurrencyDto, Domain.Directory.Currency>(key));- if (!currency.Any()) return NotFound();-- return Ok(currency.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Currency", OperationId = "GetCurrencies")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Currencies)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<CurrencyDto, Domain.Directory.Currency>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Currencies)) return Forbid();++ var currency = await _mediator.Send(new GetGenericQuery<CurrencyDto, Currency>(key));+ if (!currency.Any()) return NotFound();++ return Ok(currency.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Currency", OperationId = "GetCurrencies")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Currencies)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<CurrencyDto, Currency>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CustomerController.cs b/src/API/Grand.Api/Controllers/OData/CustomerController.csindex 524e98be2..9adc14c37 100644--- a/src/API/Grand.Api/Controllers/OData/CustomerController.cs+++ b/src/API/Grand.Api/Controllers/OData/CustomerController.cs@@ -2,8 +2,8 @@using Grand.Api.DTOs.Customers;using Grand.Api.Queries.Models.Customers;using Grand.Business.Core.Interfaces.Common.Security;-using Grand.Business.Core.Utilities.Common.Security;using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Common.Security;using Grand.Business.Core.Utilities.Customers;using Grand.Domain.Customers;using MediatR;@@ -11,167 +11,167 @@ using Microsoft.AspNetCore.Mvc;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Customer")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CustomerController : BaseODataController{- [Route("odata/Customer")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CustomerController : BaseODataController+ private readonly ICustomerManagerService _customerManagerService;++ private readonly CustomerSettings _customerSettings;+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CustomerController(+ IMediator mediator,+ IPermissionService permissionService,+ ICustomerManagerService customerManagerService,+ CustomerSettings customerSettings)+ {+ _mediator = mediator;+ _customerManagerService = customerManagerService;+ _customerSettings = customerSettings;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Customer by email", OperationId = "GetCustomerByEmail")]+ [HttpGet]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string email)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ var customer = await _mediator.Send(new GetCustomerQuery { Email = email });+ if (customer == null) return NotFound();++ return Ok(customer);+ }++ [SwaggerOperation("Add new entity to Customer", OperationId = "InsertCustomer")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] CustomerDto model){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;- private readonly ICustomerManagerService _customerManagerService;-- private readonly CustomerSettings _customerSettings;-- public CustomerController(- IMediator mediator,- IPermissionService permissionService,- ICustomerManagerService customerManagerService,- CustomerSettings customerSettings)- {- _mediator = mediator;- _customerManagerService = customerManagerService;- _customerSettings = customerSettings;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Customer by email", OperationId = "GetCustomerByEmail")]- [HttpGet]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string email)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- var customer = await _mediator.Send(new GetCustomerQuery { Email = email });- if (customer == null) return NotFound();-- return Ok(customer);- }-- [SwaggerOperation(summary: "Add new entity to Customer", OperationId = "InsertCustomer")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] CustomerDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- model = await _mediator.Send(new AddCustomerCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in Customer", OperationId = "UpdateCustomer")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Put([FromBody] CustomerDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- model = await _mediator.Send(new UpdateCustomerCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Delete entity from Customer", OperationId = "DeleteCustomer")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete([FromRoute] string email)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- var customer = await _mediator.Send(new GetCustomerQuery { Email = email });- if (customer == null) return NotFound();-- await _mediator.Send(new DeleteCustomerCommand { Email = email });-- return Ok();- }-- //odata/Customer/email/AddAddress- [SwaggerOperation(summary: "Invoke action AddAddress", OperationId = "AddAddress")]- [HttpPost("/{email}/AddAddress")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> AddAddress([FromRoute] string email, [FromBody] AddressDto address)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- var customer = await _mediator.Send(new GetCustomerQuery { Email = email });- if (customer == null) return NotFound();-- address = await _mediator.Send(new AddCustomerAddressCommand { Customer = customer, Address = address });- return Ok(address);- }-- //odata/Customer/email/UpdateAddress- [SwaggerOperation(summary: "Invoke action UpdateAddress", OperationId = "UpdateAddress")]- [HttpPost("/{email}/UpdateAddress")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateAddress([FromRoute] string email, [FromBody] AddressDto address)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- var customer = await _mediator.Send(new GetCustomerQuery { Email = email });- if (customer == null) return NotFound();-- address = await _mediator.Send(new UpdateCustomerAddressCommand { Customer = customer, Address = address });-- return Ok(address);- }-- //odata/Customer/email/DeleteAddress- //body: { "addressId": "xxx" }- [SwaggerOperation(summary: "Invoke action DeleteAddress", OperationId = "DeleteAddress")]- [HttpPost("/{email}/DeleteAddress")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteAddress([FromRoute] string email, [FromBody] DeleteAddressDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- if (model == null || string.IsNullOrEmpty(model.AddressId)) return NotFound();-- var customer = await _mediator.Send(new GetCustomerQuery { Email = email });- if (customer == null) return NotFound();-- var address = customer.Addresses.FirstOrDefault(x => x.Id == model.AddressId);- if (address == null) return NotFound();-- await _mediator.Send(new DeleteCustomerAddressCommand { Customer = customer, Address = address });-- return Ok(true);- }-- //odata/Customer/email/SetPassword- //body: { "password": "123456" }- [SwaggerOperation(summary: "Invoke action SetPassword", OperationId = "SetPassword")]- [HttpPost("/{email}/SetPassword")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> SetPassword([FromRoute] string email, [FromBody] PasswordDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- if (model == null || string.IsNullOrEmpty(model.Password)) return NotFound();-- var changePassRequest = new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);- await _customerManagerService.ChangePassword(changePassRequest);-- return Ok(true);- }+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ model = await _mediator.Send(new AddCustomerCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in Customer", OperationId = "UpdateCustomer")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Put([FromBody] CustomerDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ model = await _mediator.Send(new UpdateCustomerCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Delete entity from Customer", OperationId = "DeleteCustomer")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete([FromRoute] string email)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ var customer = await _mediator.Send(new GetCustomerQuery { Email = email });+ if (customer == null) return NotFound();++ await _mediator.Send(new DeleteCustomerCommand { Email = email });++ return Ok();+ }++ //odata/Customer/email/AddAddress+ [SwaggerOperation("Invoke action AddAddress", OperationId = "AddAddress")]+ [HttpPost("/{email}/AddAddress")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> AddAddress([FromRoute] string email, [FromBody] AddressDto address)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ var customer = await _mediator.Send(new GetCustomerQuery { Email = email });+ if (customer == null) return NotFound();++ address = await _mediator.Send(new AddCustomerAddressCommand { Customer = customer, Address = address });+ return Ok(address);+ }++ //odata/Customer/email/UpdateAddress+ [SwaggerOperation("Invoke action UpdateAddress", OperationId = "UpdateAddress")]+ [HttpPost("/{email}/UpdateAddress")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateAddress([FromRoute] string email, [FromBody] AddressDto address)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ var customer = await _mediator.Send(new GetCustomerQuery { Email = email });+ if (customer == null) return NotFound();++ address = await _mediator.Send(new UpdateCustomerAddressCommand { Customer = customer, Address = address });++ return Ok(address);+ }++ //odata/Customer/email/DeleteAddress+ //body: { "addressId": "xxx" }+ [SwaggerOperation("Invoke action DeleteAddress", OperationId = "DeleteAddress")]+ [HttpPost("/{email}/DeleteAddress")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteAddress([FromRoute] string email, [FromBody] DeleteAddressDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ if (model == null || string.IsNullOrEmpty(model.AddressId)) return NotFound();++ var customer = await _mediator.Send(new GetCustomerQuery { Email = email });+ if (customer == null) return NotFound();++ var address = customer.Addresses.FirstOrDefault(x => x.Id == model.AddressId);+ if (address == null) return NotFound();++ await _mediator.Send(new DeleteCustomerAddressCommand { Customer = customer, Address = address });++ return Ok(true);+ }++ //odata/Customer/email/SetPassword+ //body: { "password": "123456" }+ [SwaggerOperation("Invoke action SetPassword", OperationId = "SetPassword")]+ [HttpPost("/{email}/SetPassword")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> SetPassword([FromRoute] string email, [FromBody] PasswordDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ if (model == null || string.IsNullOrEmpty(model.Password)) return NotFound();++ var changePassRequest =+ new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);+ await _customerManagerService.ChangePassword(changePassRequest);++ return Ok(true);}}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/CustomerGroupController.cs b/src/API/Grand.Api/Controllers/OData/CustomerGroupController.csindex 34cf82f46..c510be1ff 100644--- a/src/API/Grand.Api/Controllers/OData/CustomerGroupController.cs+++ b/src/API/Grand.Api/Controllers/OData/CustomerGroupController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Customers;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Customers;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,125 +12,126 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/CustomerGroup")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class CustomerGroupController : BaseODataController{- [Route("odata/CustomerGroup")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class CustomerGroupController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public CustomerGroupController(IMediator mediator, IPermissionService permissionService){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;+ _mediator = mediator;+ _permissionService = permissionService;+ }- public CustomerGroupController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }+ [SwaggerOperation("Get entity from CustomerGroup by key", OperationId = "GetCustomerGroupById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();- [SwaggerOperation(summary: "Get entity from CustomerGroup by key", OperationId = "GetCustomerGroupById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();+ var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(key));+ if (!customerGroup.Any()) return NotFound();- var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>(key));- if (!customerGroup.Any()) return NotFound();+ return Ok(customerGroup.FirstOrDefault());+ }- return Ok(customerGroup.FirstOrDefault());- }+ [SwaggerOperation("Get entities from CustomerGroup", OperationId = "GetCustomerGroups")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();- [SwaggerOperation(summary: "Get entities from CustomerGroup", OperationId = "GetCustomerGroups")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();+ return Ok(await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>()));+ }- return Ok(await _mediator.Send(new GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>()));- }+ [SwaggerOperation("Add new entity to CustomerGroup", OperationId = "InsertCustomerGroup")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] CustomerGroupDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();- [SwaggerOperation(summary: "Add new entity to CustomerGroup", OperationId = "InsertCustomerGroup")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] CustomerGroupDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();+ model = await _mediator.Send(new AddCustomerGroupCommand { Model = model });+ return Ok(model);+ }- model = await _mediator.Send(new AddCustomerGroupCommand { Model = model });+ [SwaggerOperation("Update entity in CustomerGroup", OperationId = "UpdateCustomerGroup")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Put([FromBody] CustomerGroupDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();++ var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(model.Id));+ if (!customerGroup.Any()) return NotFound();++ if (!model.IsSystem)+ {+ model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model });return Ok(model);}- [SwaggerOperation(summary: "Update entity in CustomerGroup", OperationId = "UpdateCustomerGroup")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Put([FromBody] CustomerGroupDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();+ return BadRequest(ModelState);+ }- var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>(model.Id));- if (!customerGroup.Any()) return NotFound();+ [SwaggerOperation("Partially update entity in CustomerGroup", OperationId = "PartiallyUpdateCustomerGroup")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CustomerGroupDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");- if (!model.IsSystem)- {- model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model });- return Ok(model);- }- return BadRequest(ModelState);- }+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();- [SwaggerOperation(summary: "Partially update entity in CustomerGroup", OperationId = "PartiallyUpdateCustomerGroup")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<CustomerGroupDto> model)+ var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(key));+ if (!customerGroup.Any()) return NotFound();++ var cr = customerGroup.FirstOrDefault();+ model.ApplyTo(cr);+ if (cr is { IsSystem: false }){- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();-- var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>(key));- if (!customerGroup.Any()) return NotFound();-- var cr = customerGroup.FirstOrDefault();- model.ApplyTo(cr);- if (cr is { IsSystem: false })- {- await _mediator.Send(new UpdateCustomerGroupCommand { Model = cr });- return Ok();- }- return BadRequest(ModelState);+ await _mediator.Send(new UpdateCustomerGroupCommand { Model = cr });+ return Ok();}- [SwaggerOperation(summary: "Delete entity in CustomerGroup", OperationId = "DeleteCustomerGroup")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();+ return BadRequest(ModelState);+ }- var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>(key));- if (!customerGroup.Any()) return NotFound();+ [SwaggerOperation("Delete entity in CustomerGroup", OperationId = "DeleteCustomerGroup")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();- if (customerGroup.FirstOrDefault()!.IsSystem) return Forbid();+ var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(key));+ if (!customerGroup.Any()) return NotFound();- await _mediator.Send(new DeleteCustomerGroupCommand { Model = customerGroup.FirstOrDefault() });+ if (customerGroup.FirstOrDefault()!.IsSystem) return Forbid();- return Ok();- }+ await _mediator.Send(new DeleteCustomerGroupCommand { Model = customerGroup.FirstOrDefault() });++ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/DeliveryDateController.cs b/src/API/Grand.Api/Controllers/OData/DeliveryDateController.csindex 0c318de16..3ce8a783b 100644--- a/src/API/Grand.Api/Controllers/OData/DeliveryDateController.cs+++ b/src/API/Grand.Api/Controllers/OData/DeliveryDateController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Shipping;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/DeliveryDate")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class DeliveryDateController : BaseODataController{- [Route("odata/DeliveryDate")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class DeliveryDateController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public DeliveryDateController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Delivery Date by key", OperationId = "GetDeliveryDateById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public DeliveryDateController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Delivery Date by key", OperationId = "GetDeliveryDateById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- var deliverydate = await _mediator.Send(new GetGenericQuery<DeliveryDateDto, Domain.Shipping.DeliveryDate>(key));- if (!deliverydate.Any()) return NotFound();-- return Ok(deliverydate.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Delivery Date", OperationId = "GetDeliveryDates")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<DeliveryDateDto, Domain.Shipping.DeliveryDate>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ var deliverydate = await _mediator.Send(new GetGenericQuery<DeliveryDateDto, DeliveryDate>(key));+ if (!deliverydate.Any()) return NotFound();++ return Ok(deliverydate.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Delivery Date", OperationId = "GetDeliveryDates")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<DeliveryDateDto, DeliveryDate>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/LanguageController.cs b/src/API/Grand.Api/Controllers/OData/LanguageController.csindex 553f222f3..1316202a2 100644--- a/src/API/Grand.Api/Controllers/OData/LanguageController.cs+++ b/src/API/Grand.Api/Controllers/OData/LanguageController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Localization;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Language")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class LanguageController : BaseODataController{- [Route("odata/Language")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class LanguageController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public LanguageController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Languages by key", OperationId = "GetLanguageById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public LanguageController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Languages by key", OperationId = "GetLanguageById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Languages)) return Forbid();-- var language = await _mediator.Send(new GetGenericQuery<LanguageDto, Domain.Localization.Language>(key));- if (!language.Any()) return NotFound();-- return Ok(language.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Languages", OperationId = "GetLanguages")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Languages)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<LanguageDto, Domain.Localization.Language>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Languages)) return Forbid();++ var language = await _mediator.Send(new GetGenericQuery<LanguageDto, Language>(key));+ if (!language.Any()) return NotFound();++ return Ok(language.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Languages", OperationId = "GetLanguages")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Languages)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<LanguageDto, Language>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/PickupPointController.cs b/src/API/Grand.Api/Controllers/OData/PickupPointController.csindex 520aff3c7..e3284651d 100644--- a/src/API/Grand.Api/Controllers/OData/PickupPointController.cs+++ b/src/API/Grand.Api/Controllers/OData/PickupPointController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Shipping;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/PickupPoint")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class PickupPointController : BaseODataController{- [Route("odata/PickupPoint")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class PickupPointController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public PickupPointController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from PickupPoint by key", OperationId = "GetPickupPointById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public PickupPointController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from PickupPoint by key", OperationId = "GetPickupPointById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- var points = await _mediator.Send(new GetGenericQuery<PickupPointDto, Domain.Shipping.PickupPoint>(key));- if (!points.Any()) return NotFound();-- return Ok(points.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from PickupPoint", OperationId = "GetPickupPoints")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<PickupPointDto, Domain.Shipping.PickupPoint>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ var points = await _mediator.Send(new GetGenericQuery<PickupPointDto, PickupPoint>(key));+ if (!points.Any()) return NotFound();++ return Ok(points.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from PickupPoint", OperationId = "GetPickupPoints")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<PickupPointDto, PickupPoint>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/PictureController.cs b/src/API/Grand.Api/Controllers/OData/PictureController.csindex 3ddb0ebca..3bd681947 100644--- a/src/API/Grand.Api/Controllers/OData/PictureController.cs+++ b/src/API/Grand.Api/Controllers/OData/PictureController.cs@@ -3,85 +3,85 @@ using Grand.Api.DTOs.Common;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Media;using MediatR;using Microsoft.AspNetCore.Mvc;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Picture")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class PictureController : BaseODataController{- [Route("odata/Picture")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class PictureController : BaseODataController- {- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;- public PictureController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }+ public PictureController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }- [SwaggerOperation(summary: "Get entities from Picture by key", OperationId = "GetPictureById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();+ [SwaggerOperation("Get entities from Picture by key", OperationId = "GetPictureById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();- var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Domain.Media.Picture>(key));- if (picture == null || !picture.Any()) return NotFound();+ var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Picture>(key));+ if (picture == null || !picture.Any()) return NotFound();- return Ok(picture.FirstOrDefault());- }+ return Ok(picture.FirstOrDefault());+ }- [SwaggerOperation(summary: "Add new entity in Picture", OperationId = "InsertPicture")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] PictureDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();+ [SwaggerOperation("Add new entity in Picture", OperationId = "InsertPicture")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] PictureDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();- model = await _mediator.Send(new AddPictureCommand { PictureDto = model });- return Ok(model);- }+ model = await _mediator.Send(new AddPictureCommand { PictureDto = model });+ return Ok(model);+ }- [SwaggerOperation(summary: "Update entity in Picture", OperationId = "UpdatePicture")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Put([FromBody] PictureDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();+ [SwaggerOperation("Update entity in Picture", OperationId = "UpdatePicture")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Put([FromBody] PictureDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();- var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Domain.Media.Picture>(model.Id));- if (picture == null || !picture.Any()) return NotFound();+ var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Picture>(model.Id));+ if (picture == null || !picture.Any()) return NotFound();- var result = await _mediator.Send(new UpdatePictureCommand { Model = model });- return Ok(result);- }+ var result = await _mediator.Send(new UpdatePictureCommand { Model = model });+ return Ok(result);+ }- [SwaggerOperation(summary: "Delete entity in Picture", OperationId = "DeletePicture")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();+ [SwaggerOperation("Delete entity in Picture", OperationId = "DeletePicture")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();- var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Domain.Media.Picture>(key));- if (picture == null || !picture.Any()) return NotFound();+ var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Picture>(key));+ if (picture == null || !picture.Any()) return NotFound();- await _mediator.Send(new DeletePictureCommand { PictureDto = picture.FirstOrDefault() });- return Ok();- }+ await _mediator.Send(new DeletePictureCommand { PictureDto = picture.FirstOrDefault() });+ return Ok();}}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/ProductAttributeController.cs b/src/API/Grand.Api/Controllers/OData/ProductAttributeController.csindex 84d424b0d..229587230 100644--- a/src/API/Grand.Api/Controllers/OData/ProductAttributeController.cs+++ b/src/API/Grand.Api/Controllers/OData/ProductAttributeController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,112 +12,112 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/ProductAttribute")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class ProductAttributeController : BaseODataController{- [Route("odata/ProductAttribute")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class ProductAttributeController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public ProductAttributeController(+ IMediator mediator,+ IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from ProductAttribute by key", OperationId = "GetProductAttributeById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, ProductAttribute>(key));+ if (!productAttribute.Any()) return NotFound();++ return Ok(productAttribute.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from ProductAttribute", OperationId = "GetProductAttributes")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<ProductAttributeDto, ProductAttribute>()));+ }++ [SwaggerOperation("Add new entity to ProductAttribute", OperationId = "InsertProductAttribute")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] ProductAttributeDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ model = await _mediator.Send(new AddProductAttributeCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in ProductAttribute", OperationId = "UpdateProductAttribute")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Put([FromBody] ProductAttributeDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ model = await _mediator.Send(new UpdateProductAttributeCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Partially update entity in ProductAttribute", OperationId = "PartiallyUpdateProductAttribute")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key,+ [FromBody] JsonPatchDocument<ProductAttributeDto> model){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public ProductAttributeController(- IMediator mediator,- IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from ProductAttribute by key", OperationId = "GetProductAttributeById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, Domain.Catalog.ProductAttribute>(key));- if (!productAttribute.Any()) return NotFound();-- return Ok(productAttribute.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from ProductAttribute", OperationId = "GetProductAttributes")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<ProductAttributeDto, Domain.Catalog.ProductAttribute>()));- }-- [SwaggerOperation(summary: "Add new entity to ProductAttribute", OperationId = "InsertProductAttribute")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] ProductAttributeDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- model = await _mediator.Send(new AddProductAttributeCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in ProductAttribute", OperationId = "UpdateProductAttribute")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Put([FromBody] ProductAttributeDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- model = await _mediator.Send(new UpdateProductAttributeCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Partially update entity in ProductAttribute", OperationId = "PartiallyUpdateProductAttribute")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<ProductAttributeDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, Domain.Catalog.ProductAttribute>(key));- if (!productAttribute.Any()) return NotFound();-- var pa = productAttribute.FirstOrDefault();- model.ApplyTo(pa);- pa = await _mediator.Send(new UpdateProductAttributeCommand { Model = pa });- return Ok(pa);- }-- [SwaggerOperation(summary: "Delete entity from ProductAttribute", OperationId = "DeleteProductAttribute")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();-- var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, Domain.Catalog.ProductAttribute>(key));- if (!productAttribute.Any()) return NotFound();-- await _mediator.Send(new DeleteProductAttributeCommand { Model = productAttribute.FirstOrDefault() });- return Ok();- }+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");++ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, ProductAttribute>(key));+ if (!productAttribute.Any()) return NotFound();++ var pa = productAttribute.FirstOrDefault();+ model.ApplyTo(pa);+ pa = await _mediator.Send(new UpdateProductAttributeCommand { Model = pa });+ return Ok(pa);+ }++ [SwaggerOperation("Delete entity from ProductAttribute", OperationId = "DeleteProductAttribute")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();++ var productAttribute = await _mediator.Send(new GetGenericQuery<ProductAttributeDto, ProductAttribute>(key));+ if (!productAttribute.Any()) return NotFound();++ await _mediator.Send(new DeleteProductAttributeCommand { Model = productAttribute.FirstOrDefault() });+ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/ProductController.cs b/src/API/Grand.Api/Controllers/OData/ProductController.csindex 2bd584896..df16d09ec 100644--- a/src/API/Grand.Api/Controllers/OData/ProductController.cs+++ b/src/API/Grand.Api/Controllers/OData/ProductController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,652 +12,720 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Product")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class ProductController : BaseODataController{- [Route("odata/Product")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class ProductController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public ProductController(+ IMediator mediator,+ IPermissionService permissionService){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;+ _mediator = mediator;+ _permissionService = permissionService;+ }- public ProductController(- IMediator mediator,- IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }+ [SwaggerOperation("Get entity from Product by key", OperationId = "GetProductById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Get entity from Product by key", OperationId = "GetProductById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ return Ok(product.FirstOrDefault());+ }- return Ok(product.FirstOrDefault());- }+ [SwaggerOperation("Get entities from Product", OperationId = "GetProducts")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Get entities from Product", OperationId = "GetProducts")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return Ok(await _mediator.Send(new GetGenericQuery<ProductDto, Product>()));+ }- return Ok(await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>()));- }+ [SwaggerOperation("Add new entity to Product", OperationId = "InsertProduct")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] ProductDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Add new entity to Product", OperationId = "InsertProduct")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] ProductDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ model = await _mediator.Send(new AddProductCommand { Model = model });+ return Ok(model);+ }- model = await _mediator.Send(new AddProductCommand { Model = model });- return Ok(model);- }+ [SwaggerOperation("Update entity in Product", OperationId = "UpdateProduct")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Put([FromBody] ProductDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Update entity in Product", OperationId = "UpdateProduct")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Put([FromBody] ProductDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ await _mediator.Send(new UpdateProductCommand { Model = model });+ return Ok();+ }- await _mediator.Send(new UpdateProductCommand { Model = model });- return Ok();- }+ [SwaggerOperation("Partially update entity in Product", OperationId = "PartiallyUpdateProduct")]+ [HttpPatch]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<ProductDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");- [SwaggerOperation(summary: "Partially update entity in Product", OperationId = "PartiallyUpdateProduct")]- [HttpPatch]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<ProductDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();-- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();-- var pr = product.FirstOrDefault();- model.ApplyTo(pr);- await _mediator.Send(new UpdateProductCommand { Model = pr });- return Ok();- }+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Delete entity in Product", OperationId = "DeleteProduct")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var pr = product.FirstOrDefault();+ model.ApplyTo(pr);+ await _mediator.Send(new UpdateProductCommand { Model = pr });+ return Ok();+ }- await _mediator.Send(new DeleteProductCommand { Model = product.FirstOrDefault() });+ [SwaggerOperation("Delete entity in Product", OperationId = "DeleteProduct")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- return Ok();- }+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- //odata/Product/id/UpdateStock- //body: { "WarehouseId": "", "Stock": 10 }- [SwaggerOperation(summary: "Invoke action UpdateStock", OperationId = "UpdateStock")]- [HttpPost("/{key}/UpdateStock")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateStock([FromRoute] string key, [FromBody] ProductUpdateStock model)- {- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ await _mediator.Send(new DeleteProductCommand { Model = product.FirstOrDefault() });- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ return Ok();+ }- if (model == null) return BadRequest();+ //odata/Product/id/UpdateStock+ //body: { "WarehouseId": "", "Stock": 10 }+ [SwaggerOperation("Invoke action UpdateStock", OperationId = "UpdateStock")]+ [HttpPost("/{key}/UpdateStock")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateStock([FromRoute] string key, [FromBody] ProductUpdateStock model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- await _mediator.Send(new UpdateProductStockCommand { Product = product.FirstOrDefault(), WarehouseId = model.WarehouseId, Stock = model.Stock });+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- return Ok(true);- }+ if (model == null) return BadRequest();- #region Product category+ await _mediator.Send(new UpdateProductStockCommand+ { Product = product.FirstOrDefault(), WarehouseId = model.WarehouseId, Stock = model.Stock });- [SwaggerOperation(summary: "Invoke action CreateProductCategory", OperationId = "CreateProductCategory")]- [HttpPost("/{key}/CreateProductCategory")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductCategory([FromRoute] string key, [FromBody] ProductCategoryDto productCategory)- {- if (productCategory == null) return BadRequest();+ return Ok(true);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #region Product category- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ [SwaggerOperation("Invoke action CreateProductCategory", OperationId = "CreateProductCategory")]+ [HttpPost("/{key}/CreateProductCategory")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductCategory([FromRoute] string key,+ [FromBody] ProductCategoryDto productCategory)+ {+ if (productCategory == null) return BadRequest();- var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => x.CategoryId == productCategory.CategoryId);- if (pc != null) return BadRequest("Product category mapping found with the specified CategoryId");+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory });- return Ok(result);- }- return BadRequest(ModelState);+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();++ var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x =>+ x.CategoryId == productCategory.CategoryId);+ if (pc != null) return BadRequest("Product category mapping found with the specified CategoryId");++ if (ModelState.IsValid)+ {+ var result = await _mediator.Send(new AddProductCategoryCommand+ { Product = product.FirstOrDefault(), Model = productCategory });+ return Ok(result);}- [SwaggerOperation(summary: "Invoke action UpdateProductCategory", OperationId = "UpdateProductCategory")]- [HttpPost("/{key}/UpdateProductCategory")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductCategory([FromRoute] string key, [FromBody] ProductCategoryDto productCategory)+ return BadRequest(ModelState);+ }++ [SwaggerOperation("Invoke action UpdateProductCategory", OperationId = "UpdateProductCategory")]+ [HttpPost("/{key}/UpdateProductCategory")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductCategory([FromRoute] string key,+ [FromBody] ProductCategoryDto productCategory)+ {+ if (productCategory == null) return BadRequest();++ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();++ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();++ var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x =>+ x.CategoryId == productCategory.CategoryId);+ if (pc == null) return BadRequest("No product category mapping found with the specified id");++ if (ModelState.IsValid){- if (productCategory == null) return BadRequest();+ var result = await _mediator.Send(new UpdateProductCategoryCommand+ { Product = product.FirstOrDefault(), Model = productCategory });+ return Ok(result);+ }++ return BadRequest(ModelState);+ }++ [SwaggerOperation("Invoke action DeleteProductCategory", OperationId = "DeleteProductCategory")]+ [HttpPost("/{key}/DeleteProductCategory")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductCategory([FromRoute] string key,+ [FromBody] ProductCategoryDeleteDto model)+ {+ if (model == null) return BadRequest();- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => x.CategoryId == productCategory.CategoryId);+ var categoryId = model.CategoryId;+ if (!string.IsNullOrEmpty(categoryId))+ {+ var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => x.CategoryId == categoryId);if (pc == null) return BadRequest("No product category mapping found with the specified id");if (ModelState.IsValid){- var result = await _mediator.Send(new UpdateProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory });- return Ok(result);+ _ = await _mediator.Send(new DeleteProductCategoryCommand+ { Product = product.FirstOrDefault(), CategoryId = categoryId });+ return Ok(true);}+return BadRequest(ModelState);}- [SwaggerOperation(summary: "Invoke action DeleteProductCategory", OperationId = "DeleteProductCategory")]- [HttpPost("/{key}/DeleteProductCategory")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductCategory([FromRoute] string key, [FromBody] ProductCategoryDeleteDto model)- {- if (model == null) return BadRequest();+ return NotFound();+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #endregion- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ #region Product collection- var categoryId = model.CategoryId;- if (!string.IsNullOrEmpty(categoryId))- {- var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => x.CategoryId == categoryId);- if (pc == null) return BadRequest("No product category mapping found with the specified id");-- if (ModelState.IsValid)- {- _ = await _mediator.Send(new DeleteProductCategoryCommand { Product = product.FirstOrDefault(), CategoryId = categoryId });- return Ok(true);- }- return BadRequest(ModelState);- }- return NotFound();- }+ [SwaggerOperation("Invoke action CreateProductCollection", OperationId = "CreateProductCollection")]+ [HttpPost("/{key}/CreateProductCollection")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductCollection([FromRoute] string key,+ [FromBody] ProductCollectionDto productCollection)+ {+ if (productCollection == null) return BadRequest();- #endregion+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- #region Product collection+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- [SwaggerOperation(summary: "Invoke action CreateProductCollection", OperationId = "CreateProductCollection")]- [HttpPost("/{key}/CreateProductCollection")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductCollection([FromRoute] string key, [FromBody] ProductCollectionDto productCollection)+ var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x =>+ x.CollectionId == productCollection.CollectionId);+ if (pm != null) return BadRequest("Product collection mapping found with the specified CollectionId");++ if (ModelState.IsValid){- if (productCollection == null) return BadRequest();+ var result = await _mediator.Send(new AddProductCollectionCommand+ { Product = product.FirstOrDefault(), Model = productCollection });+ return Ok(result);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return BadRequest(ModelState);+ }- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ [SwaggerOperation("Invoke action UpdateProductCollection", OperationId = "UpdateProductCollection")]+ [HttpPost("/{key}/UpdateProductCollection")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductCollection([FromRoute] string key,+ [FromBody] ProductCollectionDto productCollection)+ {+ if (productCollection == null) return BadRequest();- var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId);- if (pm != null) return BadRequest("Product collection mapping found with the specified CollectionId");+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection });- return Ok(result);- }- return BadRequest(ModelState);- }+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();++ var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x =>+ x.CollectionId == productCollection.CollectionId);+ if (pm == null) return BadRequest("No product collection mapping found with the specified id");- [SwaggerOperation(summary: "Invoke action UpdateProductCollection", OperationId = "UpdateProductCollection")]- [HttpPost("/{key}/UpdateProductCollection")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductCollection([FromRoute] string key, [FromBody] ProductCollectionDto productCollection)+ if (ModelState.IsValid){- if (productCollection == null) return BadRequest();+ var result = await _mediator.Send(new UpdateProductCollectionCommand+ { Product = product.FirstOrDefault(), Model = productCollection });+ return Ok(result);+ }++ return BadRequest(ModelState);+ }++ [SwaggerOperation("Invoke action DeleteProductCollection", OperationId = "DeleteProductCollection")]+ [HttpPost("/{key}/DeleteProductCollection")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductCollection([FromRoute] string key,+ [FromBody] ProductCollectionDeleteDto model)+ {+ if (model == null) return BadRequest();- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId);+ var collectionId = model.CollectionId;+ if (!string.IsNullOrEmpty(collectionId))+ {+ var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == collectionId);if (pm == null) return BadRequest("No product collection mapping found with the specified id");if (ModelState.IsValid){- var result = await _mediator.Send(new UpdateProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection });- return Ok(result);+ await _mediator.Send(new DeleteProductCollectionCommand+ { Product = product.FirstOrDefault(), CollectionId = collectionId });+ return Ok(true);}+return BadRequest(ModelState);}- [SwaggerOperation(summary: "Invoke action DeleteProductCollection", OperationId = "DeleteProductCollection")]- [HttpPost("/{key}/DeleteProductCollection")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductCollection([FromRoute] string key, [FromBody] ProductCollectionDeleteDto model)- {- if (model == null) return BadRequest();+ return NotFound();+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #endregion- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ #region Product picture- var collectionId = model.CollectionId;- if (!string.IsNullOrEmpty(collectionId))- {- var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == collectionId);- if (pm == null) return BadRequest("No product collection mapping found with the specified id");-- if (ModelState.IsValid)- {- await _mediator.Send(new DeleteProductCollectionCommand { Product = product.FirstOrDefault(), CollectionId = collectionId });- return Ok(true);- }- return BadRequest(ModelState);- }- return NotFound();- }+ [SwaggerOperation("Invoke action CreateProductPicture", OperationId = "CreateProductPicture")]+ [HttpPost("/{key}/CreateProductPicture")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductPicture([FromRoute] string key,+ [FromBody] ProductPictureDto productPicture)+ {+ if (productPicture == null) return BadRequest();- #endregion+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- #region Product picture+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- [SwaggerOperation(summary: "Invoke action CreateProductPicture", OperationId = "CreateProductPicture")]- [HttpPost("/{key}/CreateProductPicture")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductPicture([FromRoute] string key, [FromBody] ProductPictureDto productPicture)+ var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId);+ if (pp != null) return BadRequest("Product picture mapping found with the specified pictureid");++ if (ModelState.IsValid){- if (productPicture == null) return BadRequest();+ var result = await _mediator.Send(new AddProductPictureCommand+ { Product = product.FirstOrDefault(), Model = productPicture });+ return Ok(result);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return BadRequest(ModelState);+ }- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ [SwaggerOperation("Invoke action UpdateProductPicture", OperationId = "UpdateProductPicture")]+ [HttpPost("/{key}/UpdateProductPicture")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductPicture([FromRoute] string key,+ [FromBody] ProductPictureDto productPicture)+ {+ if (productPicture == null) return BadRequest();- var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId);- if (pp != null) return BadRequest("Product picture mapping found with the specified pictureid");+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture });- return Ok(result);- }- return BadRequest(ModelState);- }+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();++ var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId);+ if (pp == null) return BadRequest("No product picture mapping found with the specified id");- [SwaggerOperation(summary: "Invoke action UpdateProductPicture", OperationId = "UpdateProductPicture")]- [HttpPost("/{key}/UpdateProductPicture")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductPicture([FromRoute] string key, [FromBody] ProductPictureDto productPicture)+ if (ModelState.IsValid){- if (productPicture == null) return BadRequest();+ var result = await _mediator.Send(new UpdateProductPictureCommand+ { Product = product.FirstOrDefault(), Model = productPicture });+ return Ok(result);+ }++ return BadRequest(ModelState);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ [SwaggerOperation("Invoke action DeleteProductPicture", OperationId = "DeleteProductPicture")]+ [HttpPost("/{key}/DeleteProductPicture")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductPicture([FromRoute] string key,+ [FromBody] ProductPictureDeleteDto model)+ {+ if (model == null) return BadRequest();++ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId);+ var pictureId = model.PictureId;+ if (!string.IsNullOrEmpty(pictureId))+ {+ var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == pictureId);if (pp == null) return BadRequest("No product picture mapping found with the specified id");if (ModelState.IsValid){- var result = await _mediator.Send(new UpdateProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture });+ var result = await _mediator.Send(new DeleteProductPictureCommand+ { Product = product.FirstOrDefault(), PictureId = pictureId });return Ok(result);}+return BadRequest(ModelState);}- [SwaggerOperation(summary: "Invoke action DeleteProductPicture", OperationId = "DeleteProductPicture")]- [HttpPost("/{key}/DeleteProductPicture")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductPicture([FromRoute] string key, [FromBody] ProductPictureDeleteDto model)- {- if (model == null) return BadRequest();+ return NotFound();+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #endregion- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ #region Product specification- var pictureId = model.PictureId;- if (!string.IsNullOrEmpty(pictureId))- {- var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == pictureId);- if (pp == null) return BadRequest("No product picture mapping found with the specified id");-- if (ModelState.IsValid)- {- var result = await _mediator.Send(new DeleteProductPictureCommand { Product = product.FirstOrDefault(), PictureId = pictureId });- return Ok(result);- }- return BadRequest(ModelState);- }- return NotFound();- }+ [SwaggerOperation("Invoke action CreateProductSpecification", OperationId = "CreateProductSpecification")]+ [HttpPost("/{key}/CreateProductSpecification")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductSpecification([FromRoute] string key,+ [FromBody] ProductSpecificationAttributeDto productSpecification)+ {+ if (productSpecification == null) return BadRequest();++ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- #endregion+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- #region Product specification+ var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x =>+ x.Id == productSpecification.Id);+ if (psa != null) return BadRequest("Product specification mapping found with the specified id");- [SwaggerOperation(summary: "Invoke action CreateProductSpecification", OperationId = "CreateProductSpecification")]- [HttpPost("/{key}/CreateProductSpecification")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDto productSpecification)+ if (ModelState.IsValid){- if (productSpecification == null) return BadRequest();+ var result = await _mediator.Send(new AddProductSpecificationCommand+ { Product = product.FirstOrDefault(), Model = productSpecification });+ return Ok(result);+ }++ return BadRequest(ModelState);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ [SwaggerOperation("Invoke action UpdateProductSpecification", OperationId = "UpdateProductSpecification")]+ [HttpPost("/{key}/UpdateProductSpecification")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductSpecification([FromRoute] string key,+ [FromBody] ProductSpecificationAttributeDto productSpecification)+ {+ if (productSpecification == null) return BadRequest();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == productSpecification.Id);- if (psa != null) return BadRequest("Product specification mapping found with the specified id");+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification });- return Ok(result);- }- return BadRequest(ModelState);- }+ var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x =>+ x.Id == productSpecification.Id);+ if (psa == null) return BadRequest("No product specification mapping found with the specified id");- [SwaggerOperation(summary: "Invoke action UpdateProductSpecification", OperationId = "UpdateProductSpecification")]- [HttpPost("/{key}/UpdateProductSpecification")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDto productSpecification)+ if (ModelState.IsValid){- if (productSpecification == null) return BadRequest();+ var result = await _mediator.Send(new UpdateProductSpecificationCommand+ { Product = product.FirstOrDefault(), Model = productSpecification });+ return Ok(result);+ }++ return BadRequest(ModelState);+ }++ [SwaggerOperation("Invoke action DeleteProductSpecification", OperationId = "DeleteProductSpecification")]+ [HttpPost("/{key}/DeleteProductSpecification")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductSpecification([FromRoute] string key,+ [FromBody] ProductSpecificationAttributeDeleteDto model)+ {+ if (model == null) return BadRequest();- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == productSpecification.Id);+ var specificationId = model.Id;+ if (!string.IsNullOrEmpty(specificationId))+ {+ var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x =>+ x.Id == specificationId);if (psa == null) return BadRequest("No product specification mapping found with the specified id");if (ModelState.IsValid){- var result = await _mediator.Send(new UpdateProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification });+ var result = await _mediator.Send(new DeleteProductSpecificationCommand+ { Product = product.FirstOrDefault(), Id = specificationId });return Ok(result);}+return BadRequest(ModelState);}- [SwaggerOperation(summary: "Invoke action DeleteProductSpecification", OperationId = "DeleteProductSpecification")]- [HttpPost("/{key}/DeleteProductSpecification")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDeleteDto model)- {- if (model == null) return BadRequest();+ return NotFound();+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #endregion- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ #region Product tierprice- var specificationId = model.Id;- if (!string.IsNullOrEmpty(specificationId))- {- var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == specificationId);- if (psa == null) return BadRequest("No product specification mapping found with the specified id");-- if (ModelState.IsValid)- {- var result = await _mediator.Send(new DeleteProductSpecificationCommand { Product = product.FirstOrDefault(), Id = specificationId });- return Ok(result);- }- return BadRequest(ModelState);- }- return NotFound();- }+ [SwaggerOperation("Invoke action CreateProductTierPrice", OperationId = "CreateProductTierPrice")]+ [HttpPost("/{key}/CreateProductTierPrice")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductTierPrice([FromRoute] string key,+ [FromBody] ProductTierPriceDto productTierPrice)+ {+ if (productTierPrice == null) return BadRequest();++ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- #endregion+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- #region Product tierprice+ var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id);+ if (pt != null) return BadRequest("Product tier price mapping found with the specified id");- [SwaggerOperation(summary: "Invoke action CreateProductTierPrice", OperationId = "CreateProductTierPrice")]- [HttpPost("/{key}/CreateProductTierPrice")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDto productTierPrice)+ if (ModelState.IsValid){- if (productTierPrice == null) return BadRequest();+ var result = await _mediator.Send(new AddProductTierPriceCommand+ { Product = product.FirstOrDefault(), Model = productTierPrice });+ return Ok(result);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return BadRequest(ModelState);+ }- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ [SwaggerOperation("Invoke action UpdateProductTierPrice", OperationId = "UpdateProductTierPrice")]+ [HttpPost("/{key}/UpdateProductTierPrice")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductTierPrice([FromRoute] string key,+ [FromBody] ProductTierPriceDto productTierPrice)+ {+ if (productTierPrice == null) return BadRequest();- var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id);- if (pt != null) return BadRequest("Product tier price mapping found with the specified id");+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice });- return Ok(result);- }- return BadRequest(ModelState);- }+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- [SwaggerOperation(summary: "Invoke action UpdateProductTierPrice", OperationId = "UpdateProductTierPrice")]- [HttpPost("/{key}/UpdateProductTierPrice")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDto productTierPrice)+ var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id);+ if (pt == null) return BadRequest("No product tier price mapping found with the specified id");++ if (ModelState.IsValid){- if (productTierPrice == null) return BadRequest();+ var result = await _mediator.Send(new UpdateProductTierPriceCommand+ { Product = product.FirstOrDefault(), Model = productTierPrice });+ return Ok(result);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return BadRequest(ModelState);+ }++ [SwaggerOperation("Invoke action DeleteProductTierPrice", OperationId = "DeleteProductTierPrice")]+ [HttpPost("/{key}/DeleteProductTierPrice")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductTierPrice([FromRoute] string key,+ [FromBody] ProductTierPriceDeleteDto model)+ {+ if (model == null) return BadRequest();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id);+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();++ var tierPriceId = model.Id;+ if (!string.IsNullOrEmpty(tierPriceId))+ {+ var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == tierPriceId);if (pt == null) return BadRequest("No product tier price mapping found with the specified id");if (ModelState.IsValid){- var result = await _mediator.Send(new UpdateProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice });+ var result = await _mediator.Send(new DeleteProductTierPriceCommand+ { Product = product.FirstOrDefault(), Id = tierPriceId });return Ok(result);}+return BadRequest(ModelState);}- [SwaggerOperation(summary: "Invoke action DeleteProductTierPrice", OperationId = "DeleteProductTierPrice")]- [HttpPost("/{key}/DeleteProductTierPrice")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDeleteDto model)- {- if (model == null) return BadRequest();+ return NotFound();+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ #endregion- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ #region Product attribute mapping- var tierPriceId = model.Id;- if (!string.IsNullOrEmpty(tierPriceId))- {- var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == tierPriceId);- if (pt == null) return BadRequest("No product tier price mapping found with the specified id");-- if (ModelState.IsValid)- {- var result = await _mediator.Send(new DeleteProductTierPriceCommand { Product = product.FirstOrDefault(), Id = tierPriceId });- return Ok(result);- }- return BadRequest(ModelState);- }- return NotFound();- }+ [SwaggerOperation("Invoke action CreateProductAttributeMapping", OperationId = "CreateProductAttributeMapping")]+ [HttpPost("/{key}/CreateProductAttributeMapping")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> CreateProductAttributeMapping([FromRoute] string key,+ [FromBody] ProductAttributeMappingDto productAttributeMapping)+ {+ if (productAttributeMapping == null) return BadRequest();- #endregion+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- #region Product attribute mapping+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- [SwaggerOperation(summary: "Invoke action CreateProductAttributeMapping", OperationId = "CreateProductAttributeMapping")]- [HttpPost("/{key}/CreateProductAttributeMapping")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> CreateProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDto productAttributeMapping)+ var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x =>+ x.Id == productAttributeMapping.Id);+ if (pam != null) return BadRequest("Product attribute mapping found with the specified id");++ if (ModelState.IsValid){- if (productAttributeMapping == null) return BadRequest();+ var result = await _mediator.Send(new AddProductAttributeMappingCommand+ { Product = product.FirstOrDefault(), Model = productAttributeMapping });+ return Ok(result);+ }- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ return BadRequest(ModelState);+ }- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ [SwaggerOperation("Invoke action UpdateProductAttributeMapping", OperationId = "UpdateProductAttributeMapping")]+ [HttpPost("/{key}/UpdateProductAttributeMapping")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> UpdateProductAttributeMapping([FromRoute] string key,+ [FromBody] ProductAttributeMappingDto productAttributeMapping)+ {+ if (productAttributeMapping == null) return BadRequest();- var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMapping.Id);- if (pam != null) return BadRequest("Product attribute mapping found with the specified id");+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new AddProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping });- return Ok(result);- }- return BadRequest(ModelState);- }+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- [SwaggerOperation(summary: "Invoke action UpdateProductAttributeMapping", OperationId = "UpdateProductAttributeMapping")]- [HttpPost("/{key}/UpdateProductAttributeMapping")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> UpdateProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDto productAttributeMapping)- {- if (productAttributeMapping == null) return BadRequest();+ var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x =>+ x.Id == productAttributeMapping.Id);+ if (pam == null) return BadRequest("No product attribute mapping found with the specified id");- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ if (ModelState.IsValid)+ {+ var result = await _mediator.Send(new UpdateProductAttributeMappingCommand+ { Product = product.FirstOrDefault(), Model = productAttributeMapping });+ return Ok(result);+ }- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ return BadRequest(ModelState);+ }- var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMapping.Id);- if (pam == null) return BadRequest("No product attribute mapping found with the specified id");+ [SwaggerOperation("Invoke action DeleteProductAttributeMapping", OperationId = "DeleteProductAttributeMapping")]+ [HttpPost("/{key}/DeleteProductAttributeMapping")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> DeleteProductAttributeMapping([FromRoute] string key,+ [FromBody] ProductAttributeMappingDeleteDto model)+ {+ if (model == null) return BadRequest();- if (ModelState.IsValid)- {- var result = await _mediator.Send(new UpdateProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping });- return Ok(result);- }- return BadRequest(ModelState);- }+ if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();- [SwaggerOperation(summary: "Invoke action DeleteProductAttributeMapping", OperationId = "DeleteProductAttributeMapping")]- [HttpPost("/{key}/DeleteProductAttributeMapping")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> DeleteProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDeleteDto model)- {- if (model == null) return BadRequest();+ var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));+ if (!product.Any()) return NotFound();- if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();+ var attrId = model.Id;+ if (string.IsNullOrEmpty(attrId)) return NotFound();- var product = await _mediator.Send(new GetGenericQuery<ProductDto, Domain.Catalog.Product>(key));- if (!product.Any()) return NotFound();+ var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => x.Id == attrId);+ if (pam == null) return BadRequest("No product attribute mapping found with the specified id");- var attrId = model.Id;- if (string.IsNullOrEmpty(attrId)) return NotFound();-- var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => x.Id == attrId);- if (pam == null) return BadRequest("No product attribute mapping found with the specified id");+ if (!ModelState.IsValid) return BadRequest(ModelState);- if (!ModelState.IsValid) return BadRequest(ModelState);-- var result = await _mediator.Send(new DeleteProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = pam });- return Ok(result);- }- #endregion+ var result = await _mediator.Send(new DeleteProductAttributeMappingCommand+ { Product = product.FirstOrDefault(), Model = pam });+ return Ok(result);}-}++ #endregion+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/ProductLayoutController.cs b/src/API/Grand.Api/Controllers/OData/ProductLayoutController.csindex c9fcc7076..5980c9e46 100644--- a/src/API/Grand.Api/Controllers/OData/ProductLayoutController.cs+++ b/src/API/Grand.Api/Controllers/OData/ProductLayoutController.cs@@ -1,6 +1,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -8,47 +9,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/ProductLayout")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class ProductLayoutController : BaseODataController{- [Route("odata/ProductLayout")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class ProductLayoutController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public ProductLayoutController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from ProductLayout by key", OperationId = "GetProductLayoutById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public ProductLayoutController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from ProductLayout by key", OperationId = "GetProductLayoutById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(Domain.Catalog.ProductLayout).Name });- if (!layout.Any()) return NotFound();-- return Ok(layout.FirstOrDefault());-- }-- [SwaggerOperation(summary: "Get entities from ProductTemplate", OperationId = "GetProductTemplates")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();-- return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(Domain.Catalog.ProductLayout).Name }));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ var layout = await _mediator.Send(new GetLayoutQuery { Id = key, LayoutName = typeof(ProductLayout).Name });+ if (!layout.Any()) return NotFound();++ return Ok(layout.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from ProductTemplate", OperationId = "GetProductTemplates")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();++ return Ok(await _mediator.Send(new GetLayoutQuery { LayoutName = typeof(ProductLayout).Name }));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/ShippingMethodController.cs b/src/API/Grand.Api/Controllers/OData/ShippingMethodController.csindex 3ee0c32ab..c646866d6 100644--- a/src/API/Grand.Api/Controllers/OData/ShippingMethodController.cs+++ b/src/API/Grand.Api/Controllers/OData/ShippingMethodController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Shipping;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/ShippingMethod")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class ShippingMethodController : BaseODataController{- [Route("odata/ShippingMethod")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class ShippingMethodController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public ShippingMethodController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from ShippingMethod by key", OperationId = "GetShippingMethodById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public ShippingMethodController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from ShippingMethod by key", OperationId = "GetShippingMethodById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- var shipping = await _mediator.Send(new GetGenericQuery<ShippingMethodDto, Domain.Shipping.ShippingMethod>(key));- if (!shipping.Any()) return NotFound();-- return Ok(shipping.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from ShippingMethod", OperationId = "GetShippingMethods")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<ShippingMethodDto, Domain.Shipping.ShippingMethod>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ var shipping = await _mediator.Send(new GetGenericQuery<ShippingMethodDto, ShippingMethod>(key));+ if (!shipping.Any()) return NotFound();++ return Ok(shipping.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from ShippingMethod", OperationId = "GetShippingMethods")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<ShippingMethodDto, ShippingMethod>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/SpecificationAttributeController.cs b/src/API/Grand.Api/Controllers/OData/SpecificationAttributeController.csindex e43e975f9..17e9abe2f 100644--- a/src/API/Grand.Api/Controllers/OData/SpecificationAttributeController.cs+++ b/src/API/Grand.Api/Controllers/OData/SpecificationAttributeController.cs@@ -3,6 +3,7 @@ using Grand.Api.DTOs.Catalog;using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Catalog;using MediatR;using Microsoft.AspNetCore.JsonPatch;using Microsoft.AspNetCore.Mvc;@@ -11,110 +12,115 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/SpecificationAttribute")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class SpecificationAttributeController : BaseODataController{- [Route("odata/SpecificationAttribute")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class SpecificationAttributeController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public SpecificationAttributeController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from SpecificationAttribute by key", OperationId = "GetSpecificationAttributeById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ var specificationAttribute =+ await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));+ if (!specificationAttribute.Any()) return NotFound();++ return Ok(specificationAttribute.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from SpecificationAttribute", OperationId = "GetSpecificationAttributes")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>()));+ }++ [SwaggerOperation("Add new entity to SpecificationAttribute", OperationId = "InsertSpecificationAttribute")]+ [HttpPost]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Post([FromBody] SpecificationAttributeDto model){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;- public SpecificationAttributeController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from SpecificationAttribute by key", OperationId = "GetSpecificationAttributeById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- var specificationAttribute = await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>(key));- if (!specificationAttribute.Any()) return NotFound();-- return Ok(specificationAttribute.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from SpecificationAttribute", OperationId = "GetSpecificationAttributes")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>()));- }-- [SwaggerOperation(summary: "Add new entity to SpecificationAttribute", OperationId = "InsertSpecificationAttribute")]- [HttpPost]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Post([FromBody] SpecificationAttributeDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- model = await _mediator.Send(new AddSpecificationAttributeCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Update entity in SpecificationAttribute", OperationId = "UpdateSpecificationAttribute")]- [HttpPut]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- public async Task<IActionResult> Put([FromBody] SpecificationAttributeDto model)- {- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- model = await _mediator.Send(new UpdateSpecificationAttributeCommand { Model = model });- return Ok(model);- }-- [SwaggerOperation(summary: "Partially update entity in SpecificationAttribute", OperationId = "PartiallyUpdateSpecificationAttribute")]- [HttpPatch("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.BadRequest)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<SpecificationAttributeDto> model)- {- if (string.IsNullOrEmpty(key))- return BadRequest("Key is null or empty");-- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- var specification = await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>(key));- if (!specification.Any()) return NotFound();-- var spec = specification.FirstOrDefault();- model.ApplyTo(spec);- await _mediator.Send(new UpdateSpecificationAttributeCommand { Model = spec });- return Ok();- }-- [SwaggerOperation(summary: "Delete entity in SpecificationAttribute", OperationId = "DeleteSpecificationAttribute")]- [HttpDelete]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Delete(string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();-- var specification = await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>(key));- if (!specification.Any()) return NotFound();-- await _mediator.Send(new DeleteSpecificationAttributeCommand { Model = specification.FirstOrDefault() });-- return Ok();- }+ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ model = await _mediator.Send(new AddSpecificationAttributeCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Update entity in SpecificationAttribute", OperationId = "UpdateSpecificationAttribute")]+ [HttpPut]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ public async Task<IActionResult> Put([FromBody] SpecificationAttributeDto model)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ model = await _mediator.Send(new UpdateSpecificationAttributeCommand { Model = model });+ return Ok(model);+ }++ [SwaggerOperation("Partially update entity in SpecificationAttribute",+ OperationId = "PartiallyUpdateSpecificationAttribute")]+ [HttpPatch("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.BadRequest)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Patch([FromRoute] string key,+ [FromBody] JsonPatchDocument<SpecificationAttributeDto> model)+ {+ if (string.IsNullOrEmpty(key))+ return BadRequest("Key is null or empty");++ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ var specification =+ await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));+ if (!specification.Any()) return NotFound();++ var spec = specification.FirstOrDefault();+ model.ApplyTo(spec);+ await _mediator.Send(new UpdateSpecificationAttributeCommand { Model = spec });+ return Ok();+ }++ [SwaggerOperation("Delete entity in SpecificationAttribute", OperationId = "DeleteSpecificationAttribute")]+ [HttpDelete]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Delete(string key)+ {+ if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();++ var specification =+ await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));+ if (!specification.Any()) return NotFound();++ await _mediator.Send(new DeleteSpecificationAttributeCommand { Model = specification.FirstOrDefault() });++ return Ok();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/StoreController.cs b/src/API/Grand.Api/Controllers/OData/StoreController.csindex e13f403ff..b78f14fd5 100644--- a/src/API/Grand.Api/Controllers/OData/StoreController.cs+++ b/src/API/Grand.Api/Controllers/OData/StoreController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Stores;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Store")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class StoreController : BaseODataController{- [Route("odata/Store")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class StoreController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public StoreController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Store by key", OperationId = "GetStoreById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public StoreController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Store by key", OperationId = "GetStoreById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Stores)) return Forbid();-- var store = await _mediator.Send(new GetGenericQuery<StoreDto, Domain.Stores.Store>(key));- if (!store.Any()) return NotFound();-- return Ok(store.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Store", OperationId = "GetStores")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Stores)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<StoreDto, Domain.Stores.Store>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Stores)) return Forbid();++ var store = await _mediator.Send(new GetGenericQuery<StoreDto, Store>(key));+ if (!store.Any()) return NotFound();++ return Ok(store.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Store", OperationId = "GetStores")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Stores)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<StoreDto, Store>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/VendorController.cs b/src/API/Grand.Api/Controllers/OData/VendorController.csindex 94be3990e..3a327a5b7 100644--- a/src/API/Grand.Api/Controllers/OData/VendorController.cs+++ b/src/API/Grand.Api/Controllers/OData/VendorController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Vendors;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,47 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Vendor")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class VendorController : BaseODataController{- [Route("odata/Vendor")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class VendorController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public VendorController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Vendor by key", OperationId = "GetVendorById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public VendorController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Vendor by key", OperationId = "GetVendorById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.Vendors)) return Forbid();-- var vendor = await _mediator.Send(new GetGenericQuery<VendorDto, Domain.Vendors.Vendor>(key));- if (!vendor.Any()) return NotFound();-- return Ok(vendor.FirstOrDefault());-- }-- [SwaggerOperation(summary: "Get entities from Vendor", OperationId = "GetVendors")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.Vendors)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<VendorDto, Domain.Vendors.Vendor>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.Vendors)) return Forbid();++ var vendor = await _mediator.Send(new GetGenericQuery<VendorDto, Vendor>(key));+ if (!vendor.Any()) return NotFound();++ return Ok(vendor.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Vendor", OperationId = "GetVendors")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.Vendors)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<VendorDto, Vendor>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/OData/WarehouseController.cs b/src/API/Grand.Api/Controllers/OData/WarehouseController.csindex dc52adff6..2bc5fef56 100644--- a/src/API/Grand.Api/Controllers/OData/WarehouseController.cs+++ b/src/API/Grand.Api/Controllers/OData/WarehouseController.cs@@ -2,6 +2,7 @@using Grand.Api.Queries.Models.Common;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Shipping;using MediatR;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;@@ -9,46 +10,45 @@ using MongoDB.AspNetCore.OData;using Swashbuckle.AspNetCore.Annotations;using System.Net;-namespace Grand.Api.Controllers.OData+namespace Grand.Api.Controllers.OData;++[Route("odata/Warehouse")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+public class WarehouseController : BaseODataController{- [Route("odata/Warehouse")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- public class WarehouseController : BaseODataController+ private readonly IMediator _mediator;+ private readonly IPermissionService _permissionService;++ public WarehouseController(IMediator mediator, IPermissionService permissionService)+ {+ _mediator = mediator;+ _permissionService = permissionService;+ }++ [SwaggerOperation("Get entity from Warehouse by key", OperationId = "GetWarehouseById")]+ [HttpGet("{key}")]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ [ProducesResponseType((int)HttpStatusCode.NotFound)]+ public async Task<IActionResult> Get([FromRoute] string key){- private readonly IMediator _mediator;- private readonly IPermissionService _permissionService;-- public WarehouseController(IMediator mediator, IPermissionService permissionService)- {- _mediator = mediator;- _permissionService = permissionService;- }-- [SwaggerOperation(summary: "Get entity from Warehouse by key", OperationId = "GetWarehouseById")]- [HttpGet("{key}")]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- [ProducesResponseType((int)HttpStatusCode.NotFound)]- public async Task<IActionResult> Get([FromRoute] string key)- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- var warehouse = await _mediator.Send(new GetGenericQuery<WarehouseDto, Domain.Shipping.Warehouse>(key));- if (!warehouse.Any()) return NotFound();-- return Ok(warehouse.FirstOrDefault());- }-- [SwaggerOperation(summary: "Get entities from Warehouse", OperationId = "GetWarehouses")]- [HttpGet]- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]- [ProducesResponseType((int)HttpStatusCode.Forbidden)]- [ProducesResponseType((int)HttpStatusCode.OK)]- public async Task<IActionResult> Get()- {- if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();-- return Ok(await _mediator.Send(new GetGenericQuery<WarehouseDto, Domain.Shipping.Warehouse>()));- }+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ var warehouse = await _mediator.Send(new GetGenericQuery<WarehouseDto, Warehouse>(key));+ if (!warehouse.Any()) return NotFound();++ return Ok(warehouse.FirstOrDefault());+ }++ [SwaggerOperation("Get entities from Warehouse", OperationId = "GetWarehouses")]+ [HttpGet]+ [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]+ [ProducesResponseType((int)HttpStatusCode.Forbidden)]+ [ProducesResponseType((int)HttpStatusCode.OK)]+ public async Task<IActionResult> Get()+ {+ if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();++ return Ok(await _mediator.Send(new GetGenericQuery<WarehouseDto, Warehouse>()));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/TokenController.cs b/src/API/Grand.Api/Controllers/TokenController.csindex 0294b93e4..25e51c1ce 100644--- a/src/API/Grand.Api/Controllers/TokenController.cs+++ b/src/API/Grand.Api/Controllers/TokenController.cs@@ -6,41 +6,40 @@ using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using Swashbuckle.AspNetCore.Annotations;-namespace Grand.Api.Controllers+namespace Grand.Api.Controllers;++[ApiController]+[Area("Api")]+[Route("[area]/[controller]/[action]")]+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]+[SwaggerTag("Create token")]+public class TokenController : Controller{- [ApiController]- [Area("Api")]- [Route("[area]/[controller]/[action]")]- [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]- [SwaggerTag(description: "Create token")]- public class TokenController : Controller- {- private readonly IUserApiService _userApiService;- private readonly IMediator _mediator;+ private readonly IMediator _mediator;+ private readonly IUserApiService _userApiService;- public TokenController(IMediator mediator, IUserApiService userApiService)- {- _userApiService = userApiService;- _mediator = mediator;- }+ public TokenController(IMediator mediator, IUserApiService userApiService)+ {+ _userApiService = userApiService;+ _mediator = mediator;+ }- [AllowAnonymous]- [IgnoreAntiforgeryToken]- [HttpPost]- public async Task<IActionResult> Create([FromBody] LoginModel model)- {- if (!ModelState.IsValid)- return BadRequest(ModelState);+ [AllowAnonymous]+ [IgnoreAntiforgeryToken]+ [HttpPost]+ public async Task<IActionResult> Create([FromBody] LoginModel model)+ {+ if (!ModelState.IsValid)+ return BadRequest(ModelState);- var claims = new Dictionary<string, string> {- { "Email", model.Email }- };- var user = await _userApiService.GetUserByEmail(model.Email);- if (user != null)- claims.Add("Token", user.Token);+ var claims = new Dictionary<string, string> {+ { "Email", model.Email }+ };+ var user = await _userApiService.GetUserByEmail(model.Email);+ if (user != null)+ claims.Add("Token", user.Token);- var token = await _mediator.Send(new GenerateTokenCommand { Claims = claims });- return Content(token);- }+ var token = await _mediator.Send(new GenerateTokenCommand { Claims = claims });+ return Content(token);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Controllers/TokenWebController.cs b/src/API/Grand.Api/Controllers/TokenWebController.csindex 6d0ec34d8..fd0cd1de9 100644--- a/src/API/Grand.Api/Controllers/TokenWebController.cs+++ b/src/API/Grand.Api/Controllers/TokenWebController.cs@@ -14,161 +14,159 @@ using Microsoft.AspNetCore.Mvc;using Swashbuckle.AspNetCore.Annotations;using System.Security.Claims;-namespace Grand.Api.Controllers+namespace Grand.Api.Controllers;++[ApiExplorerSettings(GroupName = "v2")]+[ApiController]+[Route("[controller]/[action]")]+[SwaggerTag("Create token")]+public class TokenWebController : ControllerBase{- [ApiExplorerSettings(GroupName = "v2")]- [ApiController]- [Route("[controller]/[action]")]- [SwaggerTag(description: "Create token")]- public class TokenWebController : ControllerBase+ private readonly IAntiforgery _antiforgery;+ private readonly FrontendAPIConfig _apiConfig;+ private readonly ICustomerService _customerService;+ private readonly IMediator _mediator;+ private readonly IRefreshTokenService _refreshTokenService;+ private readonly IStoreHelper _storeHelper;+ private readonly IUserFieldService _userFieldService;++ public TokenWebController(+ ICustomerService customerService,+ IMediator mediator,+ IStoreHelper storeHelper,+ IRefreshTokenService refreshTokenService,+ IUserFieldService userFieldService,+ IAntiforgery antiforgery,+ FrontendAPIConfig apiConfig){- private readonly ICustomerService _customerService;- private readonly IMediator _mediator;- private readonly IStoreHelper _storeHelper;- private readonly IRefreshTokenService _refreshTokenService;- private readonly IUserFieldService _userFieldService;- private readonly IAntiforgery _antiforgery;- private readonly FrontendAPIConfig _apiConfig;-- public TokenWebController(- ICustomerService customerService,- IMediator mediator,- IStoreHelper storeHelper,- IRefreshTokenService refreshTokenService,- IUserFieldService userFieldService,- IAntiforgery antiforgery,- FrontendAPIConfig apiConfig)- {- _customerService = customerService;- _mediator = mediator;- _storeHelper = storeHelper;- _refreshTokenService = refreshTokenService;- _userFieldService = userFieldService;- _antiforgery = antiforgery;- _apiConfig = apiConfig;- }+ _customerService = customerService;+ _mediator = mediator;+ _storeHelper = storeHelper;+ _refreshTokenService = refreshTokenService;+ _userFieldService = userFieldService;+ _antiforgery = antiforgery;+ _apiConfig = apiConfig;+ }++ [AllowAnonymous]+ [IgnoreAntiforgeryToken]+ [HttpPost]+ public async Task<IActionResult> Guest()+ {+ if (!_apiConfig.Enabled)+ return BadRequest("API is disabled");++ var customer = new Customer {+ CustomerGuid = Guid.NewGuid(),+ Active = true,+ StoreId = _storeHelper.StoreHost.Id,+ LastActivityDateUtc = DateTime.UtcNow+ };++ customer = await _customerService.InsertGuestCustomer(customer);++ var claims = new Dictionary<string, string> {+ { "Guid", customer.CustomerGuid.ToString() }+ };++ var tokenDto = await GetToken(claims, customer);+ return Ok(tokenDto);+ }++ [AllowAnonymous]+ [IgnoreAntiforgeryToken]+ [HttpPost]+ public async Task<IActionResult> Login([FromBody] LoginWebModel model)+ {+ if (!ModelState.IsValid)+ return BadRequest(ModelState);- [AllowAnonymous]- [IgnoreAntiforgeryToken]- [HttpPost]- public async Task<IActionResult> Guest()+ try{- if (!_apiConfig.Enabled)- return BadRequest("API is disabled");-- var customer = new Customer {- CustomerGuid = Guid.NewGuid(),- Active = true,- StoreId = _storeHelper.StoreHost.Id,- LastActivityDateUtc = DateTime.UtcNow,- };-- customer = await _customerService.InsertGuestCustomer(customer);-+ var customer = await _customerService.GetCustomerByEmail(model.Email);var claims = new Dictionary<string, string> {- { "Guid", customer.CustomerGuid.ToString()}+ { "Email", model.Email }, {+ "Token",+ await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken)+ }};-var tokenDto = await GetToken(claims, customer);return Ok(tokenDto);}-- [AllowAnonymous]- [IgnoreAntiforgeryToken]- [HttpPost]- public async Task<IActionResult> Login([FromBody] LoginWebModel model)+ catch (Exception ex){- if (!ModelState.IsValid)- return BadRequest(ModelState);+ return BadRequest(ex.Message);+ }+ }- try- {- var customer = await _customerService.GetCustomerByEmail(model.Email);- var claims = new Dictionary<string, string> {- { "Email", model.Email },- { "Token", await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken) }- };- var tokenDto = await GetToken(claims, customer);- return Ok(tokenDto);- }- catch (Exception ex)- {- return BadRequest(ex.Message);- }+ [AllowAnonymous]+ [IgnoreAntiforgeryToken]+ [HttpPost]+ public async Task<IActionResult> Refresh([FromBody] TokenDto tokenDto)+ {+ if (!_apiConfig.Enabled)+ return BadRequest("API is disabled");++ string email;+ Customer customer = null;+ var claims = new Dictionary<string, string>();+ ClaimsPrincipal principal;+ try+ {+ principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken);+ email = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;+ }+ catch (Exception)+ {+ return BadRequest("Invalid access token");}- [AllowAnonymous]- [IgnoreAntiforgeryToken]- [HttpPost]- public async Task<IActionResult> Refresh([FromBody] TokenDto tokenDto)+ if (!string.IsNullOrEmpty(email)){- if (!_apiConfig.Enabled)- return BadRequest("API is disabled");-- string email;- Customer customer = null;- var claims = new Dictionary<string, string>();- ClaimsPrincipal principal;- try- {- principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken);- email = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;- }- catch (Exception)- {- return BadRequest("Invalid access token");- }- if (!string.IsNullOrEmpty(email))- {- customer = await _customerService.GetCustomerByEmail(email);- claims.Add("Email", email);- claims.Add("Token", await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken));- }- else+ customer = await _customerService.GetCustomerByEmail(email);+ claims.Add("Email", email);+ claims.Add("Token",+ await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken));+ }+ else+ {+ var guid = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;+ if (guid != null){- var guid = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;- if (guid != null)- {- customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));- claims.Add("Guid", guid);- }+ customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));+ claims.Add("Guid", guid);}+ }- var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);- if (customerRefreshToken is null || !customerRefreshToken.Token.Equals(tokenDto.RefreshToken))- {- return BadRequest("Invalid refresh token");- }+ var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);+ if (customerRefreshToken is null || !customerRefreshToken.Token.Equals(tokenDto.RefreshToken))+ return BadRequest("Invalid refresh token");- if (customerRefreshToken.ValidTo.CompareTo(DateTime.UtcNow) < 0)- {- return BadRequest("Token expired");- }- var token = await GetToken(claims, customer);- return Ok(token);- }+ if (customerRefreshToken.ValidTo.CompareTo(DateTime.UtcNow) < 0) return BadRequest("Token expired");+ var token = await GetToken(claims, customer);+ return Ok(token);+ }- [HttpGet]- [AllowAnonymous]- public IActionResult Antiforgery()- {- if (!_apiConfig.Enabled)- return BadRequest("API is disabled");+ [HttpGet]+ [AllowAnonymous]+ public IActionResult Antiforgery()+ {+ if (!_apiConfig.Enabled)+ return BadRequest("API is disabled");- var token = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken;- return Ok(token);- }+ var token = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken;+ return Ok(token);+ }- private async Task<TokenDto> GetToken(Dictionary<string, string> claims, Customer customer)- {- var refreshTokenValue = _refreshTokenService.GenerateRefreshToken();- var refreshToken = await _refreshTokenService.SaveRefreshTokenToCustomer(customer, refreshTokenValue);- claims.Add("RefreshId", refreshToken.RefreshId);- var token = await _mediator.Send(new GenerateTokenWebCommand { Claims = claims });- return new TokenDto {- AccessToken = token,- RefreshToken = refreshTokenValue- };- }+ private async Task<TokenDto> GetToken(Dictionary<string, string> claims, Customer customer)+ {+ var refreshTokenValue = _refreshTokenService.GenerateRefreshToken();+ var refreshToken = await _refreshTokenService.SaveRefreshTokenToCustomer(customer, refreshTokenValue);+ claims.Add("RefreshId", refreshToken.RefreshId);+ var token = await _mediator.Send(new GenerateTokenWebCommand { Claims = claims });+ return new TokenDto {+ AccessToken = token,+ RefreshToken = refreshTokenValue+ };}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/BrandDto.cs b/src/API/Grand.Api/DTOs/Catalog/BrandDto.csindex d6d957340..b8c7a2c20 100644--- a/src/API/Grand.Api/DTOs/Catalog/BrandDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/BrandDto.cs@@ -1,26 +1,25 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class BrandDto : BaseApiEntityModel{- public class BrandDto : BaseApiEntityModel- {- public string Name { get; set; }- public string SeName { get; set; }- public string Description { get; set; }- public string BottomDescription { get; set; }- public string BrandLayoutId { get; set; }- public string MetaKeywords { get; set; }- public string MetaDescription { get; set; }- public string MetaTitle { get; set; }- public string PictureId { get; set; }- public int PageSize { get; set; }- public bool AllowCustomersToSelectPageSize { get; set; }- public string PageSizeOptions { get; set; }- public bool ShowOnHomePage { get; set; }- public bool IncludeInMenu { get; set; }- public string Icon { get; set; }- public bool Published { get; set; }- public string ExternalId { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string SeName { get; set; }+ public string Description { get; set; }+ public string BottomDescription { get; set; }+ public string BrandLayoutId { get; set; }+ public string MetaKeywords { get; set; }+ public string MetaDescription { get; set; }+ public string MetaTitle { get; set; }+ public string PictureId { get; set; }+ public int PageSize { get; set; }+ public bool AllowCustomersToSelectPageSize { get; set; }+ public string PageSizeOptions { get; set; }+ public bool ShowOnHomePage { get; set; }+ public bool IncludeInMenu { get; set; }+ public string Icon { get; set; }+ public bool Published { get; set; }+ public string ExternalId { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/CategoryDTO.cs b/src/API/Grand.Api/DTOs/Catalog/CategoryDTO.csindex ec8f8ffbb..5aca909c8 100644--- a/src/API/Grand.Api/DTOs/Catalog/CategoryDTO.cs+++ b/src/API/Grand.Api/DTOs/Catalog/CategoryDTO.cs@@ -1,33 +1,32 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class CategoryDto : BaseApiEntityModel{- public class CategoryDto : BaseApiEntityModel- {- public string Name { get; set; }- public string Description { get; set; }- public string BottomDescription { get; set; }- public string CategoryLayoutId { get; set; }- public string MetaKeywords { get; set; }- public string MetaDescription { get; set; }- public string MetaTitle { get; set; }- public string SeName { get; set; }- public string ParentCategoryId { get; set; }- public string PictureId { get; set; }- public int PageSize { get; set; }- public bool AllowCustomersToSelectPageSize { get; set; }- public string PageSizeOptions { get; set; }- public bool ShowOnHomePage { get; set; }- public bool FeaturedProductsOnHomePage { get; set; }- public bool IncludeInMenu { get; set; }- public bool Published { get; set; }- public int DisplayOrder { get; set; }- public string ExternalId { get; set; }- public string Flag { get; set; }- public string FlagStyle { get; set; }- public string Icon { get; set; }- public bool HideOnCatalog { get; set; }- public bool ShowOnSearchBox { get; set; }- public int SearchBoxDisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string Description { get; set; }+ public string BottomDescription { get; set; }+ public string CategoryLayoutId { get; set; }+ public string MetaKeywords { get; set; }+ public string MetaDescription { get; set; }+ public string MetaTitle { get; set; }+ public string SeName { get; set; }+ public string ParentCategoryId { get; set; }+ public string PictureId { get; set; }+ public int PageSize { get; set; }+ public bool AllowCustomersToSelectPageSize { get; set; }+ public string PageSizeOptions { get; set; }+ public bool ShowOnHomePage { get; set; }+ public bool FeaturedProductsOnHomePage { get; set; }+ public bool IncludeInMenu { get; set; }+ public bool Published { get; set; }+ public int DisplayOrder { get; set; }+ public string ExternalId { get; set; }+ public string Flag { get; set; }+ public string FlagStyle { get; set; }+ public string Icon { get; set; }+ public bool HideOnCatalog { get; set; }+ public bool ShowOnSearchBox { get; set; }+ public int SearchBoxDisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/CollectionDto.cs b/src/API/Grand.Api/DTOs/Catalog/CollectionDto.csindex 78cf622eb..f1002195f 100644--- a/src/API/Grand.Api/DTOs/Catalog/CollectionDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/CollectionDto.cs@@ -1,27 +1,26 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class CollectionDto : BaseApiEntityModel{- public class CollectionDto : BaseApiEntityModel- {- public string Name { get; set; }- public string SeName { get; set; }- public string Description { get; set; }- public string BottomDescription { get; set; }- public string CollectionLayoutId { get; set; }- public string MetaKeywords { get; set; }- public string MetaDescription { get; set; }- public string MetaTitle { get; set; }- public string PictureId { get; set; }- public int PageSize { get; set; }- public bool AllowCustomersToSelectPageSize { get; set; }- public string PageSizeOptions { get; set; }- public bool ShowOnHomePage { get; set; }- public bool FeaturedProductsOnHomePage { get; set; }- public bool IncludeInMenu { get; set; }- public string Icon { get; set; }- public bool Published { get; set; }- public string ExternalId { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string SeName { get; set; }+ public string Description { get; set; }+ public string BottomDescription { get; set; }+ public string CollectionLayoutId { get; set; }+ public string MetaKeywords { get; set; }+ public string MetaDescription { get; set; }+ public string MetaTitle { get; set; }+ public string PictureId { get; set; }+ public int PageSize { get; set; }+ public bool AllowCustomersToSelectPageSize { get; set; }+ public string PageSizeOptions { get; set; }+ public bool ShowOnHomePage { get; set; }+ public bool FeaturedProductsOnHomePage { get; set; }+ public bool IncludeInMenu { get; set; }+ public string Icon { get; set; }+ public bool Published { get; set; }+ public string ExternalId { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeCombinationDto.csindex 8f1f4dd14..a302985ae 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs@@ -1,18 +1,17 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductAttributeCombinationDto : BaseApiEntityModel{- public class ProductAttributeCombinationDto : BaseApiEntityModel- {- public int StockQuantity { get; set; }- public int ReservedQuantity { get; set; }- public bool AllowOutOfStockOrders { get; set; }- public string Text { get; set; }- public string Sku { get; set; }- public string Mpn { get; set; }- public string Gtin { get; set; }- public double? OverriddenPrice { get; set; }- public int NotifyAdminForQuantityBelow { get; set; }- public string PictureId { get; set; }- }-}+ public int StockQuantity { get; set; }+ public int ReservedQuantity { get; set; }+ public bool AllowOutOfStockOrders { get; set; }+ public string Text { get; set; }+ public string Sku { get; set; }+ public string Mpn { get; set; }+ public string Gtin { get; set; }+ public double? OverriddenPrice { get; set; }+ public int NotifyAdminForQuantityBelow { get; set; }+ public string PictureId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeDto.csindex 9d0250656..4d734dbfa 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeDto.cs@@ -1,21 +1,22 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductAttributeDto : BaseApiEntityModel{- public class ProductAttributeDto : BaseApiEntityModel- {- public string Name { get; set; }- public string Description { get; set; }- public IList<PredefinedProductAttributeValueDto> PredefinedProductAttributeValues { get; set; } = new List<PredefinedProductAttributeValueDto>();- }+ public string Name { get; set; }+ public string Description { get; set; }- public class PredefinedProductAttributeValueDto : BaseApiEntityModel- {- public string Name { get; set; }- public double PriceAdjustment { get; set; }- public double WeightAdjustment { get; set; }- public double Cost { get; set; }- public bool IsPreSelected { get; set; }- public int DisplayOrder { get; set; }- }+ public IList<PredefinedProductAttributeValueDto> PredefinedProductAttributeValues { get; set; } =+ new List<PredefinedProductAttributeValueDto>();}++public class PredefinedProductAttributeValueDto : BaseApiEntityModel+{+ public string Name { get; set; }+ public double PriceAdjustment { get; set; }+ public double WeightAdjustment { get; set; }+ public double Cost { get; set; }+ public bool IsPreSelected { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.csindex 941fd0227..f134e7924 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductAttributeMappingDeleteDto{- public class ProductAttributeMappingDeleteDto- {- public string Id { get; set; }- }-}+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDto.csindex 9fbc568bd..d071c20e0 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductAttributeMappingDto.cs@@ -1,37 +1,37 @@-using Grand.Domain.Catalog;-using Grand.Api.Models;+using Grand.Api.Models;+using Grand.Domain.Catalog;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductAttributeMappingDto : BaseApiEntityModel{- public class ProductAttributeMappingDto : BaseApiEntityModel- {- public string ProductAttributeId { get; set; }- public string TextPrompt { get; set; }- public bool IsRequired { get; set; }- public int DisplayOrder { get; set; }- public int? ValidationMinLength { get; set; }- public int? ValidationMaxLength { get; set; }- public string ValidationFileAllowedExtensions { get; set; }- public int? ValidationFileMaximumSize { get; set; }- public string DefaultValue { get; set; }- public string ConditionAttributeXml { get; set; }- public AttributeControlType AttributeControlTypeId { get; set; }+ public string ProductAttributeId { get; set; }+ public string TextPrompt { get; set; }+ public bool IsRequired { get; set; }+ public int DisplayOrder { get; set; }+ public int? ValidationMinLength { get; set; }+ public int? ValidationMaxLength { get; set; }+ public string ValidationFileAllowedExtensions { get; set; }+ public int? ValidationFileMaximumSize { get; set; }+ public string DefaultValue { get; set; }+ public string ConditionAttributeXml { get; set; }+ public AttributeControlType AttributeControlTypeId { get; set; }- public IList<ProductAttributeValueDto> ProductAttributeValues { get; set; } = new List<ProductAttributeValueDto>();- }- public class ProductAttributeValueDto: BaseApiEntityModel- {- public string AssociatedProductId { get; set; }- public string Name { get; set; }- public string ColorSquaresRgb { get; set; }- public string ImageSquaresPictureId { get; set; }- public double PriceAdjustment { get; set; }- public double WeightAdjustment { get; set; }- public double Cost { get; set; }- public int Quantity { get; set; }- public bool IsPreSelected { get; set; }- public int DisplayOrder { get; set; }- public string PictureId { get; set; }- public AttributeValueType AttributeValueTypeId { get; set; }- }+ public IList<ProductAttributeValueDto> ProductAttributeValues { get; set; } = new List<ProductAttributeValueDto>();}++public class ProductAttributeValueDto : BaseApiEntityModel+{+ public string AssociatedProductId { get; set; }+ public string Name { get; set; }+ public string ColorSquaresRgb { get; set; }+ public string ImageSquaresPictureId { get; set; }+ public double PriceAdjustment { get; set; }+ public double WeightAdjustment { get; set; }+ public double Cost { get; set; }+ public int Quantity { get; set; }+ public bool IsPreSelected { get; set; }+ public int DisplayOrder { get; set; }+ public string PictureId { get; set; }+ public AttributeValueType AttributeValueTypeId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDeleteDto.csindex 1d2158f24..f95706282 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductCategoryDeleteDto{- public class ProductCategoryDeleteDto- {- public string CategoryId { get; set; }- }-}+ public string CategoryId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDto.csindex cd5bb91f7..8f283f11f 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductCategoryDto.cs@@ -1,11 +1,10 @@using System.ComponentModel.DataAnnotations;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductCategoryDto{- public class ProductCategoryDto- {- [Key]- public string CategoryId { get; set; }- public bool IsFeaturedProduct { get; set; }- }-}+ [Key] public string CategoryId { get; set; }++ public bool IsFeaturedProduct { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDeleteDto.csindex 0bea153dc..525d5d265 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductCollectionDeleteDto{- public class ProductCollectionDeleteDto- {- public string CollectionId { get; set; }- }-}+ public string CollectionId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDto.csindex 301623417..04446eb37 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductCollectionDto.cs@@ -1,11 +1,10 @@using System.ComponentModel.DataAnnotations;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductCollectionDto{- public class ProductCollectionDto- {- [Key]- public string CollectionId { get; set; }- public bool IsFeaturedProduct { get; set; }- }-}+ [Key] public string CollectionId { get; set; }++ public bool IsFeaturedProduct { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductDto.csindex 344248144..629916e9d 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductDto.cs@@ -1,129 +1,138 @@using Grand.Api.Models;using Grand.Domain.Catalog;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductDto : BaseApiEntityModel{- public class ProductDto : BaseApiEntityModel- {- public ProductType ProductTypeId { get; set; }- public string ParentGroupedProductId { get; set; }- public bool VisibleIndividually { get; set; }- public string Name { get; set; }- public string SeName { get; set; }- public string ShortDescription { get; set; }- public string FullDescription { get; set; }- public string AdminComment { get; set; }- public string ProductLayoutId { get; set; }- public string BrandId { get; set; }- public string VendorId { get; set; }- public bool ShowOnHomePage { get; set; }- public string MetaKeywords { get; set; }- public string MetaDescription { get; set; }- public string MetaTitle { get; set; }- public bool AllowCustomerReviews { get; set; }- public int ApprovedRatingSum { get; set; }- public int NotApprovedRatingSum { get; set; }- public int ApprovedTotalReviews { get; set; }- public int NotApprovedTotalReviews { get; set; }- public string ExternalId { get; set; }- public string Sku { get; set; }- public string Mpn { get; set; }- public string Gtin { get; set; }- public bool IsGiftVoucher { get; set; }- public GiftVoucherType GiftVoucherTypeId { get; set; }- public double? OverGiftAmount { get; set; }- public bool RequireOtherProducts { get; set; }- public string RequiredProductIds { get; set; }- public bool AutoAddRequiredProducts { get; set; }- public bool IsDownload { get; set; }- public string DownloadId { get; set; }- public bool UnlimitedDownloads { get; set; }- public DownloadActivationType DownloadActivationTypeId { get; set; }- public int MaxNumberOfDownloads { get; set; }- public int? DownloadExpirationDays { get; set; }- public bool HasSampleDownload { get; set; }- public string SampleDownloadId { get; set; }- public bool HasUserAgreement { get; set; }- public string UserAgreementText { get; set; }- public bool IsRecurring { get; set; }- public int RecurringCycleLength { get; set; }- public int RecurringTotalCycles { get; set; }- public RecurringCyclePeriod RecurringCyclePeriodId { get; set; }- public bool IncBothDate { get; set; }- public int Interval { get; set; }- public IntervalUnit IntervalUnitId { get; set; }- public bool IsShipEnabled { get; set; }- public bool IsFreeShipping { get; set; }- public bool ShipSeparately { get; set; }- public double AdditionalShippingCharge { get; set; }- public string DeliveryDateId { get; set; }- public bool IsTaxExempt { get; set; }- public string TaxCategoryId { get; set; }- public bool IsTele { get; set; }- public bool UseMultipleWarehouses { get; set; }- public string WarehouseId { get; set; }- public int StockQuantity { get; set; }- public int ReservedQuantity { get; set; }- public ManageInventoryMethod ManageInventoryMethodId { get; set; }- public bool StockAvailability { get; set; }- public bool DisplayStockQuantity { get; set; }- public int MinStockQuantity { get; set; }- public bool LowStock { get; set; }- public LowStockActivity LowStockActivityId { get; set; }- public int NotifyAdminForQuantityBelow { get; set; }- public BackorderMode BackorderModeId { get; set; }- public bool AllowOutOfStockSubscriptions { get; set; }- public int OrderMinimumQuantity { get; set; }- public int OrderMaximumQuantity { get; set; }- public string AllowedQuantities { get; set; }- public bool NotReturnable { get; set; }- public bool DisableBuyButton { get; set; }- public bool DisableWishlistButton { get; set; }- public bool AvailableForPreOrder { get; set; }- public DateTime? PreOrderDateTimeUtc { get; set; }- public bool CallForPrice { get; set; }- public double Price { get; set; }- public double OldPrice { get; set; }- public double CatalogPrice { get; set; }- public double ProductCost { get; set; }- public 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 string UnitId { get; set; }- public bool MarkAsNew { get; set; }- public DateTime? MarkAsNewStartDateTimeUtc { get; set; }- public DateTime? MarkAsNewEndDateTimeUtc { get; set; }- public double Weight { get; set; }- public double Length { get; set; }- public double Width { get; set; }- public double Height { get; set; }- public DateTime? AvailableStartDateTimeUtc { get; set; }- public DateTime? AvailableEndDateTimeUtc { get; set; }- public double StartPrice { get; set; }- public bool AuctionEnded { get; set; }- public int DisplayOrder { get; set; }- public int DisplayOrderCategory { get; set; }- public int DisplayOrderBrand { get; set; }- public int DisplayOrderCollection { get; set; }- public bool Published { get; set; }- public int Sold { get; set; }- public Int64 Viewed { get; set; }- public int OnSale { get; set; }- public string Flag { get; set; }- public IList<ProductCategoryDto> ProductCategories { get; set; } = new List<ProductCategoryDto>();- public IList<ProductCollectionDto> ProductCollections { get; set; } = new List<ProductCollectionDto>();- public IList<ProductPictureDto> ProductPictures { get; set; } = new List<ProductPictureDto>();- public IList<ProductSpecificationAttributeDto> ProductSpecificationAttributes { get; set; } = new List<ProductSpecificationAttributeDto>();- public IList<ProductTierPriceDto> TierPrices { get; set; } = new List<ProductTierPriceDto>();- public IList<ProductWarehouseInventoryDto> ProductWarehouseInventory { get; set; } = new List<ProductWarehouseInventoryDto>();- public IList<ProductAttributeMappingDto> ProductAttributeMappings { get; set; } = new List<ProductAttributeMappingDto>();- public IList<ProductAttributeCombinationDto> ProductAttributeCombinations { get; set; } = new List<ProductAttributeCombinationDto>();- public IList<string> ProductTags { get; set; } = new List<string>();- public IList<string> AppliedDiscounts { get; set; } = new List<string>();- }-}+ public ProductType ProductTypeId { get; set; }+ public string ParentGroupedProductId { get; set; }+ public bool VisibleIndividually { get; set; }+ public string Name { get; set; }+ public string SeName { get; set; }+ public string ShortDescription { get; set; }+ public string FullDescription { get; set; }+ public string AdminComment { get; set; }+ public string ProductLayoutId { get; set; }+ public string BrandId { get; set; }+ public string VendorId { get; set; }+ public bool ShowOnHomePage { get; set; }+ public string MetaKeywords { get; set; }+ public string MetaDescription { get; set; }+ public string MetaTitle { get; set; }+ public bool AllowCustomerReviews { get; set; }+ public int ApprovedRatingSum { get; set; }+ public int NotApprovedRatingSum { get; set; }+ public int ApprovedTotalReviews { get; set; }+ public int NotApprovedTotalReviews { get; set; }+ public string ExternalId { get; set; }+ public string Sku { get; set; }+ public string Mpn { get; set; }+ public string Gtin { get; set; }+ public bool IsGiftVoucher { get; set; }+ public GiftVoucherType GiftVoucherTypeId { get; set; }+ public double? OverGiftAmount { get; set; }+ public bool RequireOtherProducts { get; set; }+ public string RequiredProductIds { get; set; }+ public bool AutoAddRequiredProducts { get; set; }+ public bool IsDownload { get; set; }+ public string DownloadId { get; set; }+ public bool UnlimitedDownloads { get; set; }+ public DownloadActivationType DownloadActivationTypeId { get; set; }+ public int MaxNumberOfDownloads { get; set; }+ public int? DownloadExpirationDays { get; set; }+ public bool HasSampleDownload { get; set; }+ public string SampleDownloadId { get; set; }+ public bool HasUserAgreement { get; set; }+ public string UserAgreementText { get; set; }+ public bool IsRecurring { get; set; }+ public int RecurringCycleLength { get; set; }+ public int RecurringTotalCycles { get; set; }+ public RecurringCyclePeriod RecurringCyclePeriodId { get; set; }+ public bool IncBothDate { get; set; }+ public int Interval { get; set; }+ public IntervalUnit IntervalUnitId { get; set; }+ public bool IsShipEnabled { get; set; }+ public bool IsFreeShipping { get; set; }+ public bool ShipSeparately { get; set; }+ public double AdditionalShippingCharge { get; set; }+ public string DeliveryDateId { get; set; }+ public bool IsTaxExempt { get; set; }+ public string TaxCategoryId { get; set; }+ public bool IsTele { get; set; }+ public bool UseMultipleWarehouses { get; set; }+ public string WarehouseId { get; set; }+ public int StockQuantity { get; set; }+ public int ReservedQuantity { get; set; }+ public ManageInventoryMethod ManageInventoryMethodId { get; set; }+ public bool StockAvailability { get; set; }+ public bool DisplayStockQuantity { get; set; }+ public int MinStockQuantity { get; set; }+ public bool LowStock { get; set; }+ public LowStockActivity LowStockActivityId { get; set; }+ public int NotifyAdminForQuantityBelow { get; set; }+ public BackorderMode BackorderModeId { get; set; }+ public bool AllowOutOfStockSubscriptions { get; set; }+ public int OrderMinimumQuantity { get; set; }+ public int OrderMaximumQuantity { get; set; }+ public string AllowedQuantities { get; set; }+ public bool NotReturnable { get; set; }+ public bool DisableBuyButton { get; set; }+ public bool DisableWishlistButton { get; set; }+ public bool AvailableForPreOrder { get; set; }+ public DateTime? PreOrderDateTimeUtc { get; set; }+ public bool CallForPrice { get; set; }+ public double Price { get; set; }+ public double OldPrice { get; set; }+ public double CatalogPrice { get; set; }+ public double ProductCost { get; set; }+ public 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 string UnitId { get; set; }+ public bool MarkAsNew { get; set; }+ public DateTime? MarkAsNewStartDateTimeUtc { get; set; }+ public DateTime? MarkAsNewEndDateTimeUtc { get; set; }+ public double Weight { get; set; }+ public double Length { get; set; }+ public double Width { get; set; }+ public double Height { get; set; }+ public DateTime? AvailableStartDateTimeUtc { get; set; }+ public DateTime? AvailableEndDateTimeUtc { get; set; }+ public double StartPrice { get; set; }+ public bool AuctionEnded { get; set; }+ public int DisplayOrder { get; set; }+ public int DisplayOrderCategory { get; set; }+ public int DisplayOrderBrand { get; set; }+ public int DisplayOrderCollection { get; set; }+ public bool Published { get; set; }+ public int Sold { get; set; }+ public long Viewed { get; set; }+ public int OnSale { get; set; }+ public string Flag { get; set; }+ public IList<ProductCategoryDto> ProductCategories { get; set; } = new List<ProductCategoryDto>();+ public IList<ProductCollectionDto> ProductCollections { get; set; } = new List<ProductCollectionDto>();+ public IList<ProductPictureDto> ProductPictures { get; set; } = new List<ProductPictureDto>();++ public IList<ProductSpecificationAttributeDto> ProductSpecificationAttributes { get; set; } =+ new List<ProductSpecificationAttributeDto>();++ public IList<ProductTierPriceDto> TierPrices { get; set; } = new List<ProductTierPriceDto>();++ public IList<ProductWarehouseInventoryDto> ProductWarehouseInventory { get; set; } =+ new List<ProductWarehouseInventoryDto>();++ public IList<ProductAttributeMappingDto> ProductAttributeMappings { get; set; } =+ new List<ProductAttributeMappingDto>();++ public IList<ProductAttributeCombinationDto> ProductAttributeCombinations { get; set; } =+ new List<ProductAttributeCombinationDto>();++ public IList<string> ProductTags { get; set; } = new List<string>();+ public IList<string> AppliedDiscounts { get; set; } = new List<string>();+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductPictureDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductPictureDeleteDto.csindex 6fe93c003..85855c732 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductPictureDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductPictureDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductPictureDeleteDto{- public class ProductPictureDeleteDto- {- public string PictureId { get; set; }- }-}+ public string PictureId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductPictureDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductPictureDto.csindex 08d1ba23a..1e13d7562 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductPictureDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductPictureDto.cs@@ -1,11 +1,10 @@using System.ComponentModel.DataAnnotations;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductPictureDto{- public class ProductPictureDto- {- [Key]- public string PictureId { get; set; }- public int DisplayOrder { get; set; }- }-}+ [Key] public string PictureId { get; set; }++ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.csindex f8893bea2..cab9a16e3 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductSpecificationAttributeDeleteDto{- public class ProductSpecificationAttributeDeleteDto- {- public string Id { get; set; }- }-}+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDto.csindex ca7c631f8..0fdc7a382 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs@@ -1,17 +1,16 @@using Grand.Api.Models;using Grand.Domain.Catalog;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductSpecificationAttributeDto : BaseApiEntityModel{- public class ProductSpecificationAttributeDto : BaseApiEntityModel- {- public string SpecificationAttributeId { get; set; }- public string SpecificationAttributeOptionId { get; set; }- public string CustomName { get; set; }- public string CustomValue { get; set; }- public bool AllowFiltering { get; set; }- public bool ShowOnProductPage { get; set; }- public int DisplayOrder { get; set; }- public SpecificationAttributeType AttributeTypeId { get; set; }- }-}+ public string SpecificationAttributeId { get; set; }+ public string SpecificationAttributeOptionId { get; set; }+ public string CustomName { get; set; }+ public string CustomValue { get; set; }+ public bool AllowFiltering { get; set; }+ public bool ShowOnProductPage { get; set; }+ public int DisplayOrder { get; set; }+ public SpecificationAttributeType AttributeTypeId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDeleteDto.csindex e8fa8c5f6..cd8163314 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs@@ -1,7 +1,6 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductTierPriceDeleteDto{- public class ProductTierPriceDeleteDto- {- public string Id { get; set; }- }-}+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDto.csindex 20fca0d30..d944fd390 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductTierPriceDto.cs@@ -1,14 +1,13 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductTierPriceDto : BaseApiEntityModel{- public class ProductTierPriceDto : BaseApiEntityModel- {- public string StoreId { get; set; }- public string CustomerGroupId { get; set; }- public int Quantity { get; set; }- public double Price { get; set; }- public DateTime? StartDateTimeUtc { get; set; }- public DateTime? EndDateTimeUtc { get; set; }- }-}+ public string StoreId { get; set; }+ public string CustomerGroupId { get; set; }+ public int Quantity { get; set; }+ public double Price { get; set; }+ public DateTime? StartDateTimeUtc { get; set; }+ public DateTime? EndDateTimeUtc { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductUpdateStock.cs b/src/API/Grand.Api/DTOs/Catalog/ProductUpdateStock.csindex fbedf8c92..3cf39d4e6 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductUpdateStock.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductUpdateStock.cs@@ -1,8 +1,7 @@-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductUpdateStock{- public class ProductUpdateStock- {- public string WarehouseId { get; set; }- public int Stock { get; set; }- }-}+ public string WarehouseId { get; set; }+ public int Stock { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs b/src/API/Grand.Api/DTOs/Catalog/ProductWarehouseInventoryDto.csindex 3b8a1d17d..95b3ce062 100644--- a/src/API/Grand.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs@@ -1,11 +1,10 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class ProductWarehouseInventoryDto : BaseApiEntityModel{- public class ProductWarehouseInventoryDto : BaseApiEntityModel- {- public string WarehouseId { get; set; }- public int StockQuantity { get; set; }- public int ReservedQuantity { get; set; }- }-}+ public string WarehouseId { get; set; }+ public int StockQuantity { get; set; }+ public int ReservedQuantity { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Catalog/SpecificationAttributeDto.cs b/src/API/Grand.Api/DTOs/Catalog/SpecificationAttributeDto.csindex 0a109b52b..f9d207c7a 100644--- a/src/API/Grand.Api/DTOs/Catalog/SpecificationAttributeDto.cs+++ b/src/API/Grand.Api/DTOs/Catalog/SpecificationAttributeDto.cs@@ -1,17 +1,19 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Catalog+namespace Grand.Api.DTOs.Catalog;++public class SpecificationAttributeDto : BaseApiEntityModel{- public class SpecificationAttributeDto : BaseApiEntityModel- {- public string Name { get; set; }- public int DisplayOrder { get; set; }- public IList<SpecificationAttributeOptionDto> SpecificationAttributeOptions { get; set; } = new List<SpecificationAttributeOptionDto>();- }- public class SpecificationAttributeOptionDto : BaseApiEntityModel- {- public string Name { get; set; }- public int DisplayOrder { get; set; }- public string ColorSquaresRgb { get; set; }- }+ public string Name { get; set; }+ public int DisplayOrder { get; set; }++ public IList<SpecificationAttributeOptionDto> SpecificationAttributeOptions { get; set; } =+ new List<SpecificationAttributeOptionDto>();}++public class SpecificationAttributeOptionDto : BaseApiEntityModel+{+ public string Name { get; set; }+ public int DisplayOrder { get; set; }+ public string ColorSquaresRgb { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/CountryDto.cs b/src/API/Grand.Api/DTOs/Common/CountryDto.csindex 1fb87b245..c03db672e 100644--- a/src/API/Grand.Api/DTOs/Common/CountryDto.cs+++ b/src/API/Grand.Api/DTOs/Common/CountryDto.cs@@ -1,32 +1,31 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class CountryDto : BaseApiEntityModel{- public class CountryDto : BaseApiEntityModel- {- private ICollection<StateProvinceDto> _stateProvinces;+ private ICollection<StateProvinceDto> _stateProvinces;++ public string Name { get; set; }+ public bool AllowsBilling { get; set; }+ public bool AllowsShipping { get; set; }+ public string TwoLetterIsoCode { get; set; }+ public string ThreeLetterIsoCode { get; set; }+ public int NumericIsoCode { get; set; }+ public bool SubjectToVat { get; set; }+ public bool Published { get; set; }+ public int DisplayOrder { get; set; }++ public virtual ICollection<StateProvinceDto> StateProvinces {+ get => _stateProvinces ??= new List<StateProvinceDto>();+ protected set => _stateProvinces = value;+ }+ public class StateProvinceDto+ {public string Name { get; set; }- public bool AllowsBilling { get; set; }- public bool AllowsShipping { get; set; }- public string TwoLetterIsoCode { get; set; }- public string ThreeLetterIsoCode { get; set; }- public int NumericIsoCode { get; set; }- public bool SubjectToVat { get; set; }+ public string Abbreviation { get; set; }public bool Published { get; set; }public int DisplayOrder { get; set; }-- public virtual ICollection<StateProvinceDto> StateProvinces {- get => _stateProvinces ??= new List<StateProvinceDto>();- protected set => _stateProvinces = value;- }-- public class StateProvinceDto- {- public string Name { get; set; }- public string Abbreviation { get; set; }- public bool Published { get; set; }- public int DisplayOrder { get; set; }- }}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/CurrencyDto.cs b/src/API/Grand.Api/DTOs/Common/CurrencyDto.csindex 48a581f67..2a29b3a9f 100644--- a/src/API/Grand.Api/DTOs/Common/CurrencyDto.cs+++ b/src/API/Grand.Api/DTOs/Common/CurrencyDto.cs@@ -1,15 +1,14 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class CurrencyDto : BaseApiEntityModel{- public class CurrencyDto : BaseApiEntityModel- {- public string Name { get; set; }- public string CurrencyCode { get; set; }- public double Rate { get; set; }- public string DisplayLocale { get; set; }- public string CustomFormatting { get; set; }- public bool Published { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string CurrencyCode { get; set; }+ public double Rate { get; set; }+ public string DisplayLocale { get; set; }+ public string CustomFormatting { get; set; }+ public bool Published { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/LanguageDto.cs b/src/API/Grand.Api/DTOs/Common/LanguageDto.csindex bba58b309..7f5530614 100644--- a/src/API/Grand.Api/DTOs/Common/LanguageDto.cs+++ b/src/API/Grand.Api/DTOs/Common/LanguageDto.cs@@ -1,16 +1,15 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class LanguageDto : BaseApiEntityModel{- public class LanguageDto : BaseApiEntityModel- {- public string Name { get; set; }- public string LanguageCulture { get; set; }- public string UniqueSeoCode { get; set; }- public string FlagImageFileName { get; set; }- public bool Rtl { get; set; }- public string DefaultCurrencyId { get; set; }- public bool Published { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string LanguageCulture { get; set; }+ public string UniqueSeoCode { get; set; }+ public string FlagImageFileName { get; set; }+ public bool Rtl { get; set; }+ public string DefaultCurrencyId { get; set; }+ public bool Published { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/LayoutDto.cs b/src/API/Grand.Api/DTOs/Common/LayoutDto.csindex 3c7881fc3..6eb94b814 100644--- a/src/API/Grand.Api/DTOs/Common/LayoutDto.cs+++ b/src/API/Grand.Api/DTOs/Common/LayoutDto.cs@@ -1,11 +1,10 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class LayoutDto : BaseApiEntityModel{- public class LayoutDto : BaseApiEntityModel- {- public string Name { get; set; }- public int DisplayOrder { get; set; }- public string ViewPath { get; set; }- }-}+ public string Name { get; set; }+ public int DisplayOrder { get; set; }+ public string ViewPath { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/PictureDto.cs b/src/API/Grand.Api/DTOs/Common/PictureDto.csindex 55a69ef0e..618a8b145 100644--- a/src/API/Grand.Api/DTOs/Common/PictureDto.cs+++ b/src/API/Grand.Api/DTOs/Common/PictureDto.cs@@ -1,19 +1,18 @@using Grand.Api.Models;using Grand.Domain.Common;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class PictureDto : BaseApiEntityModel{- public class PictureDto : BaseApiEntityModel- {- public byte[] PictureBinary { get; set; }- public string MimeType { get; set; }- public string SeoFilename { get; set; }- public string AltAttribute { get; set; }- public string TitleAttribute { get; set; }- public Reference Reference { get; set; }- public string ObjectId { get; set; }- public string Style { get; set; }- public string ExtraField { get; set; }- public bool IsNew { get; set; }- }-}+ public byte[] PictureBinary { get; set; }+ public string MimeType { get; set; }+ public string SeoFilename { get; set; }+ public string AltAttribute { get; set; }+ public string TitleAttribute { get; set; }+ public Reference Reference { get; set; }+ public string ObjectId { get; set; }+ public string Style { get; set; }+ public string ExtraField { get; set; }+ public bool IsNew { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Common/StoreDto.cs b/src/API/Grand.Api/DTOs/Common/StoreDto.csindex 45b2afb52..4f802f29f 100644--- a/src/API/Grand.Api/DTOs/Common/StoreDto.cs+++ b/src/API/Grand.Api/DTOs/Common/StoreDto.cs@@ -1,21 +1,20 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Common+namespace Grand.Api.DTOs.Common;++public class StoreDto : BaseApiEntityModel{- public class StoreDto : BaseApiEntityModel- {- public string Name { get; set; }- public string Url { get; set; }- public bool SslEnabled { get; set; }- public string SecureUrl { get; set; }- public string Hosts { get; set; }- public string DefaultLanguageId { get; set; }- public string DefaultWarehouseId { get; set; }- public int DisplayOrder { get; set; }- public string CompanyName { get; set; }- public string CompanyAddress { get; set; }- public string CompanyPhoneNumber { get; set; }- public string CompanyRegNo { get; set; }- public string CompanyVat { get; set; }- }-}+ public string Name { get; set; }+ public string Url { get; set; }+ public bool SslEnabled { get; set; }+ public string SecureUrl { get; set; }+ public string Hosts { get; set; }+ public string DefaultLanguageId { get; set; }+ public string DefaultWarehouseId { get; set; }+ public int DisplayOrder { get; set; }+ public string CompanyName { get; set; }+ public string CompanyAddress { get; set; }+ public string CompanyPhoneNumber { get; set; }+ public string CompanyRegNo { get; set; }+ public string CompanyVat { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/AddressDto.cs b/src/API/Grand.Api/DTOs/Customers/AddressDto.csindex ce31fa7ea..8433d2773 100644--- a/src/API/Grand.Api/DTOs/Customers/AddressDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/AddressDto.cs@@ -1,23 +1,21 @@--namespace Grand.Api.DTOs.Customers+namespace Grand.Api.DTOs.Customers;++public class AddressDto{- public class AddressDto- {- public string Id { get; set; }- public string FirstName { get; set; }- public string LastName { get; set; }- public string Email { get; set; }- public string Company { get; set; }- public string VatNumber { get; set; }- public string CountryId { get; set; }- public string StateProvinceId { get; set; }- public string City { get; set; }- public string Address1 { get; set; }- public string Address2 { get; set; }- public string ZipPostalCode { get; set; }- public string PhoneNumber { get; set; }- public string FaxNumber { get; set; }- public string Note { get; set; }- public int AddressType { get; set; }- }-}+ public string Id { get; set; }+ public string FirstName { get; set; }+ public string LastName { get; set; }+ public string Email { get; set; }+ public string Company { get; set; }+ public string VatNumber { get; set; }+ public string CountryId { get; set; }+ public string StateProvinceId { get; set; }+ public string City { get; set; }+ public string Address1 { get; set; }+ public string Address2 { get; set; }+ public string ZipPostalCode { get; set; }+ public string PhoneNumber { get; set; }+ public string FaxNumber { get; set; }+ public string Note { get; set; }+ public int AddressType { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/CustomerDto.cs b/src/API/Grand.Api/DTOs/Customers/CustomerDto.csindex eaa07179e..8545e2543 100644--- a/src/API/Grand.Api/DTOs/Customers/CustomerDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/CustomerDto.cs@@ -1,38 +1,38 @@using Grand.Api.Models;using System.ComponentModel.DataAnnotations;-namespace Grand.Api.DTOs.Customers+namespace Grand.Api.DTOs.Customers;++public class CustomerDto : BaseApiEntityModel{- public class CustomerDto : BaseApiEntityModel- {- public Guid CustomerGuid { get; set; } = Guid.NewGuid();- public string Username { get; set; }- [Key]- public string Email { get; set; }- public string AdminComment { get; set; }- public bool IsTaxExempt { get; set; }- public bool FreeShipping { get; set; }- public string AffiliateId { get; set; }- public string VendorId { get; set; }- public string StoreId { get; set; }- public bool Active { get; set; }- public bool Deleted { get; set; }- public string Gender { get; set; }- public string FirstName { get; set; }- public string LastName { get; set; }- public DateTime? DateOfBirth { get; set; }- public string Company { get; set; }- public string StreetAddress { get; set; }- public string StreetAddress2 { get; set; }- public string ZipPostalCode { get; set; }- public string City { get; set; }- public string CountryId { get; set; }- public string StateProvinceId { get; set; }- public string Phone { get; set; }- public string Fax { get; set; }- public string VatNumber { get; set; }- public string VatNumberStatusId { get; set; }- public IList<string> Groups { get; set; } = new List<string>();- public IList<AddressDto> Addresses { get; set; } = new List<AddressDto>();- }-}+ public Guid CustomerGuid { get; set; } = Guid.NewGuid();+ public string Username { get; set; }++ [Key] public string Email { get; set; }++ public string AdminComment { get; set; }+ public bool IsTaxExempt { get; set; }+ public bool FreeShipping { get; set; }+ public string AffiliateId { get; set; }+ public string VendorId { get; set; }+ public string StoreId { get; set; }+ public bool Active { get; set; }+ public bool Deleted { get; set; }+ public string Gender { get; set; }+ public string FirstName { get; set; }+ public string LastName { get; set; }+ public DateTime? DateOfBirth { get; set; }+ public string Company { get; set; }+ public string StreetAddress { get; set; }+ public string StreetAddress2 { get; set; }+ public string ZipPostalCode { get; set; }+ public string City { get; set; }+ public string CountryId { get; set; }+ public string StateProvinceId { get; set; }+ public string Phone { get; set; }+ public string Fax { get; set; }+ public string VatNumber { get; set; }+ public string VatNumberStatusId { get; set; }+ public IList<string> Groups { get; set; } = new List<string>();+ public IList<AddressDto> Addresses { get; set; } = new List<AddressDto>();+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/CustomerGroupDto.cs b/src/API/Grand.Api/DTOs/Customers/CustomerGroupDto.csindex 88ae924c8..03b41c4db 100644--- a/src/API/Grand.Api/DTOs/Customers/CustomerGroupDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/CustomerGroupDto.cs@@ -1,15 +1,14 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Customers+namespace Grand.Api.DTOs.Customers;++public class CustomerGroupDto : BaseApiEntityModel{- public class CustomerGroupDto : BaseApiEntityModel- {- public string Name { get; set; }- public bool FreeShipping { get; set; }- public bool TaxExempt { get; set; }- public bool Active { get; set; }- public bool IsSystem { get; set; }- public string SystemName { get; set; }- public bool EnablePasswordLifetime { get; set; }- }-}+ public string Name { get; set; }+ public bool FreeShipping { get; set; }+ public bool TaxExempt { get; set; }+ public bool Active { get; set; }+ public bool IsSystem { get; set; }+ public string SystemName { get; set; }+ public bool EnablePasswordLifetime { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/DeleteAddressDto.cs b/src/API/Grand.Api/DTOs/Customers/DeleteAddressDto.csindex 220900138..4995414d0 100644--- a/src/API/Grand.Api/DTOs/Customers/DeleteAddressDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/DeleteAddressDto.cs@@ -1,8 +1,6 @@-namespace Grand.Api.DTOs.Customers-{- public class DeleteAddressDto- {- public string AddressId { get; set; }+namespace Grand.Api.DTOs.Customers;- }-}+public class DeleteAddressDto+{+ public string AddressId { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/PasswordDto.cs b/src/API/Grand.Api/DTOs/Customers/PasswordDto.csindex 53da68687..8f65ebbbb 100644--- a/src/API/Grand.Api/DTOs/Customers/PasswordDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/PasswordDto.cs@@ -1,8 +1,6 @@-namespace Grand.Api.DTOs.Customers-{- public class PasswordDto- {- public string Password { get; set; }+namespace Grand.Api.DTOs.Customers;- }-}+public class PasswordDto+{+ public string Password { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Customers/VendorDto.cs b/src/API/Grand.Api/DTOs/Customers/VendorDto.csindex 585a77fe6..8108a782c 100644--- a/src/API/Grand.Api/DTOs/Customers/VendorDto.cs+++ b/src/API/Grand.Api/DTOs/Customers/VendorDto.cs@@ -1,24 +1,23 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Customers+namespace Grand.Api.DTOs.Customers;++public class VendorDto : BaseApiEntityModel{- public class VendorDto : BaseApiEntityModel- {- public string Name { get; set; }- public string SeName { get; set; }- public string PictureId { get; set; }- public string Email { get; set; }- public string Description { get; set; }- public string StoreId { get; set; }- public string AdminComment { get; set; }- public bool Active { get; set; }- public bool Deleted { get; set; }- public int DisplayOrder { get; set; }- public bool AllowCustomerReviews { get; set; }- public int ApprovedRatingSum { get; set; }- public int NotApprovedRatingSum { get; set; }- public int ApprovedTotalReviews { get; set; }- public int NotApprovedTotalReviews { get; set; }- public virtual AddressDto Address { get; set; }- }-}+ public string Name { get; set; }+ public string SeName { get; set; }+ public string PictureId { get; set; }+ public string Email { get; set; }+ public string Description { get; set; }+ public string StoreId { get; set; }+ public string AdminComment { get; set; }+ public bool Active { get; set; }+ public bool Deleted { get; set; }+ public int DisplayOrder { get; set; }+ public bool AllowCustomerReviews { get; set; }+ public int ApprovedRatingSum { get; set; }+ public int NotApprovedRatingSum { get; set; }+ public int ApprovedTotalReviews { get; set; }+ public int NotApprovedTotalReviews { get; set; }+ public virtual AddressDto Address { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Shipping/DeliveryDateDto.cs b/src/API/Grand.Api/DTOs/Shipping/DeliveryDateDto.csindex a2168834a..499892684 100644--- a/src/API/Grand.Api/DTOs/Shipping/DeliveryDateDto.cs+++ b/src/API/Grand.Api/DTOs/Shipping/DeliveryDateDto.cs@@ -1,11 +1,10 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Shipping+namespace Grand.Api.DTOs.Shipping;++public class DeliveryDateDto : BaseApiEntityModel{- public class DeliveryDateDto : BaseApiEntityModel- {- public string Name { get; set; }- public int DisplayOrder { get; set; }- public string ColorSquaresRgb { get; set; }- }-}+ public string Name { get; set; }+ public int DisplayOrder { get; set; }+ public string ColorSquaresRgb { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Shipping/PickupPointDto.cs b/src/API/Grand.Api/DTOs/Shipping/PickupPointDto.csindex b15f38c47..978959e5c 100644--- a/src/API/Grand.Api/DTOs/Shipping/PickupPointDto.cs+++ b/src/API/Grand.Api/DTOs/Shipping/PickupPointDto.cs@@ -1,15 +1,14 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Shipping+namespace Grand.Api.DTOs.Shipping;++public class PickupPointDto : BaseApiEntityModel{- public class PickupPointDto : BaseApiEntityModel- {- public string Name { get; set; }- public string Description { get; set; }- public string AdminComment { get; set; }- public string WarehouseId { get; set; }- public string StoreId { get; set; }- public double PickupFee { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string Description { get; set; }+ public string AdminComment { get; set; }+ public string WarehouseId { get; set; }+ public string StoreId { get; set; }+ public double PickupFee { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Shipping/ShippingMethodDto.cs b/src/API/Grand.Api/DTOs/Shipping/ShippingMethodDto.csindex 5733f92b1..feeb70af5 100644--- a/src/API/Grand.Api/DTOs/Shipping/ShippingMethodDto.cs+++ b/src/API/Grand.Api/DTOs/Shipping/ShippingMethodDto.cs@@ -1,11 +1,10 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Shipping+namespace Grand.Api.DTOs.Shipping;++public class ShippingMethodDto : BaseApiEntityModel{- public class ShippingMethodDto : BaseApiEntityModel- {- public string Name { get; set; }- public string Description { get; set; }- public int DisplayOrder { get; set; }- }-}+ public string Name { get; set; }+ public string Description { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/Shipping/WarehouseDto.cs b/src/API/Grand.Api/DTOs/Shipping/WarehouseDto.csindex 9002f7289..ceac8c3fc 100644--- a/src/API/Grand.Api/DTOs/Shipping/WarehouseDto.cs+++ b/src/API/Grand.Api/DTOs/Shipping/WarehouseDto.cs@@ -1,10 +1,9 @@using Grand.Api.Models;-namespace Grand.Api.DTOs.Shipping+namespace Grand.Api.DTOs.Shipping;++public class WarehouseDto : BaseApiEntityModel{- public class WarehouseDto : BaseApiEntityModel- {- public string Name { get; set; }- public string AdminComment { get; set; }- }-}+ public string Name { get; set; }+ public string AdminComment { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/DTOs/TokenDto.cs b/src/API/Grand.Api/DTOs/TokenDto.csindex e919a0c13..d81318096 100644--- a/src/API/Grand.Api/DTOs/TokenDto.cs+++ b/src/API/Grand.Api/DTOs/TokenDto.cs@@ -1,8 +1,7 @@-namespace Grand.Api.DTOs+namespace Grand.Api.DTOs;++public class TokenDto{- public class TokenDto- {- public string AccessToken { get; set; }- public string RefreshToken { get; set; }- }-}+ public string AccessToken { get; set; }+ public string RefreshToken { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs b/src/API/Grand.Api/Extensions/AddParamOperationFilter.csindex cdf188a28..a99078bdd 100644--- a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs+++ b/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs@@ -2,106 +2,103 @@using Microsoft.OpenApi.Models;using Swashbuckle.AspNetCore.SwaggerGen;-namespace Grand.Api.Extensions+namespace Grand.Api.Extensions;++public class AddParamOperationFilter : IOperationFilter{- public class AddParamOperationFilter : IOperationFilter+ public void Apply(OpenApiOperation operation, OperationFilterContext context){- public void Apply(OpenApiOperation operation, OperationFilterContext context)+ switch (context.ApiDescription.GroupName){- switch (context.ApiDescription.GroupName)- {- case "v1" when context.ApiDescription.HttpMethod == "GET" &&- context.ApiDescription.ParameterDescriptions.Count == 0:- ApplyV1(operation);- break;- case "v2" when context.ApiDescription.HttpMethod == "POST":- ApplyV2(operation, context);- break;- }+ case "v1" when context.ApiDescription.HttpMethod == "GET" &&+ context.ApiDescription.ParameterDescriptions.Count == 0:+ ApplyV1(operation);+ break;+ case "v2" when context.ApiDescription.HttpMethod == "POST":+ ApplyV2(operation, context);+ break;}+ }- private void ApplyV1(OpenApiOperation operation)- {- operation.Parameters.Add(new OpenApiParameter {- Name = "$top",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Show only the first n items.",- Required = false,- Schema = new OpenApiSchema {- Minimum = 0,- Type = "integer"- }- });- operation.Parameters.Add(new OpenApiParameter {- Name = "$skip",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Skip the first n items",- Required = false,- Schema = new OpenApiSchema {- Minimum = 0,- Type = "integer"- }- });- operation.Parameters.Add(new OpenApiParameter {- Name = "$count",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Include count of items",- Required = false,- Schema = new OpenApiSchema {- Type = "boolean"- }- });- operation.Parameters.Add(new OpenApiParameter {- Name = "$orderby",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Order items by property values",- Required = false,- Schema = new OpenApiSchema {- Type = "string"- }- });- operation.Parameters.Add(new OpenApiParameter {- Name = "$filter",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Filter items by property values",- Required = false,- Schema = new OpenApiSchema {- Type = "string"- }- });+ private void ApplyV1(OpenApiOperation operation)+ {+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$top",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Show only the first n items.",+ Required = false,+ Schema = new OpenApiSchema {+ Minimum = 0,+ Type = "integer"+ }+ });+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$skip",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Skip the first n items",+ Required = false,+ Schema = new OpenApiSchema {+ Minimum = 0,+ Type = "integer"+ }+ });+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$count",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Include count of items",+ Required = false,+ Schema = new OpenApiSchema {+ Type = "boolean"+ }+ });+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$orderby",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Order items by property values",+ Required = false,+ Schema = new OpenApiSchema {+ Type = "string"+ }+ });+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$filter",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Filter items by property values",+ Required = false,+ Schema = new OpenApiSchema {+ Type = "string"+ }+ });+ operation.Parameters.Add(new OpenApiParameter {+ Name = "$select",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Select specific properties from the model",+ Required = false,+ Schema = new OpenApiSchema {+ Type = "string"+ }+ });+ }++ private void ApplyV2(OpenApiOperation operation, OperationFilterContext context)+ {+ operation.Parameters ??= new List<OpenApiParameter>();++ if (context.MethodInfo.GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), true).Any())operation.Parameters.Add(new OpenApiParameter {- Name = "$select",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Select specific properties from the model",- Required = false,+ Name = "X-CSRF-TOKEN",+ In = ParameterLocation.Header,+ Required = true,Schema = new OpenApiSchema {- Type = "string"+ Type = "string",+ Description = "Antiforgery token"}});- }-- private void ApplyV2(OpenApiOperation operation, OperationFilterContext context)- {- operation.Parameters ??= new List<OpenApiParameter>();-- if (context.MethodInfo.GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), true).Any())- {- operation.Parameters.Add(new OpenApiParameter {- Name = "X-CSRF-TOKEN",- In = ParameterLocation.Header,- Required = true,- Schema = new OpenApiSchema {- Type = "string",- Description = "Antiforgery token"- }- });- }- }}}\ No newline at end of filediff --git a/src/API/Grand.Api/Extensions/MappingExtensions.cs b/src/API/Grand.Api/Extensions/MappingExtensions.csindex e199f3167..188031bea 100644--- a/src/API/Grand.Api/Extensions/MappingExtensions.cs+++ b/src/API/Grand.Api/Extensions/MappingExtensions.cs@@ -7,222 +7,227 @@ using Grand.Domain.Customers;using Grand.Domain.Media;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Extensions+namespace Grand.Api.Extensions;++public static class MappingExtensions{- public static class MappingExtensions+ #region Picture++ public static PictureDto ToModel(this Picture entity)+ {+ return entity.MapTo<Picture, PictureDto>();+ }++ #endregion++ #region Product++ public static ProductDto ToModel(this Product entity)+ {+ return entity.MapTo<Product, ProductDto>();+ }++ public static Product ToEntity(this ProductDto model)+ {+ return model.MapTo<ProductDto, Product>();+ }++ public static Product ToEntity(this ProductDto model, Product destination)+ {+ return model.MapTo(destination);+ }++ #endregion++ #region Category++ public static CategoryDto ToModel(this Category entity)+ {+ return entity.MapTo<Category, CategoryDto>();+ }++ public static Category ToEntity(this CategoryDto model)+ {+ return model.MapTo<CategoryDto, Category>();+ }++ public static Category ToEntity(this CategoryDto model, Category destination)+ {+ return model.MapTo(destination);+ }++ #endregion++ #region Brand++ public static BrandDto ToModel(this Brand entity)+ {+ return entity.MapTo<Brand, BrandDto>();+ }++ public static Brand ToEntity(this BrandDto model)+ {+ return model.MapTo<BrandDto, Brand>();+ }++ public static Brand ToEntity(this BrandDto model, Brand destination)+ {+ return model.MapTo(destination);+ }++ #endregion++ #region Collection++ public static CollectionDto ToModel(this Collection entity)+ {+ return entity.MapTo<Collection, CollectionDto>();+ }++ public static Collection ToEntity(this CollectionDto model)+ {+ return model.MapTo<CollectionDto, Collection>();+ }++ public static Collection ToEntity(this CollectionDto model, Collection destination)+ {+ return model.MapTo(destination);+ }++ #endregion++ #region Product attribute++ public static ProductAttributeDto ToModel(this ProductAttribute entity)+ {+ return entity.MapTo<ProductAttribute, ProductAttributeDto>();+ }++ public static ProductAttribute ToEntity(this ProductAttributeDto model){+ return model.MapTo<ProductAttributeDto, ProductAttribute>();+ }++ public static ProductAttribute ToEntity(this ProductAttributeDto model, ProductAttribute destination)+ {+ return model.MapTo(destination);+ }++ #endregion++ #region Product attribute mapping- #region Product+ public static ProductAttributeMappingDto ToModel(this ProductAttributeMapping entity)+ {+ return entity.MapTo<ProductAttributeMapping, ProductAttributeMappingDto>();+ }- public static ProductDto ToModel(this Product entity)- {- return entity.MapTo<Product, ProductDto>();- }+ public static ProductAttributeMapping ToEntity(this ProductAttributeMappingDto model)+ {+ return model.MapTo<ProductAttributeMappingDto, ProductAttributeMapping>();+ }- public static Product ToEntity(this ProductDto model)- {- return model.MapTo<ProductDto, Product>();- }+ public static ProductAttributeMapping ToEntity(this ProductAttributeMappingDto model,+ ProductAttributeMapping destination)+ {+ return model.MapTo(destination);+ }- public static Product ToEntity(this ProductDto model, Product destination)- {- return model.MapTo(destination);- }+ #endregion- #endregion+ #region Specification attribute- #region Category+ public static SpecificationAttributeDto ToModel(this SpecificationAttribute entity)+ {+ return entity.MapTo<SpecificationAttribute, SpecificationAttributeDto>();+ }- public static CategoryDto ToModel(this Category entity)- {- return entity.MapTo<Category, CategoryDto>();- }+ public static SpecificationAttribute ToEntity(this SpecificationAttributeDto model)+ {+ return model.MapTo<SpecificationAttributeDto, SpecificationAttribute>();+ }- public static Category ToEntity(this CategoryDto model)- {- return model.MapTo<CategoryDto, Category>();- }+ public static SpecificationAttribute ToEntity(this SpecificationAttributeDto model,+ SpecificationAttribute destination)+ {+ return model.MapTo(destination);+ }- public static Category ToEntity(this CategoryDto model, Category destination)- {- return model.MapTo(destination);- }+ #endregion- #endregion+ #region Tier prices- #region Brand+ public static ProductTierPriceDto ToModel(this TierPrice entity)+ {+ return entity.MapTo<TierPrice, ProductTierPriceDto>();+ }- public static BrandDto ToModel(this Brand entity)- {- return entity.MapTo<Brand, BrandDto>();- }+ public static TierPrice ToEntity(this ProductTierPriceDto model)+ {+ return model.MapTo<ProductTierPriceDto, TierPrice>();+ }- public static Brand ToEntity(this BrandDto model)- {- return model.MapTo<BrandDto, Brand>();- }+ public static TierPrice ToEntity(this ProductTierPriceDto model, TierPrice destination)+ {+ return model.MapTo(destination);+ }- public static Brand ToEntity(this BrandDto model, Brand destination)- {- return model.MapTo(destination);- }+ #endregion- #endregion+ #region Customer group- #region Collection- public static CollectionDto ToModel(this Collection entity)- {- return entity.MapTo<Collection, CollectionDto>();- }+ public static CustomerGroupDto ToModel(this CustomerGroup entity)+ {+ return entity.MapTo<CustomerGroup, CustomerGroupDto>();+ }- public static Collection ToEntity(this CollectionDto model)- {- return model.MapTo<CollectionDto, Collection>();- }+ public static CustomerGroup ToEntity(this CustomerGroupDto model)+ {+ return model.MapTo<CustomerGroupDto, CustomerGroup>();+ }- public static Collection ToEntity(this CollectionDto model, Collection destination)- {- return model.MapTo(destination);- }+ public static CustomerGroup ToEntity(this CustomerGroupDto model, CustomerGroup destination)+ {+ return model.MapTo(destination);+ }- #endregion+ #endregion- #region Product attribute- public static ProductAttributeDto ToModel(this ProductAttribute entity)- {- return entity.MapTo<ProductAttribute, ProductAttributeDto>();- }+ #region Customer- public static ProductAttribute ToEntity(this ProductAttributeDto model)- {- return model.MapTo<ProductAttributeDto, ProductAttribute>();- }+ public static CustomerDto ToModel(this Customer entity)+ {+ return entity.MapTo<Customer, CustomerDto>();+ }- public static ProductAttribute ToEntity(this ProductAttributeDto model, ProductAttribute destination)- {- return model.MapTo(destination);- }+ public static Customer ToEntity(this CustomerDto model)+ {+ return model.MapTo<CustomerDto, Customer>();+ }- #endregion+ public static Customer ToEntity(this CustomerDto model, Customer destination)+ {+ return model.MapTo(destination);+ }- #region Product attribute mapping+ #endregion- public static ProductAttributeMappingDto ToModel(this ProductAttributeMapping entity)- {- return entity.MapTo<ProductAttributeMapping, ProductAttributeMappingDto>();- }-- public static ProductAttributeMapping ToEntity(this ProductAttributeMappingDto model)- {- return model.MapTo<ProductAttributeMappingDto, ProductAttributeMapping>();- }-- public static ProductAttributeMapping ToEntity(this ProductAttributeMappingDto model, ProductAttributeMapping destination)- {- return model.MapTo(destination);- }-- #endregion-- #region Specification attribute- public static SpecificationAttributeDto ToModel(this SpecificationAttribute entity)- {- return entity.MapTo<SpecificationAttribute, SpecificationAttributeDto>();- }-- public static SpecificationAttribute ToEntity(this SpecificationAttributeDto model)- {- return model.MapTo<SpecificationAttributeDto, SpecificationAttribute>();- }-- public static SpecificationAttribute ToEntity(this SpecificationAttributeDto model, SpecificationAttribute destination)- {- return model.MapTo(destination);- }-- #endregion-- #region Tier prices-- public static ProductTierPriceDto ToModel(this TierPrice entity)- {- return entity.MapTo<TierPrice, ProductTierPriceDto>();- }-- public static TierPrice ToEntity(this ProductTierPriceDto model)- {- return model.MapTo<ProductTierPriceDto, TierPrice>();- }-- public static TierPrice ToEntity(this ProductTierPriceDto model, TierPrice destination)- {- return model.MapTo(destination);- }-- #endregion-- #region Customer group- public static CustomerGroupDto ToModel(this CustomerGroup entity)- {- return entity.MapTo<CustomerGroup, CustomerGroupDto>();- }-- public static CustomerGroup ToEntity(this CustomerGroupDto model)- {- return model.MapTo<CustomerGroupDto, CustomerGroup>();- }-- public static CustomerGroup ToEntity(this CustomerGroupDto model, CustomerGroup destination)- {- return model.MapTo(destination);- }-- #endregion-- #region Customer-- public static CustomerDto ToModel(this Customer entity)- {- return entity.MapTo<Customer, CustomerDto>();- }-- public static Customer ToEntity(this CustomerDto model)- {- return model.MapTo<CustomerDto, Customer>();- }-- public static Customer ToEntity(this CustomerDto model, Customer destination)- {- return model.MapTo(destination);- }+ #region Customer address- #endregion+ public static AddressDto ToModel(this Address entity)+ {+ return entity.MapTo<Address, AddressDto>();+ }- #region Customer address- public static AddressDto ToModel(this Address entity)- {- return entity.MapTo<Address, AddressDto>();- }+ public static Address ToEntity(this AddressDto model)+ {+ return model.MapTo<AddressDto, Address>();+ }- public static Address ToEntity(this AddressDto model)- {- return model.MapTo<AddressDto, Address>();- }- public static Address ToEntity(this AddressDto model, Address destination)- {- return model.MapTo(destination);- }--- #endregion+ public static Address ToEntity(this AddressDto model, Address destination)+ {+ return model.MapTo(destination);+ }- #region Picture-- public static PictureDto ToModel(this Picture entity)- {- return entity.MapTo<Picture, PictureDto>();- }-- #endregion- }-}+ #endregion+}\ No newline at end of filediff --git a/src/API/Grand.Api/Extensions/SwaggerODataControllerDocumentFilter.cs b/src/API/Grand.Api/Extensions/SwaggerODataControllerDocumentFilter.csindex 8d64550a9..2d3c96e40 100644--- a/src/API/Grand.Api/Extensions/SwaggerODataControllerDocumentFilter.cs+++ b/src/API/Grand.Api/Extensions/SwaggerODataControllerDocumentFilter.cs@@ -1,5 +1,4 @@-using Microsoft.AspNetCore.Mvc.ApiExplorer;-using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.Controllers;using Microsoft.OpenApi.Models;using Swashbuckle.AspNetCore.SwaggerGen;@@ -10,22 +9,16 @@ public class SwaggerODataControllerDocumentFilter : IDocumentFilterpublic void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context){// remove controller- foreach (ApiDescription apiDescription in context.ApiDescriptions)+ foreach (var apiDescription in context.ApiDescriptions){var actionDescriptor = (ControllerActionDescriptor)apiDescription.ActionDescriptor;if (actionDescriptor.ControllerName == "Metadata")- {swaggerDoc.Paths.Remove($"/{apiDescription.RelativePath}");- }}// remove schemasforeach (var (key, _) in swaggerDoc.Components.Schemas)- {if (key.Contains("Edm") || key.Contains("OData"))- {swaggerDoc.Components.Schemas.Remove(key);- }- }}}\ No newline at end of filediff --git a/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs b/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.csindex c5f044c0b..fe4175564 100644--- a/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs+++ b/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs@@ -6,100 +6,97 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Api.Filters+namespace Grand.Api.Filters;++/// <summary>+/// Represents a filter attribute that confirms access to the admin panel+/// </summary>+public class AuthorizeApiAdminAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that confirms access to the admin panel+ /// Create instance of the filter attribute/// </summary>- public class AuthorizeApiAdminAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public AuthorizeApiAdminAttribute(bool ignore = false) : base(typeof(AuthorizeApiAdminFilter)){- private readonly bool _ignoreFilter;+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public AuthorizeApiAdminAttribute(bool ignore = false) : base(typeof(AuthorizeApiAdminFilter))+ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter that confirms access to the admin panel+ /// </summary>+ private class AuthorizeApiAdminFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public AuthorizeApiAdminFilter(bool ignoreFilter, IPermissionService permissionService,+ SecuritySettings securitySettings){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _securitySettings = securitySettings;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter that confirms access to the admin panel+ /// Called early in the filter pipeline to confirm request is authorized/// </summary>- private class AuthorizeApiAdminFilter : IAsyncAuthorizationFilter+ /// <param name="filterContext">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly SecuritySettings _securitySettings;-- #endregion+ ArgumentNullException.ThrowIfNull(filterContext);- #region Ctor+ //check whether this filter has been overridden for the action+ var actionFilter = filterContext.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<AuthorizeApiAdminAttribute>().FirstOrDefault();- public AuthorizeApiAdminFilter(bool ignoreFilter, IPermissionService permissionService, SecuritySettings securitySettings)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _securitySettings = securitySettings;- }+ //ignore filter (the action is available even if a customer hasn't access to the admin area)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;- #endregion+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- #region Methods-- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="filterContext">Authorization filter context</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)+ //there is AdminAuthorizeFilter, so check access+ if (filterContext.Filters.Any(filter => filter is AuthorizeApiAdminFilter)){- ArgumentNullException.ThrowIfNull(filterContext);+ //authorize permission of access to the admin area+ if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme);- //check whether this filter has been overridden for the action- var actionFilter = filterContext.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<AuthorizeApiAdminAttribute>().FirstOrDefault();+ //get allowed IP addresses+ var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;- //ignore filter (the action is available even if a customer hasn't access to the admin area)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ //there are no restrictions+ if (ipAddresses == null || !ipAddresses.Any())return;- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //there is AdminAuthorizeFilter, so check access- if (filterContext.Filters.Any(filter => filter is AuthorizeApiAdminFilter))- {- //authorize permission of access to the admin area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))- filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme);-- //get allowed IP addresses- var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;-- //there are no restrictions- if (ipAddresses == null || !ipAddresses.Any())- return;+ //whether current IP is allowed+ var currentIp = filterContext.HttpContext?.Connection?.RemoteIpAddress?.ToString();+ if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))+ filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme);+ }+ }- //whether current IP is allowed- var currentIp = filterContext.HttpContext?.Connection?.RemoteIpAddress?.ToString();- if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))- filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme);+ #endregion- }- }+ #region Fields- #endregion- }+ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly SecuritySettings _securitySettings;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs b/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.csindex 7e5ff8f66..ddfeca6e1 100644--- a/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs+++ b/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs@@ -8,117 +8,117 @@ using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.IdentityModel.Tokens;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++public class ApiAuthenticationRegistrar : IAuthenticationBuilder{- public class ApiAuthenticationRegistrar : IAuthenticationBuilder+ public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration){- public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration)+ builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>{- builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>- {- var config = new BackendAPIConfig();- configuration.GetSection("BackendAPI").Bind(config);- options.TokenValidationParameters = new TokenValidationParameters- {- ValidateIssuer = config.ValidateIssuer,- ValidateAudience = config.ValidateAudience,- ValidateLifetime = true,- ValidateIssuerSigningKey = true,- ValidIssuer = config.ValidIssuer,- ValidAudience = config.ValidAudience,- IssuerSigningKey = JwtSecurityKey.Create(config.SecretKey)- };+ var config = new BackendAPIConfig();+ configuration.GetSection("BackendAPI").Bind(config);+ options.TokenValidationParameters = new TokenValidationParameters {+ ValidateIssuer = config.ValidateIssuer,+ ValidateAudience = config.ValidateAudience,+ ValidateLifetime = true,+ ValidateIssuerSigningKey = true,+ ValidIssuer = config.ValidIssuer,+ ValidAudience = config.ValidAudience,+ IssuerSigningKey = JwtSecurityKey.Create(config.SecretKey)+ };- options.Events = new JwtBearerEvents+ options.Events = new JwtBearerEvents {+ OnAuthenticationFailed = async context =>{- OnAuthenticationFailed = async context =>- {- context.NoResult();- context.Response.StatusCode = 401;- context.Response.ContentType = "text/plain";- await context.Response.WriteAsync(context.Exception.Message);- },- OnChallenge = context =>- {- context.HandleResponse();- return Task.CompletedTask;- },- OnTokenValidated = async context =>+ context.NoResult();+ context.Response.StatusCode = 401;+ context.Response.ContentType = "text/plain";+ await context.Response.WriteAsync(context.Exception.Message);+ },+ OnChallenge = context =>+ {+ context.HandleResponse();+ return Task.CompletedTask;+ },+ OnTokenValidated = async context =>+ {+ try{-- try+ if (config.Enabled){- if (config.Enabled)- {- var jwtAuthentication = context.HttpContext.RequestServices.GetRequiredService<IJwtBearerAuthenticationService>();- if (!await jwtAuthentication.Valid(context))- throw new Exception(await jwtAuthentication.ErrorMessage());- }- else- throw new Exception("API is disable");+ var jwtAuthentication = context.HttpContext.RequestServices+ .GetRequiredService<IJwtBearerAuthenticationService>();+ if (!await jwtAuthentication.Valid(context))+ throw new Exception(await jwtAuthentication.ErrorMessage());}- catch (Exception ex)+ else{- throw new Exception(ex.Message);+ throw new Exception("API is disable");}}- };- });+ catch (Exception ex)+ {+ throw new Exception(ex.Message);+ }+ }+ };+ });- builder.AddJwtBearer(FrontendAPIConfig.AuthenticationScheme, options =>- {- var config = new FrontendAPIConfig();- configuration.GetSection("FrontendAPI").Bind(config);- options.TokenValidationParameters = new TokenValidationParameters {- ValidateIssuer = config.ValidateIssuer,- ValidateAudience = config.ValidateAudience,- ValidateLifetime = true,- ValidateIssuerSigningKey = true,- ValidIssuer = config.ValidIssuer,- ValidAudience = config.ValidAudience,- IssuerSigningKey = JwtSecurityKey.Create(config.SecretKey),- ClockSkew = TimeSpan.Zero- };+ builder.AddJwtBearer(FrontendAPIConfig.AuthenticationScheme, options =>+ {+ var config = new FrontendAPIConfig();+ configuration.GetSection("FrontendAPI").Bind(config);+ options.TokenValidationParameters = new TokenValidationParameters {+ ValidateIssuer = config.ValidateIssuer,+ ValidateAudience = config.ValidateAudience,+ ValidateLifetime = true,+ ValidateIssuerSigningKey = true,+ ValidIssuer = config.ValidIssuer,+ ValidAudience = config.ValidAudience,+ IssuerSigningKey = JwtSecurityKey.Create(config.SecretKey),+ ClockSkew = TimeSpan.Zero+ };- options.Events = new JwtBearerEvents {- OnAuthenticationFailed = async context =>- {- context.NoResult();- context.Response.StatusCode = 401;- context.Response.ContentType = "text/plain";- await context.Response.WriteAsync(context.Exception.Message);- },- OnChallenge = context =>- {- context.HandleResponse();- return Task.CompletedTask;- },- OnTokenValidated = async context =>+ options.Events = new JwtBearerEvents {+ OnAuthenticationFailed = async context =>+ {+ context.NoResult();+ context.Response.StatusCode = 401;+ context.Response.ContentType = "text/plain";+ await context.Response.WriteAsync(context.Exception.Message);+ },+ OnChallenge = context =>+ {+ context.HandleResponse();+ return Task.CompletedTask;+ },+ OnTokenValidated = async context =>+ {+ try{- try+ if (config.Enabled){- if (config.Enabled)- {- var jwtAuthentication = context.HttpContext.RequestServices.GetRequiredService<IJwtBearerCustomerAuthenticationService>();- var isValid = await jwtAuthentication.Valid(context);- if (!isValid)- throw new Exception(await jwtAuthentication.ErrorMessage());- }- else- throw new Exception("API is disable");+ var jwtAuthentication = context.HttpContext.RequestServices+ .GetRequiredService<IJwtBearerCustomerAuthenticationService>();+ var isValid = await jwtAuthentication.Valid(context);+ if (!isValid)+ throw new Exception(await jwtAuthentication.ErrorMessage());}- catch (Exception ex)+ else{- throw new Exception(ex.Message);+ throw new Exception("API is disable");}}- };- });--- }- public int Priority => 900;-+ catch (Exception ex)+ {+ throw new Exception(ex.Message);+ }+ }+ };+ });}-}++ public int Priority => 900;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/ApiProviderStartup.cs b/src/API/Grand.Api/Infrastructure/ApiProviderStartup.csindex bed0895d0..990469c15 100644--- a/src/API/Grand.Api/Infrastructure/ApiProviderStartup.cs+++ b/src/API/Grand.Api/Infrastructure/ApiProviderStartup.cs@@ -1,5 +1,5 @@-using Grand.Infrastructure;-using Grand.Api.ApiExplorer;+using Grand.Api.ApiExplorer;+using Grand.Infrastructure;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc.ApiExplorer;@@ -7,39 +7,38 @@ using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.DependencyInjection.Extensions;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++/// <summary>+/// Represents object for the configuring api description provider on application+/// </summary>+public class ApiProviderStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring api description provider on application+ /// Add and configure any of the middleware/// </summary>- public class ApiProviderStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <summary>- /// Add and configure any of the middleware- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration root of the application</param>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- //Swagger - api description provider- services.TryAddEnumerable(ServiceDescriptor.Transient<IApiDescriptionProvider, MetadataApiDescriptionProvider>());- }-- /// <summary>- /// Configure the using of added middleware- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- /// <param name="webHostEnvironment">WebHostEnvironment</param>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {+ //Swagger - api description provider+ services.TryAddEnumerable(+ ServiceDescriptor.Transient<IApiDescriptionProvider, MetadataApiDescriptionProvider>());+ }- }+ /// <summary>+ /// Configure the using of added middleware+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 89;- public bool BeforeConfigure => true;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 89;- }-}+ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/DependencyEdmModel.cs b/src/API/Grand.Api/Infrastructure/DependencyEdmModel.csindex ca93394da..705c6c9d2 100644--- a/src/API/Grand.Api/Infrastructure/DependencyEdmModel.cs+++ b/src/API/Grand.Api/Infrastructure/DependencyEdmModel.cs@@ -7,368 +7,387 @@ using Grand.Domain.Catalog;using Grand.Infrastructure.Configuration;using Microsoft.OData.ModelBuilder;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++public class DependencyEdmModel : IDependencyEdmModel{- public class DependencyEdmModel : IDependencyEdmModel+ public void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig){- protected void RegisterCommon(ODataConventionModelBuilder builder)+ if (apiConfig.SystemModel){- #region Language model+ RegisterCommon(builder);+ RegisterProduct(builder);+ RegisterCatalog(builder);+ RegisterCustomers(builder);+ RegisterShipping(builder);+ }+ }- builder.EntitySet<LanguageDto>("Language");+ public int Order => 0;- #endregion+ protected void RegisterCommon(ODataConventionModelBuilder builder)+ {+ #region Language model- #region Currency model+ builder.EntitySet<LanguageDto>("Language");- builder.EntitySet<CurrencyDto>("Currency");+ #endregion- #endregion+ #region Currency model- #region Store model+ builder.EntitySet<CurrencyDto>("Currency");- builder.EntitySet<StoreDto>("Store");-- #endregion+ #endregion- #region Country model+ #region Store model- builder.EntitySet<CountryDto>("Country");+ builder.EntitySet<StoreDto>("Store");- #endregion+ #endregion- #region layout model+ #region Country model- builder.EntitySet<LayoutDto>("CategoryLayout");- builder.EntitySet<LayoutDto>("CollectionLayout");- builder.EntitySet<LayoutDto>("ProductLayout");- builder.EntitySet<LayoutDto>("BrandLayout");+ builder.EntitySet<CountryDto>("Country");- #endregion+ #endregion- #region Picture model+ #region layout model- builder.EntitySet<PictureDto>("Picture");+ builder.EntitySet<LayoutDto>("CategoryLayout");+ builder.EntitySet<LayoutDto>("CollectionLayout");+ builder.EntitySet<LayoutDto>("ProductLayout");+ builder.EntitySet<LayoutDto>("BrandLayout");- #endregion- }- protected void RegisterProduct(ODataConventionModelBuilder builder)- {- builder.EntitySet<ProductDto>("Product");- var product = builder.EntityType<ProductDto>();- builder.ComplexType<ProductCategoryDto>();- builder.ComplexType<ProductCollectionDto>();- builder.ComplexType<ProductPictureDto>();- builder.ComplexType<ProductSpecificationAttributeDto>();- builder.ComplexType<ProductTierPriceDto>();- builder.ComplexType<ProductWarehouseInventoryDto>();- builder.ComplexType<ProductAttributeMappingDto>();- builder.ComplexType<ProductAttributeValueDto>();- builder.ComplexType<ProductAttributeCombinationDto>();- builder.ComplexType<ProductUpdateStock>();- builder.ComplexType<ProductCategoryDeleteDto>();- builder.ComplexType<ProductCollectionDeleteDto>();- builder.ComplexType<ProductPictureDeleteDto>();- builder.ComplexType<ProductSpecificationAttributeDeleteDto>();- builder.ComplexType<ProductTierPriceDeleteDto>();- builder.ComplexType<ProductAttributeMappingDeleteDto>();-- //update stock for product- ActionConfiguration updateStock = product.Action("UpdateStock");- updateStock.Parameter<string>("WarehouseId");- updateStock.Parameter<int>("Stock").Required();- updateStock.Returns<bool>();-- //insert/update/delete category- #region Product category- ActionConfiguration createCategory = product.Action("CreateProductCategory");- createCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();- createCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));- createCategory.Returns<bool>();-- ActionConfiguration updateCategory = product.Action("UpdateProductCategory");- updateCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();- updateCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));- updateCategory.Returns<bool>();-- ActionConfiguration deleteCategory = product.Action("DeleteProductCategory");- deleteCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();- deleteCategory.Returns<bool>();- #endregion-- //insert/update/delete collection- #region Product collection- ActionConfiguration createCollection = product.Action("CreateProductCollection");- createCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();- createCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));- createCollection.Returns<bool>();-- ActionConfiguration updateCollection = product.Action("UpdateProductCollection");- updateCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();- updateCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));- updateCollection.Returns<bool>();-- ActionConfiguration deleteCollection = product.Action("DeleteProductCollection");- deleteCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();- deleteCollection.Returns<bool>();- #endregion-- //insert/update/delete picture- #region Product picture- ActionConfiguration createPicture = product.Action("CreateProductPicture");- createPicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();- createPicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();- createPicture.Returns<bool>();-- ActionConfiguration updatePicture = product.Action("UpdateProductPicture");- updatePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();- updatePicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();- updatePicture.Returns<bool>();-- ActionConfiguration deletePicture = product.Action("DeleteProductPicture");- deletePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();- deletePicture.Returns<bool>();- #endregion-- #region Product specification- ActionConfiguration createSpecification = product.Action("CreateProductSpecification");- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id));- createSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));- //createSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();- createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId));- createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));-- createSpecification.Returns<bool>();-- ActionConfiguration updateSpecification = product.Action("UpdateProductSpecification");- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();- updateSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));- //updateSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();- updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId)).Required();- updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));- updateSpecification.Returns<bool>();-- ActionConfiguration deleteSpecification = product.Action("DeleteProductSpecification");- deleteSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();- deleteSpecification.Returns<bool>();- #endregion-- #region Product attribute mapping-- ActionConfiguration createProductAttributeMapping = product.Action("CreateProductAttributeMapping");- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id));- createProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));- createProductAttributeMapping.Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));- createProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.ValidationFileAllowedExtensions));- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));- createProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(nameof(ProductAttributeMappingDto.ProductAttributeValues));- createProductAttributeMapping.Returns<ProductAttributeMappingDto>();-- ActionConfiguration updateProductAttributeMapping = product.Action("UpdateProductAttributeMapping");- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id)).Required();- updateProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));- updateProductAttributeMapping.Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));- updateProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.ValidationFileAllowedExtensions));- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));- updateProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(nameof(ProductAttributeMappingDto.ProductAttributeValues));- updateProductAttributeMapping.Returns<ProductAttributeMappingDto>();-- ActionConfiguration deleteProductAttributeMapping = product.Action("DeleteProductAttributeMapping");- deleteProductAttributeMapping.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();- deleteProductAttributeMapping.Returns<bool>();-- #endregion-- //insert/update/delete tier price- #region Product tierprice-- ActionConfiguration createTierPrice = product.Action("CreateProductTierPrice");- createTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));- createTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));- createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));- createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));- createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));- createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));- createTierPrice.Returns<bool>();-- ActionConfiguration updateTierPrice = product.Action("UpdateProductTierPrice");- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();- updateTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));- updateTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));- updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));- updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));- updateTierPrice.Returns<bool>();-- ActionConfiguration deleteTierPrice = product.Action("DeleteProductTierPrice");- deleteTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();- deleteTierPrice.Returns<bool>();-- #endregion- }+ #endregion- protected void RegisterCatalog(ODataConventionModelBuilder builder)- {- #region Category model+ #region Picture model- builder.EntitySet<CategoryDto>("Category");+ builder.EntitySet<PictureDto>("Picture");- #endregion+ #endregion+ }- #region Brand model+ protected void RegisterProduct(ODataConventionModelBuilder builder)+ {+ builder.EntitySet<ProductDto>("Product");+ var product = builder.EntityType<ProductDto>();+ builder.ComplexType<ProductCategoryDto>();+ builder.ComplexType<ProductCollectionDto>();+ builder.ComplexType<ProductPictureDto>();+ builder.ComplexType<ProductSpecificationAttributeDto>();+ builder.ComplexType<ProductTierPriceDto>();+ builder.ComplexType<ProductWarehouseInventoryDto>();+ builder.ComplexType<ProductAttributeMappingDto>();+ builder.ComplexType<ProductAttributeValueDto>();+ builder.ComplexType<ProductAttributeCombinationDto>();+ builder.ComplexType<ProductUpdateStock>();+ builder.ComplexType<ProductCategoryDeleteDto>();+ builder.ComplexType<ProductCollectionDeleteDto>();+ builder.ComplexType<ProductPictureDeleteDto>();+ builder.ComplexType<ProductSpecificationAttributeDeleteDto>();+ builder.ComplexType<ProductTierPriceDeleteDto>();+ builder.ComplexType<ProductAttributeMappingDeleteDto>();++ //update stock for product+ var updateStock = product.Action("UpdateStock");+ updateStock.Parameter<string>("WarehouseId");+ updateStock.Parameter<int>("Stock").Required();+ updateStock.Returns<bool>();++ //insert/update/delete category++ #region Product category++ var createCategory = product.Action("CreateProductCategory");+ createCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();+ createCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));+ createCategory.Returns<bool>();++ var updateCategory = product.Action("UpdateProductCategory");+ updateCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();+ updateCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));+ updateCategory.Returns<bool>();++ var deleteCategory = product.Action("DeleteProductCategory");+ deleteCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();+ deleteCategory.Returns<bool>();++ #endregion++ //insert/update/delete collection++ #region Product collection++ var createCollection = product.Action("CreateProductCollection");+ createCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();+ createCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));+ createCollection.Returns<bool>();++ var updateCollection = product.Action("UpdateProductCollection");+ updateCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();+ updateCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));+ updateCollection.Returns<bool>();++ var deleteCollection = product.Action("DeleteProductCollection");+ deleteCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();+ deleteCollection.Returns<bool>();++ #endregion++ //insert/update/delete picture++ #region Product picture++ var createPicture = product.Action("CreateProductPicture");+ createPicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();+ createPicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();+ createPicture.Returns<bool>();++ var updatePicture = product.Action("UpdateProductPicture");+ updatePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();+ updatePicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();+ updatePicture.Returns<bool>();++ var deletePicture = product.Action("DeleteProductPicture");+ deletePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();+ deletePicture.Returns<bool>();++ #endregion++ #region Product specification++ var createSpecification = product.Action("CreateProductSpecification");+ createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id));+ createSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));+ createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));+ //createSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();+ createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));+ createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId));+ createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));+ createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));++ createSpecification.Returns<bool>();++ var updateSpecification = product.Action("UpdateProductSpecification");+ updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();+ updateSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));+ updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));+ //updateSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();+ updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));+ updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId))+ .Required();+ updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));+ updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));+ updateSpecification.Returns<bool>();++ var deleteSpecification = product.Action("DeleteProductSpecification");+ deleteSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();+ deleteSpecification.Returns<bool>();++ #endregion++ #region Product attribute mapping++ var createProductAttributeMapping = product.Action("CreateProductAttributeMapping");+ createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id));+ createProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));+ createProductAttributeMapping+ .Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();+ createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));+ createProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));+ createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));+ createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto+ .ValidationFileAllowedExtensions));+ createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));+ createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));+ createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));+ createProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(+ nameof(ProductAttributeMappingDto.ProductAttributeValues));+ createProductAttributeMapping.Returns<ProductAttributeMappingDto>();++ var updateProductAttributeMapping = product.Action("UpdateProductAttributeMapping");+ updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id)).Required();+ updateProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));+ updateProductAttributeMapping+ .Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();+ updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));+ updateProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));+ updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));+ updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto+ .ValidationFileAllowedExtensions));+ updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));+ updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));+ updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));+ updateProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(+ nameof(ProductAttributeMappingDto.ProductAttributeValues));+ updateProductAttributeMapping.Returns<ProductAttributeMappingDto>();++ var deleteProductAttributeMapping = product.Action("DeleteProductAttributeMapping");+ deleteProductAttributeMapping.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();+ deleteProductAttributeMapping.Returns<bool>();++ #endregion++ //insert/update/delete tier price++ #region Product tierprice++ var createTierPrice = product.Action("CreateProductTierPrice");+ createTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));+ createTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));+ createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));+ createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));+ createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));+ createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));+ createTierPrice.Returns<bool>();++ var updateTierPrice = product.Action("UpdateProductTierPrice");+ updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();+ updateTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));+ updateTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));+ updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));+ updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));+ updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));+ updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));+ updateTierPrice.Returns<bool>();++ var deleteTierPrice = product.Action("DeleteProductTierPrice");+ deleteTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();+ deleteTierPrice.Returns<bool>();++ #endregion+ }- builder.EntitySet<BrandDto>("Brand");+ protected void RegisterCatalog(ODataConventionModelBuilder builder)+ {+ #region Category model- #endregion+ builder.EntitySet<CategoryDto>("Category");- #region Collection model+ #endregion- builder.EntitySet<CollectionDto>("Collection");- #endregion+ #region Brand model- #region Product attribute model+ builder.EntitySet<BrandDto>("Brand");- builder.EntitySet<ProductAttributeDto>("ProductAttribute");- builder.ComplexType<PredefinedProductAttributeValueDto>();+ #endregion- #endregion+ #region Collection model- #region Product attribute model+ builder.EntitySet<CollectionDto>("Collection");- builder.EntitySet<SpecificationAttributeDto>("SpecificationAttribute");- builder.ComplexType<SpecificationAttributeOptionDto>();+ #endregion- #endregion+ #region Product attribute model- }+ builder.EntitySet<ProductAttributeDto>("ProductAttribute");+ builder.ComplexType<PredefinedProductAttributeValueDto>();- protected void RegisterCustomers(ODataConventionModelBuilder builder)- {- #region Customer-- builder.EntitySet<CustomerDto>("Customer");- var customer = builder.EntityType<CustomerDto>();- builder.ComplexType<AddressDto>();- builder.ComplexType<DeleteAddressDto>();- builder.ComplexType<PasswordDto>();-- ActionConfiguration addAddress = customer.Action("AddAddress");- addAddress.Parameter<string>(nameof(AddressDto.Id)).Required();- addAddress.Parameter<string>(nameof(AddressDto.City));- addAddress.Parameter<string>(nameof(AddressDto.Email));- addAddress.Parameter<string>(nameof(AddressDto.Company));- addAddress.Parameter<string>(nameof(AddressDto.Address1));- addAddress.Parameter<string>(nameof(AddressDto.Address2));- addAddress.Parameter<string>(nameof(AddressDto.LastName));- addAddress.Parameter<string>(nameof(AddressDto.CountryId));- addAddress.Parameter<string>(nameof(AddressDto.FaxNumber));- addAddress.Parameter<string>(nameof(AddressDto.FirstName));- addAddress.Parameter<string>(nameof(AddressDto.VatNumber));- addAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));- addAddress.Parameter<string>(nameof(AddressDto.Note));- addAddress.Parameter<int>(nameof(AddressDto.AddressType));- addAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));- addAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));- addAddress.Returns<AddressDto>();-- ActionConfiguration updateAddress = customer.Action("UpdateAddress");- updateAddress.Parameter<string>(nameof(AddressDto.Id)).Required();- updateAddress.Parameter<string>(nameof(AddressDto.City));- updateAddress.Parameter<string>(nameof(AddressDto.Email));- updateAddress.Parameter<string>(nameof(AddressDto.Company));- updateAddress.Parameter<string>(nameof(AddressDto.Address1));- updateAddress.Parameter<string>(nameof(AddressDto.Address2));- updateAddress.Parameter<string>(nameof(AddressDto.LastName));- updateAddress.Parameter<string>(nameof(AddressDto.CountryId));- updateAddress.Parameter<string>(nameof(AddressDto.FaxNumber));- updateAddress.Parameter<string>(nameof(AddressDto.FirstName));- updateAddress.Parameter<string>(nameof(AddressDto.VatNumber));- updateAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));- updateAddress.Parameter<string>(nameof(AddressDto.Note));- updateAddress.Parameter<int>(nameof(AddressDto.AddressType));- updateAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));- updateAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));- updateAddress.Returns<AddressDto>();-- ActionConfiguration deleteAddress = customer.Action("DeleteAddress");- deleteAddress.Parameter<string>(nameof(DeleteAddressDto.AddressId));- deleteAddress.Returns<bool>();-- ActionConfiguration changePassword = customer.Action("SetPassword");- changePassword.Parameter<string>(nameof(PasswordDto.Password));- changePassword.Returns<bool>();-- #endregion-- #region Customer group model-- builder.EntitySet<CustomerGroupDto>("CustomerGroup");-- #endregion-- #region Vendors-- builder.EntitySet<VendorDto>("Vendor");-- #endregion- }+ #endregion- protected void RegisterShipping(ODataConventionModelBuilder builder)- {- #region Warehouse model+ #region Product attribute model- builder.EntitySet<WarehouseDto>("Warehouse");-- #endregion+ builder.EntitySet<SpecificationAttributeDto>("SpecificationAttribute");+ builder.ComplexType<SpecificationAttributeOptionDto>();- #region Delivery date model+ #endregion+ }- builder.EntitySet<DeliveryDateDto>("DeliveryDate");-- #endregion+ protected void RegisterCustomers(ODataConventionModelBuilder builder)+ {+ #region Customer++ builder.EntitySet<CustomerDto>("Customer");+ var customer = builder.EntityType<CustomerDto>();+ builder.ComplexType<AddressDto>();+ builder.ComplexType<DeleteAddressDto>();+ builder.ComplexType<PasswordDto>();++ var addAddress = customer.Action("AddAddress");+ addAddress.Parameter<string>(nameof(AddressDto.Id)).Required();+ addAddress.Parameter<string>(nameof(AddressDto.City));+ addAddress.Parameter<string>(nameof(AddressDto.Email));+ addAddress.Parameter<string>(nameof(AddressDto.Company));+ addAddress.Parameter<string>(nameof(AddressDto.Address1));+ addAddress.Parameter<string>(nameof(AddressDto.Address2));+ addAddress.Parameter<string>(nameof(AddressDto.LastName));+ addAddress.Parameter<string>(nameof(AddressDto.CountryId));+ addAddress.Parameter<string>(nameof(AddressDto.FaxNumber));+ addAddress.Parameter<string>(nameof(AddressDto.FirstName));+ addAddress.Parameter<string>(nameof(AddressDto.VatNumber));+ addAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));+ addAddress.Parameter<string>(nameof(AddressDto.Note));+ addAddress.Parameter<int>(nameof(AddressDto.AddressType));+ addAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));+ addAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));+ addAddress.Returns<AddressDto>();++ var updateAddress = customer.Action("UpdateAddress");+ updateAddress.Parameter<string>(nameof(AddressDto.Id)).Required();+ updateAddress.Parameter<string>(nameof(AddressDto.City));+ updateAddress.Parameter<string>(nameof(AddressDto.Email));+ updateAddress.Parameter<string>(nameof(AddressDto.Company));+ updateAddress.Parameter<string>(nameof(AddressDto.Address1));+ updateAddress.Parameter<string>(nameof(AddressDto.Address2));+ updateAddress.Parameter<string>(nameof(AddressDto.LastName));+ updateAddress.Parameter<string>(nameof(AddressDto.CountryId));+ updateAddress.Parameter<string>(nameof(AddressDto.FaxNumber));+ updateAddress.Parameter<string>(nameof(AddressDto.FirstName));+ updateAddress.Parameter<string>(nameof(AddressDto.VatNumber));+ updateAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));+ updateAddress.Parameter<string>(nameof(AddressDto.Note));+ updateAddress.Parameter<int>(nameof(AddressDto.AddressType));+ updateAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));+ updateAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));+ updateAddress.Returns<AddressDto>();++ var deleteAddress = customer.Action("DeleteAddress");+ deleteAddress.Parameter<string>(nameof(DeleteAddressDto.AddressId));+ deleteAddress.Returns<bool>();++ var changePassword = customer.Action("SetPassword");+ changePassword.Parameter<string>(nameof(PasswordDto.Password));+ changePassword.Returns<bool>();++ #endregion++ #region Customer group model++ builder.EntitySet<CustomerGroupDto>("CustomerGroup");++ #endregion++ #region Vendors++ builder.EntitySet<VendorDto>("Vendor");++ #endregion+ }- #region Pickup point model+ protected void RegisterShipping(ODataConventionModelBuilder builder)+ {+ #region Warehouse model- builder.EntitySet<PickupPointDto>("PickupPoint");+ builder.EntitySet<WarehouseDto>("Warehouse");- #endregion+ #endregion- #region Shipping method model+ #region Delivery date model- builder.EntitySet<ShippingMethodDto>("ShippingMethod");+ builder.EntitySet<DeliveryDateDto>("DeliveryDate");- #endregion- }+ #endregion- public void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)- {- if (apiConfig.SystemModel)- {- RegisterCommon(builder);- RegisterProduct(builder);- RegisterCatalog(builder);- RegisterCustomers(builder);- RegisterShipping(builder);- }- }+ #region Pickup point model++ builder.EntitySet<PickupPointDto>("PickupPoint");++ #endregion++ #region Shipping method model++ builder.EntitySet<ShippingMethodDto>("ShippingMethod");- public int Order => 0;+ #endregion}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs b/src/API/Grand.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.csindex 0ddff2334..4f9c7d117 100644--- a/src/API/Grand.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs+++ b/src/API/Grand.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs@@ -1,20 +1,19 @@using Grand.Infrastructure.Configuration;using Microsoft.OData.ModelBuilder;-namespace Grand.Api.Infrastructure.DependencyManagement+namespace Grand.Api.Infrastructure.DependencyManagement;++public interface IDependencyEdmModel{- public interface IDependencyEdmModel- {- /// <summary>- /// Register edmmodel- /// </summary>- /// <param name="builder">OData Convention Model Builder</param>- /// <param name="apiConfig">ApiConfig</param>- void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig);+ /// <summary>+ /// Order of this dependency implementation+ /// </summary>+ int Order { get; }- /// <summary>- /// Order of this dependency implementation- /// </summary>- int Order { get; }- }-}+ /// <summary>+ /// Register edmmodel+ /// </summary>+ /// <param name="builder">OData Convention Model Builder</param>+ /// <param name="apiConfig">ApiConfig</param>+ void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig);+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Extensions/JwtSecurityKey.cs b/src/API/Grand.Api/Infrastructure/Extensions/JwtSecurityKey.csindex 7eb80cf49..bde184d4f 100644--- a/src/API/Grand.Api/Infrastructure/Extensions/JwtSecurityKey.cs+++ b/src/API/Grand.Api/Infrastructure/Extensions/JwtSecurityKey.cs@@ -1,12 +1,11 @@using Microsoft.IdentityModel.Tokens;-namespace Grand.Api.Infrastructure.Extensions+namespace Grand.Api.Infrastructure.Extensions;++public static class JwtSecurityKey{- public static class JwtSecurityKey+ public static SymmetricSecurityKey Create(string secret){- public static SymmetricSecurityKey Create(string secret)- {- return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));- }+ return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Filters/EnumSchemaFilter.cs b/src/API/Grand.Api/Infrastructure/Filters/EnumSchemaFilter.csindex 855d3c2ac..27c7d0d77 100644--- a/src/API/Grand.Api/Infrastructure/Filters/EnumSchemaFilter.cs+++ b/src/API/Grand.Api/Infrastructure/Filters/EnumSchemaFilter.cs@@ -2,22 +2,20 @@using Microsoft.OpenApi.Models;using Swashbuckle.AspNetCore.SwaggerGen;-namespace Grand.Api.Infrastructure.Filters+namespace Grand.Api.Infrastructure.Filters;++public class EnumSchemaFilter : ISchemaFilter{- public class EnumSchemaFilter : ISchemaFilter+ public void Apply(OpenApiSchema schema, SchemaFilterContext context){- public void Apply(OpenApiSchema schema, SchemaFilterContext context)+ if (!context.Type.IsEnum) return;++ var enumValues = schema.Enum.ToArray();+ foreach (var item in enumValues){- if (!context.Type.IsEnum) return;-- var enumValues = schema.Enum.ToArray();- foreach (var item in enumValues)- {- var value = (OpenApiPrimitive<int>)item;- var name = Enum.GetName(context.Type, value.Value);- schema.Description += $"{value.Value} - {name}; ";- }+ var value = (OpenApiPrimitive<int>)item;+ var name = Enum.GetName(context.Type, value.Value);+ schema.Description += $"{value.Value} - {name}; ";}}-}-+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Filters/IgnoreFieldFilter.cs b/src/API/Grand.Api/Infrastructure/Filters/IgnoreFieldFilter.csindex dfc88e499..fcbe8bdd8 100644--- a/src/API/Grand.Api/Infrastructure/Filters/IgnoreFieldFilter.cs+++ b/src/API/Grand.Api/Infrastructure/Filters/IgnoreFieldFilter.cs@@ -10,10 +10,7 @@ public class IgnoreFieldFilter : ISchemaFilterpublic void Apply(OpenApiSchema schema, SchemaFilterContext context){var type = context.Type;- if (!schema.Properties.Any() || type == null)- {- return;- }+ if (!schema.Properties.Any() || type == null) return;var excludedPropertyNames = type.GetProperties()@@ -21,10 +18,7 @@ public class IgnoreFieldFilter : ISchemaFiltert => t.GetCustomAttribute<IgnoreApiAttribute>() != null).Select(d => d.Name).ToList();- if (!excludedPropertyNames.Any())- {- return;- }+ if (!excludedPropertyNames.Any()) return;var excludedSchemaPropertyKey = schema.Properties.Where(@@ -33,10 +27,6 @@ public class IgnoreFieldFilter : ISchemaFilter)).Select(ap => ap.Key);- foreach (var propertyToExclude in excludedSchemaPropertyKey)- {- schema.Properties.Remove(propertyToExclude);- }-+ foreach (var propertyToExclude in excludedSchemaPropertyKey) schema.Properties.Remove(propertyToExclude);}}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/AddressProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/AddressProfile.csindex 64b1285b5..a2a3d92a6 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/AddressProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/AddressProfile.cs@@ -3,17 +3,16 @@ using Grand.Api.DTOs.Customers;using Grand.Domain.Common;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class AddressProfile : Profile, IAutoMapperProfile{- public class AddressProfile : Profile, IAutoMapperProfile+ public AddressProfile(){- public AddressProfile()- {- CreateMap<AddressDto, Address>()- .ForMember(dest => dest.Attributes, mo => mo.Ignore());- CreateMap<Address, AddressDto>();- }-- public int Order => 1;+ CreateMap<AddressDto, Address>()+ .ForMember(dest => dest.Attributes, mo => mo.Ignore());+ CreateMap<Address, AddressDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/BrandProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/BrandProfile.csindex 09df385ab..e6d783133 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/BrandProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/BrandProfile.cs@@ -3,28 +3,25 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class BrandProfile : Profile, IAutoMapperProfile{- public class BrandProfile : Profile, IAutoMapperProfile+ public BrandProfile(){- public BrandProfile()- {-- CreateMap<BrandDto, Brand>()- .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())- .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())- .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())- .ForMember(dest => dest.Stores, mo => mo.Ignore())- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.Locales, mo => mo.Ignore())- .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Brand, BrandDto>();+ CreateMap<BrandDto, Brand>()+ .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())+ .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())+ .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())+ .ForMember(dest => dest.Stores, mo => mo.Ignore())+ .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Locales, mo => mo.Ignore())+ .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- }-- public int Order => 1;+ CreateMap<Brand, BrandDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CategoryProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CategoryProfile.csindex d7db097ae..b809585c0 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CategoryProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CategoryProfile.cs@@ -3,28 +3,25 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class CategoryProfile : Profile, IAutoMapperProfile{- public class CategoryProfile : Profile, IAutoMapperProfile+ public CategoryProfile(){+ CreateMap<CategoryDto, Category>()+ .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())+ .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())+ .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())+ .ForMember(dest => dest.Stores, mo => mo.Ignore())+ .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Locales, mo => mo.Ignore())+ .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- public CategoryProfile()- {- CreateMap<CategoryDto, Category>()- .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())- .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())- .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())- .ForMember(dest => dest.Stores, mo => mo.Ignore())- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.Locales, mo => mo.Ignore())- .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Category, CategoryDto>();-- }-- public int Order => 1;+ CreateMap<Category, CategoryDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CollectionProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CollectionProfile.csindex 752891adc..6ccf14d56 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CollectionProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CollectionProfile.cs@@ -3,28 +3,25 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class CollectionProfile : Profile, IAutoMapperProfile{- public class CollectionProfile : Profile, IAutoMapperProfile+ public CollectionProfile(){- public CollectionProfile()- {-- CreateMap<CollectionDto, Collection>()- .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())- .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())- .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())- .ForMember(dest => dest.Stores, mo => mo.Ignore())- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.Locales, mo => mo.Ignore())- .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Collection, CollectionDto>();+ CreateMap<CollectionDto, Collection>()+ .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())+ .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())+ .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())+ .ForMember(dest => dest.Stores, mo => mo.Ignore())+ .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Locales, mo => mo.Ignore())+ .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- }-- public int Order => 1;+ CreateMap<Collection, CollectionDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerGroupProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerGroupProfile.csindex 5fe37921d..912b987a8 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerGroupProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerGroupProfile.cs@@ -3,20 +3,17 @@ using Grand.Api.DTOs.Customers;using Grand.Domain.Customers;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class CustomerGroupProfile : Profile, IAutoMapperProfile{- public class CustomerGroupProfile : Profile, IAutoMapperProfile+ public CustomerGroupProfile(){- public CustomerGroupProfile()- {-- CreateMap<CustomerGroupDto, CustomerGroup>()- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<CustomerGroup, CustomerGroupDto>();+ CreateMap<CustomerGroupDto, CustomerGroup>()+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- }-- public int Order => 1;+ CreateMap<CustomerGroup, CustomerGroupDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerProfile.csindex 50c6d5573..9fd91a6b4 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/CustomerProfile.cs@@ -4,57 +4,74 @@ using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class CustomerProfile : Profile, IAutoMapperProfile{- public class CustomerProfile : Profile, IAutoMapperProfile+ public CustomerProfile(){- public CustomerProfile()- {- CreateMap<CustomerDto, Customer>()- .ForMember(dest => dest.Addresses, mo => mo.Ignore())- .ForMember(dest => dest.CannotLoginUntilDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.BillingAddress, mo => mo.Ignore())- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.Groups, mo => mo.Ignore())- .ForMember(dest => dest.CustomerTags, mo => mo.Ignore())- .ForMember(dest => dest.FailedLoginAttempts, mo => mo.Ignore())- .ForMember(dest => dest.HasContributions, mo => mo.Ignore())- .ForMember(dest => dest.IsSystemAccount, mo => mo.Ignore())- .ForMember(dest => dest.LastActivityDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.LastIpAddress, mo => mo.Ignore())- .ForMember(dest => dest.LastLoginDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.LastPurchaseDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.LastUpdateCartDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.LastUpdateWishListDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.Password, mo => mo.Ignore())- .ForMember(dest => dest.PasswordChangeDateUtc, mo => mo.Ignore())- .ForMember(dest => dest.PasswordFormatId, mo => mo.Ignore())- .ForMember(dest => dest.PasswordSalt, mo => mo.Ignore())- .ForMember(dest => dest.ShippingAddress, mo => mo.Ignore())- .ForMember(dest => dest.ShoppingCartItems, mo => mo.Ignore())- .ForMember(dest => dest.SystemName, mo => mo.Ignore())- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Customer, CustomerDto>()- .ForMember(dest => dest.FirstName, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName, "")))- .ForMember(dest => dest.LastName, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName, "")))- .ForMember(dest => dest.City, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.City, "")))- .ForMember(dest => dest.Company, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company, "")))- .ForMember(dest => dest.DateOfBirth, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<DateTime?>(SystemCustomerFieldNames.DateOfBirth, "")))- .ForMember(dest => dest.Fax, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Fax, "")))- .ForMember(dest => dest.Gender, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Gender, "")))- .ForMember(dest => dest.Phone, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Phone, "")))- .ForMember(dest => dest.StateProvinceId, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StateProvinceId, "")))- .ForMember(dest => dest.StreetAddress, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress, "")))- .ForMember(dest => dest.StreetAddress2, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress2, "")))- .ForMember(dest => dest.VatNumber, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber, "")))- .ForMember(dest => dest.VatNumberStatusId, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumberStatusId, "")))- .ForMember(dest => dest.ZipPostalCode, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ZipPostalCode, "")))- .ForMember(dest => dest.CountryId, mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId, "")))- .ForMember(dest => dest.Groups, mo => mo.MapFrom(src => src.Groups.Select(x => x)));+ CreateMap<CustomerDto, Customer>()+ .ForMember(dest => dest.Addresses, mo => mo.Ignore())+ .ForMember(dest => dest.CannotLoginUntilDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.BillingAddress, mo => mo.Ignore())+ .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Groups, mo => mo.Ignore())+ .ForMember(dest => dest.CustomerTags, mo => mo.Ignore())+ .ForMember(dest => dest.FailedLoginAttempts, mo => mo.Ignore())+ .ForMember(dest => dest.HasContributions, mo => mo.Ignore())+ .ForMember(dest => dest.IsSystemAccount, mo => mo.Ignore())+ .ForMember(dest => dest.LastActivityDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.LastIpAddress, mo => mo.Ignore())+ .ForMember(dest => dest.LastLoginDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.LastPurchaseDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.LastUpdateCartDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.LastUpdateWishListDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Password, mo => mo.Ignore())+ .ForMember(dest => dest.PasswordChangeDateUtc, mo => mo.Ignore())+ .ForMember(dest => dest.PasswordFormatId, mo => mo.Ignore())+ .ForMember(dest => dest.PasswordSalt, mo => mo.Ignore())+ .ForMember(dest => dest.ShippingAddress, mo => mo.Ignore())+ .ForMember(dest => dest.ShoppingCartItems, mo => mo.Ignore())+ .ForMember(dest => dest.SystemName, mo => mo.Ignore())+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- }-- public int Order => 1;+ CreateMap<Customer, CustomerDto>()+ .ForMember(dest => dest.FirstName,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName, "")))+ .ForMember(dest => dest.LastName,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName, "")))+ .ForMember(dest => dest.City,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.City, "")))+ .ForMember(dest => dest.Company,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company, "")))+ .ForMember(dest => dest.DateOfBirth,+ mo => mo.MapFrom(src =>+ src.GetUserFieldFromEntity<DateTime?>(SystemCustomerFieldNames.DateOfBirth, "")))+ .ForMember(dest => dest.Fax,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Fax, "")))+ .ForMember(dest => dest.Gender,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Gender, "")))+ .ForMember(dest => dest.Phone,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Phone, "")))+ .ForMember(dest => dest.StateProvinceId,+ mo => mo.MapFrom(+ src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StateProvinceId, "")))+ .ForMember(dest => dest.StreetAddress,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress, "")))+ .ForMember(dest => dest.StreetAddress2,+ mo => mo.MapFrom(src =>+ src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress2, "")))+ .ForMember(dest => dest.VatNumber,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber, "")))+ .ForMember(dest => dest.VatNumberStatusId,+ mo => mo.MapFrom(src =>+ src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumberStatusId, "")))+ .ForMember(dest => dest.ZipPostalCode,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ZipPostalCode, "")))+ .ForMember(dest => dest.CountryId,+ mo => mo.MapFrom(src => src.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId, "")))+ .ForMember(dest => dest.Groups, mo => mo.MapFrom(src => src.Groups.Select(x => x)));}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/PictureProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/PictureProfile.csindex db14a6ce1..cda1aa0e5 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/PictureProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/PictureProfile.cs@@ -3,20 +3,18 @@ using Grand.Api.DTOs.Common;using Grand.Domain.Media;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class PictureProfile : Profile, IAutoMapperProfile{- public class PictureProfile : Profile, IAutoMapperProfile+ public PictureProfile(){- public PictureProfile()- {- CreateMap<PictureDto, Picture>()- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Picture, PictureDto>()- .ForMember(dest => dest.PictureBinary, mo => mo.Ignore());+ CreateMap<PictureDto, Picture>()+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- }-- public int Order => 1;+ CreateMap<Picture, PictureDto>()+ .ForMember(dest => dest.PictureBinary, mo => mo.Ignore());}++ public int Order => 1;}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeMappingProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeMappingProfile.csindex dab84d08e..4b8744b65 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeMappingProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeMappingProfile.cs@@ -3,19 +3,18 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class ProductAttributeMappingProfile : Profile, IAutoMapperProfile{- public class ProductAttributeMappingProfile : Profile, IAutoMapperProfile+ public ProductAttributeMappingProfile(){- public ProductAttributeMappingProfile()- {- CreateMap<ProductAttributeMappingDto, ProductAttributeMapping>();- CreateMap<ProductAttributeMapping, ProductAttributeMappingDto>();-- CreateMap<ProductAttributeValueDto, ProductAttributeValue>();- CreateMap<ProductAttributeValue, ProductAttributeValueDto>();- }+ CreateMap<ProductAttributeMappingDto, ProductAttributeMapping>();+ CreateMap<ProductAttributeMapping, ProductAttributeMappingDto>();- public int Order => 1;+ CreateMap<ProductAttributeValueDto, ProductAttributeValue>();+ CreateMap<ProductAttributeValue, ProductAttributeValueDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeProfile.csindex 461f9fdbb..8f98cbea4 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductAttributeProfile.cs@@ -3,25 +3,22 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class ProductAttributeProfile : Profile, IAutoMapperProfile{- public class ProductAttributeProfile : Profile, IAutoMapperProfile+ public ProductAttributeProfile(){- public ProductAttributeProfile()- {-- CreateMap<ProductAttributeDto, ProductAttribute>()- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<ProductAttribute, ProductAttributeDto>();+ CreateMap<ProductAttributeDto, ProductAttribute>()+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- CreateMap<PredefinedProductAttributeValue, PredefinedProductAttributeValueDto>();+ CreateMap<ProductAttribute, ProductAttributeDto>();- CreateMap<PredefinedProductAttributeValueDto, PredefinedProductAttributeValue>()- .ForMember(dest => dest.Locales, mo => mo.Ignore());+ CreateMap<PredefinedProductAttributeValue, PredefinedProductAttributeValueDto>();- }-- public int Order => 1;+ CreateMap<PredefinedProductAttributeValueDto, PredefinedProductAttributeValue>()+ .ForMember(dest => dest.Locales, mo => mo.Ignore());}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductProfile.csindex f575b572e..55c1ea5ad 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/ProductProfile.cs@@ -3,49 +3,47 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class ProductProfile : Profile, IAutoMapperProfile{- public class ProductProfile : Profile, IAutoMapperProfile+ public ProductProfile(){+ CreateMap<ProductDto, Product>()+ .ForMember(dest => dest.ProductCategories, mo => mo.Ignore())+ .ForMember(dest => dest.ProductCollections, mo => mo.Ignore())+ .ForMember(dest => dest.ProductPictures, mo => mo.Ignore())+ .ForMember(dest => dest.ProductSpecificationAttributes, mo => mo.Ignore())+ .ForMember(dest => dest.ProductAttributeMappings, mo => mo.Ignore())+ .ForMember(dest => dest.ProductAttributeCombinations, mo => mo.Ignore())+ .ForMember(dest => dest.TierPrices, mo => mo.Ignore())+ .ForMember(dest => dest.ProductWarehouseInventory, mo => mo.Ignore())+ .ForMember(dest => dest.CrossSellProduct, mo => mo.Ignore())+ .ForMember(dest => dest.RecommendedProduct, mo => mo.Ignore())+ .ForMember(dest => dest.RelatedProducts, mo => mo.Ignore())+ .ForMember(dest => dest.BundleProducts, mo => mo.Ignore())+ .ForMember(dest => dest.ProductTags, mo => mo.Ignore())+ .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())+ .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())+ .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())+ .ForMember(dest => dest.Stores, mo => mo.Ignore())+ .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())+ .ForMember(dest => dest.Locales, mo => mo.Ignore())+ .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- public ProductProfile()- {- CreateMap<ProductDto, Product>()- .ForMember(dest => dest.ProductCategories, mo => mo.Ignore())- .ForMember(dest => dest.ProductCollections, mo => mo.Ignore())- .ForMember(dest => dest.ProductPictures, mo => mo.Ignore())- .ForMember(dest => dest.ProductSpecificationAttributes, mo => mo.Ignore())- .ForMember(dest => dest.ProductAttributeMappings, mo => mo.Ignore())- .ForMember(dest => dest.ProductAttributeCombinations, mo => mo.Ignore())- .ForMember(dest => dest.TierPrices, mo => mo.Ignore())- .ForMember(dest => dest.ProductWarehouseInventory, mo => mo.Ignore())- .ForMember(dest => dest.CrossSellProduct, mo => mo.Ignore())- .ForMember(dest => dest.RecommendedProduct, mo => mo.Ignore())- .ForMember(dest => dest.RelatedProducts, mo => mo.Ignore())- .ForMember(dest => dest.BundleProducts, mo => mo.Ignore())- .ForMember(dest => dest.ProductTags, mo => mo.Ignore())- .ForMember(dest => dest.LimitedToGroups, mo => mo.Ignore())- .ForMember(dest => dest.CustomerGroups, mo => mo.Ignore())- .ForMember(dest => dest.LimitedToStores, mo => mo.Ignore())- .ForMember(dest => dest.Stores, mo => mo.Ignore())- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.UpdatedOnUtc, mo => mo.Ignore())- .ForMember(dest => dest.Locales, mo => mo.Ignore())- .ForMember(dest => dest.AppliedDiscounts, mo => mo.Ignore())- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<Product, ProductDto>();+ CreateMap<Product, ProductDto>();- CreateMap<ProductCategory, ProductCategoryDto>();- CreateMap<ProductCollection, ProductCollectionDto>();- CreateMap<ProductPicture, ProductPictureDto>();- CreateMap<ProductSpecificationAttribute, ProductSpecificationAttributeDto>();- CreateMap<TierPrice, ProductTierPriceDto>();- CreateMap<ProductWarehouseInventory, ProductWarehouseInventoryDto>();- CreateMap<ProductAttributeMapping, ProductAttributeMappingDto>();- CreateMap<ProductAttributeCombination, ProductAttributeCombinationDto>();- }-- public int Order => 1;+ CreateMap<ProductCategory, ProductCategoryDto>();+ CreateMap<ProductCollection, ProductCollectionDto>();+ CreateMap<ProductPicture, ProductPictureDto>();+ CreateMap<ProductSpecificationAttribute, ProductSpecificationAttributeDto>();+ CreateMap<TierPrice, ProductTierPriceDto>();+ CreateMap<ProductWarehouseInventory, ProductWarehouseInventoryDto>();+ CreateMap<ProductAttributeMapping, ProductAttributeMappingDto>();+ CreateMap<ProductAttributeCombination, ProductAttributeCombinationDto>();}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/SpecificationAttributeProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/SpecificationAttributeProfile.csindex 6b0a8efe7..a797dea9c 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/SpecificationAttributeProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/SpecificationAttributeProfile.cs@@ -3,25 +3,22 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class SpecificationAttributeProfile : Profile, IAutoMapperProfile{- public class SpecificationAttributeProfile : Profile, IAutoMapperProfile+ public SpecificationAttributeProfile(){- public SpecificationAttributeProfile()- {-- CreateMap<SpecificationAttributeDto, SpecificationAttribute>()- .ForMember(dest => dest.UserFields, mo => mo.Ignore());-- CreateMap<SpecificationAttribute, SpecificationAttributeDto>();+ CreateMap<SpecificationAttributeDto, SpecificationAttribute>()+ .ForMember(dest => dest.UserFields, mo => mo.Ignore());- CreateMap<SpecificationAttributeOption, SpecificationAttributeOptionDto>();+ CreateMap<SpecificationAttribute, SpecificationAttributeDto>();- CreateMap<SpecificationAttributeOptionDto, SpecificationAttributeOption>()- .ForMember(dest => dest.Locales, mo => mo.Ignore());+ CreateMap<SpecificationAttributeOption, SpecificationAttributeOptionDto>();- }-- public int Order => 1;+ CreateMap<SpecificationAttributeOptionDto, SpecificationAttributeOption>()+ .ForMember(dest => dest.Locales, mo => mo.Ignore());}-}++ public int Order => 1;+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/TierPriceProfile.cs b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/TierPriceProfile.csindex fed5c4925..21bcd0e2a 100644--- a/src/API/Grand.Api/Infrastructure/Mapper/Profiles/TierPriceProfile.cs+++ b/src/API/Grand.Api/Infrastructure/Mapper/Profiles/TierPriceProfile.cs@@ -3,17 +3,16 @@ using Grand.Api.DTOs.Catalog;using Grand.Domain.Catalog;using Grand.Infrastructure.Mapper;-namespace Grand.Api.Infrastructure.Mapper.Profiles+namespace Grand.Api.Infrastructure.Mapper.Profiles;++public class TierPriceProfile : Profile, IAutoMapperProfile{- public class TierPriceProfile : Profile, IAutoMapperProfile+ public TierPriceProfile(){- public TierPriceProfile()- {- CreateMap<ProductTierPriceDto, TierPrice>();-- CreateMap<TierPrice, ProductTierPriceDto>();- }+ CreateMap<ProductTierPriceDto, TierPrice>();- public int Order => 1;+ CreateMap<TierPrice, ProductTierPriceDto>();}++ public int Order => 1;}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/ModelValidationAttribute.cs b/src/API/Grand.Api/Infrastructure/ModelValidationAttribute.csindex 6c92e4f77..c23e09da3 100644--- a/src/API/Grand.Api/Infrastructure/ModelValidationAttribute.cs+++ b/src/API/Grand.Api/Infrastructure/ModelValidationAttribute.cs@@ -1,16 +1,12 @@using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++public class ModelValidationAttribute : ActionFilterAttribute{- public class ModelValidationAttribute : ActionFilterAttribute+ public override void OnActionExecuting(ActionExecutingContext context){- public override void OnActionExecuting(ActionExecutingContext context)- {- if (!context.ModelState.IsValid)- {- context.Result = new BadRequestObjectResult(context.ModelState);- }- }+ if (!context.ModelState.IsValid) context.Result = new BadRequestObjectResult(context.ModelState);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/ODataStartup.cs b/src/API/Grand.Api/Infrastructure/ODataStartup.csindex 9b9c46169..bf0c30d74 100644--- a/src/API/Grand.Api/Infrastructure/ODataStartup.cs+++ b/src/API/Grand.Api/Infrastructure/ODataStartup.cs@@ -6,6 +6,14 @@ using Grand.Api.DTOs.Shipping;using Grand.Api.Infrastructure.DependencyManagement;using Grand.Api.Queries.Handlers.Common;using Grand.Api.Queries.Models.Common;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Localization;+using Grand.Domain.Media;+using Grand.Domain.Shipping;+using Grand.Domain.Stores;+using Grand.Domain.Vendors;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.TypeSearch;@@ -21,150 +29,144 @@ using Microsoft.Extensions.Options;using Microsoft.OData.Edm;using Microsoft.OData.ModelBuilder;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++public class ODataStartup : IStartupApplication{- public class ODataStartup : IStartupApplication+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment){- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- var apiConfig = application.ApplicationServices.GetService<BackendAPIConfig>();- if (apiConfig.Enabled)- {- application.UseCors(Configurations.CorsPolicyName);- }- }+ var apiConfig = application.ApplicationServices.GetService<BackendAPIConfig>();+ if (apiConfig.Enabled) application.UseCors(Configurations.CorsPolicyName);+ }- public void ConfigureServices(IServiceCollection services,- IConfiguration configuration)+ public void ConfigureServices(IServiceCollection services,+ IConfiguration configuration)+ {+ var apiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();+ if (apiConfig.Enabled){- var apiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();- if (apiConfig.Enabled)+ //register RequestHandler+ RegisterRequestHandler(services);++ //cors+ services.AddCors(options =>{- //register RequestHandler- RegisterRequestHandler(services);-- //cors- services.AddCors(options =>- {- options.AddPolicy(Configurations.CorsPolicyName,- builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());- });- //Add OData- services.AddControllers(options =>- {- options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());- }).AddOData(opt =>- {- opt.EnableQueryFeatures(Configurations.MaxLimit);- opt.AddRouteComponents(Configurations.ODataRoutePrefix, GetEdmModel(apiConfig));- opt.Select().Filter().OrderBy().Expand().Count().SetMaxTop(Configurations.MaxLimit);- });-- services.AddScoped<ModelValidationAttribute>();-- }- }- private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()- {- var builder = new ServiceCollection()- .AddLogging()- .AddMvc()- .AddNewtonsoftJson()- .Services.BuildServiceProvider();-- return builder- .GetRequiredService<IOptions<MvcOptions>>()- .Value- .InputFormatters- .OfType<NewtonsoftJsonPatchInputFormatter>()- .First();+ options.AddPolicy(Configurations.CorsPolicyName,+ builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());+ });+ //Add OData+ services.AddControllers(options =>+ {+ options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());+ }).AddOData(opt =>+ {+ opt.EnableQueryFeatures(Configurations.MaxLimit);+ opt.AddRouteComponents(Configurations.ODataRoutePrefix, GetEdmModel(apiConfig));+ opt.Select().Filter().OrderBy().Expand().Count().SetMaxTop(Configurations.MaxLimit);+ });++ services.AddScoped<ModelValidationAttribute>();}- public int Priority => 505;- public bool BeforeConfigure => false;+ }+ public int Priority => 505;+ public bool BeforeConfigure => false;- private IEdmModel GetEdmModel(BackendAPIConfig apiConfig)- {- var builder = new ODataConventionModelBuilder {- Namespace = Configurations.ODataModelBuilderNamespace- };- RegisterDependencies(builder, apiConfig);- return builder.GetEdmModel();- }+ private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()+ {+ var builder = new ServiceCollection()+ .AddLogging()+ .AddMvc()+ .AddNewtonsoftJson()+ .Services.BuildServiceProvider();++ return builder+ .GetRequiredService<IOptions<MvcOptions>>()+ .Value+ .InputFormatters+ .OfType<NewtonsoftJsonPatchInputFormatter>()+ .First();+ }- private void RegisterDependencies(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)- {- var typeFinder = new TypeSearcher();- //find dependency provided by other assemblies- var dependencyInject = typeFinder.ClassesOfType<IDependencyEdmModel>();+ private IEdmModel GetEdmModel(BackendAPIConfig apiConfig)+ {+ var builder = new ODataConventionModelBuilder {+ Namespace = Configurations.ODataModelBuilderNamespace+ };+ RegisterDependencies(builder, apiConfig);+ return builder.GetEdmModel();+ }- //create and sort instances of dependency inject- var instances = dependencyInject- .Select(di => (IDependencyEdmModel)Activator.CreateInstance(di))- .OrderBy(di => di!.Order);+ private void RegisterDependencies(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)+ {+ var typeFinder = new TypeSearcher();- //register all provided dependencies- foreach (var dependencyRegistrar in instances)- dependencyRegistrar!.Register(builder, apiConfig);+ //find dependency provided by other assemblies+ var dependencyInject = typeFinder.ClassesOfType<IDependencyEdmModel>();- }+ //create and sort instances of dependency inject+ var instances = dependencyInject+ .Select(di => (IDependencyEdmModel)Activator.CreateInstance(di))+ .OrderBy(di => di!.Order);- private void RegisterRequestHandler(IServiceCollection services)- {- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CountryDto, Domain.Directory.Country>,- IQueryable<CountryDto>>), typeof(GetGenericQueryHandler<CountryDto, Domain.Directory.Country>));+ //register all provided dependencies+ foreach (var dependencyRegistrar in instances)+ dependencyRegistrar!.Register(builder, apiConfig);+ }- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CurrencyDto, Domain.Directory.Currency>,- IQueryable<CurrencyDto>>), typeof(GetGenericQueryHandler<CurrencyDto, Domain.Directory.Currency>));+ private void RegisterRequestHandler(IServiceCollection services)+ {+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CountryDto, Country>,+ IQueryable<CountryDto>>), typeof(GetGenericQueryHandler<CountryDto, Country>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<BrandDto, Domain.Catalog.Brand>,- IQueryable<BrandDto>>), typeof(GetGenericQueryHandler<BrandDto, Domain.Catalog.Brand>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CurrencyDto, Currency>,+ IQueryable<CurrencyDto>>), typeof(GetGenericQueryHandler<CurrencyDto, Currency>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CategoryDto, Domain.Catalog.Category>,- IQueryable<CategoryDto>>), typeof(GetGenericQueryHandler<CategoryDto, Domain.Catalog.Category>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<BrandDto, Brand>,+ IQueryable<BrandDto>>), typeof(GetGenericQueryHandler<BrandDto, Brand>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CollectionDto, Domain.Catalog.Collection>,- IQueryable<CollectionDto>>), typeof(GetGenericQueryHandler<CollectionDto, Domain.Catalog.Collection>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CategoryDto, Category>,+ IQueryable<CategoryDto>>), typeof(GetGenericQueryHandler<CategoryDto, Category>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ProductAttributeDto, Domain.Catalog.ProductAttribute>,- IQueryable<ProductAttributeDto>>), typeof(GetGenericQueryHandler<ProductAttributeDto, Domain.Catalog.ProductAttribute>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CollectionDto, Collection>,+ IQueryable<CollectionDto>>), typeof(GetGenericQueryHandler<CollectionDto, Collection>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ProductDto, Domain.Catalog.Product>,- IQueryable<ProductDto>>), typeof(GetGenericQueryHandler<ProductDto, Domain.Catalog.Product>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ProductAttributeDto, ProductAttribute>,+ IQueryable<ProductAttributeDto>>), typeof(GetGenericQueryHandler<ProductAttributeDto, ProductAttribute>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>,- IQueryable<SpecificationAttributeDto>>), typeof(GetGenericQueryHandler<SpecificationAttributeDto, Domain.Catalog.SpecificationAttribute>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ProductDto, Product>,+ IQueryable<ProductDto>>), typeof(GetGenericQueryHandler<ProductDto, Product>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<WarehouseDto, Domain.Shipping.Warehouse>,- IQueryable<WarehouseDto>>), typeof(GetGenericQueryHandler<WarehouseDto, Domain.Shipping.Warehouse>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>,+ IQueryable<SpecificationAttributeDto>>),+ typeof(GetGenericQueryHandler<SpecificationAttributeDto, SpecificationAttribute>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ShippingMethodDto, Domain.Shipping.ShippingMethod>,- IQueryable<ShippingMethodDto>>), typeof(GetGenericQueryHandler<ShippingMethodDto, Domain.Shipping.ShippingMethod>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<WarehouseDto, Warehouse>,+ IQueryable<WarehouseDto>>), typeof(GetGenericQueryHandler<WarehouseDto, Warehouse>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<PickupPointDto, Domain.Shipping.PickupPoint>,- IQueryable<PickupPointDto>>), typeof(GetGenericQueryHandler<PickupPointDto, Domain.Shipping.PickupPoint>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<ShippingMethodDto, ShippingMethod>,+ IQueryable<ShippingMethodDto>>), typeof(GetGenericQueryHandler<ShippingMethodDto, ShippingMethod>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<DeliveryDateDto, Domain.Shipping.DeliveryDate>,- IQueryable<DeliveryDateDto>>), typeof(GetGenericQueryHandler<DeliveryDateDto, Domain.Shipping.DeliveryDate>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<PickupPointDto, PickupPoint>,+ IQueryable<PickupPointDto>>), typeof(GetGenericQueryHandler<PickupPointDto, PickupPoint>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<VendorDto, Domain.Vendors.Vendor>,- IQueryable<VendorDto>>), typeof(GetGenericQueryHandler<VendorDto, Domain.Vendors.Vendor>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<DeliveryDateDto, DeliveryDate>,+ IQueryable<DeliveryDateDto>>), typeof(GetGenericQueryHandler<DeliveryDateDto, DeliveryDate>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CustomerGroupDto, Domain.Customers.CustomerGroup>,- IQueryable<CustomerGroupDto>>), typeof(GetGenericQueryHandler<CustomerGroupDto, Domain.Customers.CustomerGroup>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<VendorDto, Vendor>,+ IQueryable<VendorDto>>), typeof(GetGenericQueryHandler<VendorDto, Vendor>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<StoreDto, Domain.Stores.Store>,- IQueryable<StoreDto>>), typeof(GetGenericQueryHandler<StoreDto, Domain.Stores.Store>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<CustomerGroupDto, CustomerGroup>,+ IQueryable<CustomerGroupDto>>), typeof(GetGenericQueryHandler<CustomerGroupDto, CustomerGroup>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<LanguageDto, Domain.Localization.Language>,- IQueryable<LanguageDto>>), typeof(GetGenericQueryHandler<LanguageDto, Domain.Localization.Language>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<StoreDto, Store>,+ IQueryable<StoreDto>>), typeof(GetGenericQueryHandler<StoreDto, Store>));- services.AddScoped(typeof(IRequestHandler<GetGenericQuery<PictureDto, Domain.Media.Picture>,- IQueryable<PictureDto>>), typeof(GetGenericQueryHandler<PictureDto, Domain.Media.Picture>));+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<LanguageDto, Language>,+ IQueryable<LanguageDto>>), typeof(GetGenericQueryHandler<LanguageDto, Language>));- }-+ services.AddScoped(typeof(IRequestHandler<GetGenericQuery<PictureDto, Picture>,+ IQueryable<PictureDto>>), typeof(GetGenericQueryHandler<PictureDto, Picture>));}--}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Infrastructure/SwaggerStartup.cs b/src/API/Grand.Api/Infrastructure/SwaggerStartup.csindex dc9ec2a05..672773b84 100644--- a/src/API/Grand.Api/Infrastructure/SwaggerStartup.cs+++ b/src/API/Grand.Api/Infrastructure/SwaggerStartup.cs@@ -10,107 +10,103 @@ using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.OpenApi.Models;-namespace Grand.Api.Infrastructure+namespace Grand.Api.Infrastructure;++public class SwaggerStartup : IStartupApplication{- public class SwaggerStartup : IStartupApplication+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment){- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- var backendApiConfig = application.ApplicationServices.GetService<BackendAPIConfig>();- var frontApiConfig = application.ApplicationServices.GetService<FrontendAPIConfig>();- var swagger = application.ApplicationServices.GetService<IConfiguration>().GetValue<bool>("UseSwagger");- if (backendApiConfig.Enabled)- application.UseODataQueryRequest();+ var backendApiConfig = application.ApplicationServices.GetService<BackendAPIConfig>();+ var frontApiConfig = application.ApplicationServices.GetService<FrontendAPIConfig>();+ var swagger = application.ApplicationServices.GetService<IConfiguration>().GetValue<bool>("UseSwagger");+ if (backendApiConfig.Enabled)+ application.UseODataQueryRequest();- if (swagger && (backendApiConfig.Enabled || frontApiConfig.Enabled))+ if (swagger && (backendApiConfig.Enabled || frontApiConfig.Enabled))+ {+ application.UseSwagger();+ application.UseSwaggerUI(c =>{- application.UseSwagger();- application.UseSwaggerUI(c =>- {- if(backendApiConfig.Enabled)- c.SwaggerEndpoint("/swagger/v1/swagger.json", "Grandnode Backend API");-- if(frontApiConfig.Enabled)- c.SwaggerEndpoint("/swagger/v2/swagger.json", "Grandnode Frontend API");- });- }+ if (backendApiConfig.Enabled)+ c.SwaggerEndpoint("/swagger/v1/swagger.json", "Grandnode Backend API");++ if (frontApiConfig.Enabled)+ c.SwaggerEndpoint("/swagger/v2/swagger.json", "Grandnode Frontend API");+ });}+ }- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- var backendApiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();- var frontApiConfig = services.BuildServiceProvider().GetService<FrontendAPIConfig>();- var swagger = configuration.GetValue<bool>("UseSwagger");- if (swagger && (backendApiConfig.Enabled || frontApiConfig.Enabled))+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ var backendApiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();+ var frontApiConfig = services.BuildServiceProvider().GetService<FrontendAPIConfig>();+ var swagger = configuration.GetValue<bool>("UseSwagger");+ if (swagger && (backendApiConfig.Enabled || frontApiConfig.Enabled))+ services.AddSwaggerGen(c =>{- services.AddSwaggerGen(c =>- {- if(backendApiConfig.Enabled)- c.SwaggerDoc("v1", new OpenApiInfo- {- Title = "Grandnode Backend API",- Version = "v1",- Contact = GetOpenApiContact(),- License = GetOpenApiLicense()- });-- if(frontApiConfig.Enabled)- c.SwaggerDoc("v2", new OpenApiInfo- {- Title = "Grandnode Frontend API",- Version = "v2",- Contact = GetOpenApiContact(),- License = GetOpenApiLicense()- });-- c.CustomSchemaIds(s => s.FullName?.Replace("+", "."));- c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, //Name the security scheme- new OpenApiSecurityScheme- {- Description = "JWT Authorization header using the Bearer scheme.",- Type = SecuritySchemeType.Http, //We set the scheme type to http since we're using bearer authentication- Scheme = "bearer" //The name of the HTTP Authorization scheme to be used in the Authorization header. In this case "bearer".- });+ if (backendApiConfig.Enabled)+ c.SwaggerDoc("v1", new OpenApiInfo {+ Title = "Grandnode Backend API",+ Version = "v1",+ Contact = GetOpenApiContact(),+ License = GetOpenApiLicense()+ });- c.AddSecurityRequirement(new OpenApiSecurityRequirement {- {- new OpenApiSecurityScheme {- Reference = new OpenApiReference{- Id = JwtBearerDefaults.AuthenticationScheme, //The name of the previously defined security scheme.- Type = ReferenceType.SecurityScheme- }- },- new List<string>()- }+ if (frontApiConfig.Enabled)+ c.SwaggerDoc("v2", new OpenApiInfo {+ Title = "Grandnode Frontend API",+ Version = "v2",+ Contact = GetOpenApiContact(),+ License = GetOpenApiLicense()});- c.OperationFilter<AddParamOperationFilter>();- c.DocumentFilter<SwaggerODataControllerDocumentFilter>();- c.EnableAnnotations();- c.SchemaFilter<EnumSchemaFilter>();- c.SchemaFilter<IgnoreFieldFilter>();- });- }- }+ c.CustomSchemaIds(s => s.FullName?.Replace("+", "."));+ c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, //Name the security scheme+ new OpenApiSecurityScheme {+ Description = "JWT Authorization header using the Bearer scheme.",+ Type = SecuritySchemeType+ .Http, //We set the scheme type to http since we're using bearer authentication+ Scheme =+ "bearer" //The name of the HTTP Authorization scheme to be used in the Authorization header. In this case "bearer".+ });- public int Priority => 90;- public bool BeforeConfigure => true;+ c.AddSecurityRequirement(new OpenApiSecurityRequirement {+ {+ new OpenApiSecurityScheme {+ Reference = new OpenApiReference {+ Id = JwtBearerDefaults.AuthenticationScheme,+ Type //The name of the previously defined security scheme.+ = ReferenceType.SecurityScheme+ }+ },+ new List<string>()+ }+ });+ c.OperationFilter<AddParamOperationFilter>();+ c.DocumentFilter<SwaggerODataControllerDocumentFilter>();+ c.EnableAnnotations();+ c.SchemaFilter<EnumSchemaFilter>();+ c.SchemaFilter<IgnoreFieldFilter>();+ });+ }- private OpenApiContact GetOpenApiContact()- {- return new OpenApiContact {- Name = "Grandnode",- Email = "[email protected]",- Url = new Uri("https://grandnode.com")- };- }+ public int Priority => 90;+ public bool BeforeConfigure => true;- private OpenApiLicense GetOpenApiLicense()- {- return new OpenApiLicense {- Name = "GNU General Public License v3.0",- Url = new Uri("https://github.com/grandnode/grandnode2/blob/main/LICENSE")- };- }+ private OpenApiContact GetOpenApiContact()+ {+ return new OpenApiContact {+ Name = "Grandnode",+ Email = "[email protected]",+ Url = new Uri("https://grandnode.com")+ };+ }++ private OpenApiLicense GetOpenApiLicense()+ {+ return new OpenApiLicense {+ Name = "GNU General Public License v3.0",+ Url = new Uri("https://github.com/grandnode/grandnode2/blob/main/LICENSE")+ };}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Jwt/JwtToken.cs b/src/API/Grand.Api/Jwt/JwtToken.csindex 1320a9414..37e112388 100644--- a/src/API/Grand.Api/Jwt/JwtToken.cs+++ b/src/API/Grand.Api/Jwt/JwtToken.cs@@ -1,17 +1,16 @@using System.IdentityModel.Tokens.Jwt;-namespace Grand.Api.Jwt-{- public sealed class JwtToken- {- private JwtSecurityToken token;+namespace Grand.Api.Jwt;- internal JwtToken(JwtSecurityToken token)- {- this.token = token;- }+public sealed class JwtToken+{+ private readonly JwtSecurityToken token;- public DateTime ValidTo => token.ValidTo;- public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);+ internal JwtToken(JwtSecurityToken token)+ {+ this.token = token;}-}++ public DateTime ValidTo => token.ValidTo;+ public string Value => new JwtSecurityTokenHandler().WriteToken(token);+}\ No newline at end of filediff --git a/src/API/Grand.Api/Jwt/JwtTokenBuilder.cs b/src/API/Grand.Api/Jwt/JwtTokenBuilder.csindex ca708fc3d..68e300a7e 100644--- a/src/API/Grand.Api/Jwt/JwtTokenBuilder.cs+++ b/src/API/Grand.Api/Jwt/JwtTokenBuilder.cs@@ -2,95 +2,88 @@using System.IdentityModel.Tokens.Jwt;using System.Security.Claims;-namespace Grand.Api.Jwt+namespace Grand.Api.Jwt;++public sealed class JwtTokenBuilder{- public sealed class JwtTokenBuilder- {- private SecurityKey securityKey;- private bool useissuer;- private string issuer = "";- private bool useaudience;- private string audience = "";- private Dictionary<string, string> claims = new Dictionary<string, string>();- private int expiryInMinutes = 5;+ private readonly Dictionary<string, string> claims = new();+ private string audience = "";+ private int expiryInMinutes = 5;+ private string issuer = "";+ private SecurityKey securityKey;+ private bool useaudience;+ private bool useissuer;- private void EnsureArguments()- {- if (this.securityKey == null)- throw new ArgumentNullException(nameof(securityKey));+ private void EnsureArguments()+ {+ if (securityKey == null)+ throw new ArgumentNullException(nameof(securityKey));- if (this.useissuer && string.IsNullOrEmpty(this.issuer))- throw new ArgumentNullException(nameof(issuer));+ if (useissuer && string.IsNullOrEmpty(issuer))+ throw new ArgumentNullException(nameof(issuer));- if (this.useaudience && string.IsNullOrEmpty(this.audience))- throw new ArgumentNullException(nameof(audience));- }+ if (useaudience && string.IsNullOrEmpty(audience))+ throw new ArgumentNullException(nameof(audience));+ }- public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey)- {- this.securityKey = securityKey;- return this;- }+ public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey)+ {+ this.securityKey = securityKey;+ return this;+ }- public JwtTokenBuilder AddIssuer(string issuer)- {- this.issuer = issuer;- this.useissuer = true;- return this;- }+ public JwtTokenBuilder AddIssuer(string issuer)+ {+ this.issuer = issuer;+ useissuer = true;+ return this;+ }- public JwtTokenBuilder AddAudience(string audience)- {- this.audience = audience;- this.useaudience = true;- return this;- }+ public JwtTokenBuilder AddAudience(string audience)+ {+ this.audience = audience;+ useaudience = true;+ return this;+ }- public JwtTokenBuilder AddClaim(string type, string value)- {- this.claims.Add(type, value);- return this;- }+ public JwtTokenBuilder AddClaim(string type, string value)+ {+ claims.Add(type, value);+ return this;+ }- public JwtTokenBuilder AddClaims(Dictionary<string, string> claims)- {- foreach (var item in claims)- {- if (!this.claims.ContainsKey(item.Key) && !string.IsNullOrEmpty(item.Value))- {- this.claims.Add(item.Key, item.Value);- }- }- return this;- }+ public JwtTokenBuilder AddClaims(Dictionary<string, string> claims)+ {+ foreach (var item in claims)+ if (!this.claims.ContainsKey(item.Key) && !string.IsNullOrEmpty(item.Value))+ this.claims.Add(item.Key, item.Value);+ return this;+ }- public JwtTokenBuilder AddExpiry(int expiryInMinutes)- {- this.expiryInMinutes = expiryInMinutes;- return this;- }+ public JwtTokenBuilder AddExpiry(int expiryInMinutes)+ {+ this.expiryInMinutes = expiryInMinutes;+ return this;+ }- public JwtToken Build()- {- EnsureArguments();+ public JwtToken Build()+ {+ EnsureArguments();- var claims = new List<Claim>- {- new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())+ var claims = new List<Claim> {+ new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())}.Union(this.claims.Select(item => new Claim(item.Key, item.Value)));- var token = new JwtSecurityToken(- issuer: this.issuer,- audience: this.audience,- claims: claims,- expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),- signingCredentials: new SigningCredentials(- this.securityKey,- SecurityAlgorithms.HmacSha256));-- return new JwtToken(token);- }+ var token = new JwtSecurityToken(+ issuer,+ audience,+ claims,+ expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),+ signingCredentials: new SigningCredentials(+ securityKey,+ SecurityAlgorithms.HmacSha256));+ return new JwtToken(token);}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Models/BaseApiEntityModel.cs b/src/API/Grand.Api/Models/BaseApiEntityModel.csindex 3592f2067..0a076a306 100644--- a/src/API/Grand.Api/Models/BaseApiEntityModel.cs+++ b/src/API/Grand.Api/Models/BaseApiEntityModel.cs@@ -1,13 +1,11 @@using System.ComponentModel.DataAnnotations;-namespace Grand.Api.Models+namespace Grand.Api.Models;++public class BaseApiEntityModel{- public class BaseApiEntityModel- {- [Key]- public string Id { get; set; }- public DateTime CreatedOnUtc { get; set; }- public DateTime? UpdatedOnUtc { get; set; }+ [Key] public string Id { get; set; }- }-}+ public DateTime CreatedOnUtc { get; set; }+ public DateTime? UpdatedOnUtc { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Models/Common/LoginModel.cs b/src/API/Grand.Api/Models/Common/LoginModel.csindex 5b187d986..96842e02b 100644--- a/src/API/Grand.Api/Models/Common/LoginModel.cs+++ b/src/API/Grand.Api/Models/Common/LoginModel.cs@@ -1,8 +1,7 @@-namespace Grand.Api.Models.Common+namespace Grand.Api.Models.Common;++public class LoginModel{- public class LoginModel- {- public string Email { get; set; }- public string Password { get; set; }- }-}+ public string Email { get; set; }+ public string Password { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Models/Common/LoginWebModel.cs b/src/API/Grand.Api/Models/Common/LoginWebModel.csindex 0e52fce6c..5bbd18299 100644--- a/src/API/Grand.Api/Models/Common/LoginWebModel.cs+++ b/src/API/Grand.Api/Models/Common/LoginWebModel.cs@@ -1,8 +1,7 @@-namespace Grand.Api.Models.Common+namespace Grand.Api.Models.Common;++public class LoginWebModel{- public class LoginWebModel- {- public string Email { get; set; }- public string Password { get; set; }- }-}+ public string Email { get; set; }+ public string Password { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs b/src/API/Grand.Api/Queries/Handlers/Common/GetGenericQueryHandler.csindex 98c4d7233..d5a4ab96a 100644--- a/src/API/Grand.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs+++ b/src/API/Grand.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs@@ -1,29 +1,28 @@using Grand.Api.Models;using Grand.Api.Queries.Models.Common;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using MediatR;-namespace Grand.Api.Queries.Handlers.Common+namespace Grand.Api.Queries.Handlers.Common;++public class GetGenericQueryHandler<T, C> : IRequestHandler<GetGenericQuery<T, C>, IQueryable<T>>+ where T : BaseApiEntityModel+ where C : BaseEntity{- public class GetGenericQueryHandler<T,C> : IRequestHandler<GetGenericQuery<T,C>, IQueryable<T>>- where T : BaseApiEntityModel- where C : BaseEntity- {- private readonly IDatabaseContext _dbContext;+ private readonly IDatabaseContext _dbContext;- public GetGenericQueryHandler(IDatabaseContext dbContext)- {- _dbContext = dbContext;- }- public async Task<IQueryable<T>> Handle(GetGenericQuery<T,C> request, CancellationToken cancellationToken)- {- var query = _dbContext.Table<T>(typeof(C).Name);+ public GetGenericQueryHandler(IDatabaseContext dbContext)+ {+ _dbContext = dbContext;+ }- if (string.IsNullOrEmpty(request.Id))- return query;- return await Task.FromResult(query.Where(x => x.Id == request.Id));+ public async Task<IQueryable<T>> Handle(GetGenericQuery<T, C> request, CancellationToken cancellationToken)+ {+ var query = _dbContext.Table<T>(typeof(C).Name);- }+ if (string.IsNullOrEmpty(request.Id))+ return query;+ return await Task.FromResult(query.Where(x => x.Id == request.Id));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Handlers/Common/GetLayoutQueryHandler.cs b/src/API/Grand.Api/Queries/Handlers/Common/GetLayoutQueryHandler.csindex c5f77ff48..61c2dda5f 100644--- a/src/API/Grand.Api/Queries/Handlers/Common/GetLayoutQueryHandler.cs+++ b/src/API/Grand.Api/Queries/Handlers/Common/GetLayoutQueryHandler.cs@@ -3,25 +3,23 @@ using Grand.Api.Queries.Models.Common;using Grand.Data;using MediatR;-namespace Grand.Api.Queries.Handlers.Common-{- public class GetLayoutQueryHandler : IRequestHandler<GetLayoutQuery, IQueryable<LayoutDto>>- {- private readonly IDatabaseContext _dbContext;+namespace Grand.Api.Queries.Handlers.Common;- public GetLayoutQueryHandler(IDatabaseContext dbContext)- {- _dbContext = dbContext;- }+public class GetLayoutQueryHandler : IRequestHandler<GetLayoutQuery, IQueryable<LayoutDto>>+{+ private readonly IDatabaseContext _dbContext;- public async Task<IQueryable<LayoutDto>> Handle(GetLayoutQuery request, CancellationToken cancellationToken)- {- var query = _dbContext.Table<LayoutDto>(request.LayoutName);+ public GetLayoutQueryHandler(IDatabaseContext dbContext)+ {+ _dbContext = dbContext;+ }- if (string.IsNullOrEmpty(request.Id))- return query;- return await Task.FromResult(query.Where(x => x.Id == request.Id));+ public async Task<IQueryable<LayoutDto>> Handle(GetLayoutQuery request, CancellationToken cancellationToken)+ {+ var query = _dbContext.Table<LayoutDto>(request.LayoutName);- }+ if (string.IsNullOrEmpty(request.Id))+ return query;+ return await Task.FromResult(query.Where(x => x.Id == request.Id));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs b/src/API/Grand.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.csindex 5f529de0b..ac8bc87e1 100644--- a/src/API/Grand.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs+++ b/src/API/Grand.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs@@ -4,20 +4,19 @@ using Grand.Api.Queries.Models.Customers;using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Api.Queries.Handlers.Customers+namespace Grand.Api.Queries.Handlers.Customers;++public class GetCustomerQueryHandler : IRequestHandler<GetCustomerQuery, CustomerDto>{- public class GetCustomerQueryHandler : IRequestHandler<GetCustomerQuery, CustomerDto>- {- private readonly ICustomerService _customerService;+ private readonly ICustomerService _customerService;- public GetCustomerQueryHandler(ICustomerService customerService)- {- _customerService = customerService;- }+ public GetCustomerQueryHandler(ICustomerService customerService)+ {+ _customerService = customerService;+ }- public async Task<CustomerDto> Handle(GetCustomerQuery request, CancellationToken cancellationToken)- {- return (await _customerService.GetCustomerByEmail(request.Email)).ToModel();- }+ public async Task<CustomerDto> Handle(GetCustomerQuery request, CancellationToken cancellationToken)+ {+ return (await _customerService.GetCustomerByEmail(request.Email)).ToModel();}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Models/Common/GetGenericQuery.cs b/src/API/Grand.Api/Queries/Models/Common/GetGenericQuery.csindex 861f207b0..16b491fea 100644--- a/src/API/Grand.Api/Queries/Models/Common/GetGenericQuery.cs+++ b/src/API/Grand.Api/Queries/Models/Common/GetGenericQuery.cs@@ -4,6 +4,5 @@ using MediatR;namespace Grand.Api.Queries.Models.Common;-public record GetGenericQuery<T, C>(string Id = null) : IRequest<IQueryable<T>> where T : BaseApiEntityModel where C : BaseEntity;--+public record GetGenericQuery<T, C>(string Id = null)+ : IRequest<IQueryable<T>> where T : BaseApiEntityModel where C : BaseEntity;\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Models/Common/GetLayoutQuery.cs b/src/API/Grand.Api/Queries/Models/Common/GetLayoutQuery.csindex eed19d499..cbc8ae41a 100644--- a/src/API/Grand.Api/Queries/Models/Common/GetLayoutQuery.cs+++ b/src/API/Grand.Api/Queries/Models/Common/GetLayoutQuery.cs@@ -1,11 +1,10 @@using Grand.Api.DTOs.Common;using MediatR;-namespace Grand.Api.Queries.Models.Common+namespace Grand.Api.Queries.Models.Common;++public class GetLayoutQuery : IRequest<IQueryable<LayoutDto>>{- public class GetLayoutQuery : IRequest<IQueryable<LayoutDto>>- {- public string Id { get; set; }- public string LayoutName { get; set; }- }-}+ public string Id { get; set; }+ public string LayoutName { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Models/Common/GetQuery.cs b/src/API/Grand.Api/Queries/Models/Common/GetQuery.csindex f334cae10..081b92828 100644--- a/src/API/Grand.Api/Queries/Models/Common/GetQuery.cs+++ b/src/API/Grand.Api/Queries/Models/Common/GetQuery.cs@@ -1,9 +1,8 @@using MediatR;-namespace Grand.Api.Queries.Models.Common+namespace Grand.Api.Queries.Models.Common;++public class GetQuery<T> : IRequest<IQueryable<T>> where T : class{- public class GetQuery<T> : IRequest<IQueryable<T>> where T : class- {- public string Id { get; set; }- }-}+ public string Id { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Queries/Models/Customers/GetCustomerQuery.cs b/src/API/Grand.Api/Queries/Models/Customers/GetCustomerQuery.csindex 9195ab1d7..04ef3f5ce 100644--- a/src/API/Grand.Api/Queries/Models/Customers/GetCustomerQuery.cs+++ b/src/API/Grand.Api/Queries/Models/Customers/GetCustomerQuery.cs@@ -1,10 +1,9 @@using Grand.Api.DTOs.Customers;using MediatR;-namespace Grand.Api.Queries.Models.Customers+namespace Grand.Api.Queries.Models.Customers;++public class GetCustomerQuery : IRequest<CustomerDto>{- public class GetCustomerQuery : IRequest<CustomerDto>- {- public string Email { get; set; }- }-}+ public string Email { get; set; }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/BrandValidator.cs b/src/API/Grand.Api/Validators/Catalog/BrandValidator.csindex 03ab33519..5f776ba09 100644--- a/src/API/Grand.Api/Validators/Catalog/BrandValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/BrandValidator.cs@@ -5,47 +5,51 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Storage;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class BrandValidator : BaseGrandValidator<BrandDto>{- public class BrandValidator : BaseGrandValidator<BrandDto>+ public BrandValidator(IEnumerable<IValidatorConsumer<BrandDto>> validators,+ ITranslationService translationService, IPictureService pictureService, IBrandService brandService,+ IBrandLayoutService brandLayoutService)+ : base(validators){- public BrandValidator(IEnumerable<IValidatorConsumer<BrandDto>> validators,- ITranslationService translationService, IPictureService pictureService, IBrandService brandService, IBrandLayoutService brandLayoutService)- : base(validators)+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.Name.Required"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ if (!string.IsNullOrEmpty(x.PictureId)){- if (!string.IsNullOrEmpty(x.PictureId))- {- var picture = await pictureService.GetPictureById(x.PictureId);- if (picture == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.PictureId.NotExists"));+ var picture = await pictureService.GetPictureById(x.PictureId);+ if (picture == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.PictureId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.BrandLayoutId)){- if (!string.IsNullOrEmpty(x.BrandLayoutId))- {- var layout = await brandLayoutService.GetBrandLayoutById(x.BrandLayoutId);- if (layout == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.BrandLayoutId.NotExists"));+ var layout = await brandLayoutService.GetBrandLayoutById(x.BrandLayoutId);+ if (layout == null)+ return false;+ }- RuleFor(x => x).MustAsync(async (x, _, _) =>+ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.BrandLayoutId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var brand = await brandService.GetBrandById(x.Id);- if (brand == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.Id.NotExists"));- }+ var brand = await brandService.GetBrandById(x.Id);+ if (brand == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Brand.Fields.Id.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/CategoryValidator.cs b/src/API/Grand.Api/Validators/Catalog/CategoryValidator.csindex 985bff596..1c735c39c 100644--- a/src/API/Grand.Api/Validators/Catalog/CategoryValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/CategoryValidator.cs@@ -5,59 +5,63 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Storage;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class CategoryValidator : BaseGrandValidator<CategoryDto>{- public class CategoryValidator : BaseGrandValidator<CategoryDto>- {- public CategoryValidator(IEnumerable<IValidatorConsumer<CategoryDto>> validators,- ITranslationService translationService, IPictureService pictureService, ICategoryService categoryService, ICategoryLayoutService+ public CategoryValidator(IEnumerable<IValidatorConsumer<CategoryDto>> validators,+ ITranslationService translationService, IPictureService pictureService, ICategoryService categoryService,+ ICategoryLayoutServicecategoryLayoutService) : base(validators)+ {+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.Name.Required"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>{-- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ if (!string.IsNullOrEmpty(x.PictureId)){- if (!string.IsNullOrEmpty(x.PictureId))- {- var picture = await pictureService.GetPictureById(x.PictureId);- if (picture == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.PictureId.NotExists"));-- RuleFor(x => x).MustAsync(async (x, _, _) =>+ var picture = await pictureService.GetPictureById(x.PictureId);+ if (picture == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.PictureId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.ParentCategoryId)){- if (!string.IsNullOrEmpty(x.ParentCategoryId))- {- var category = await categoryService.GetCategoryById(x.ParentCategoryId);- if (category == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.ParentCategoryId.NotExists"));-- RuleFor(x => x).MustAsync(async (x, _, _) =>+ var category = await categoryService.GetCategoryById(x.ParentCategoryId);+ if (category == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.ParentCategoryId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.CategoryLayoutId)){- if (!string.IsNullOrEmpty(x.CategoryLayoutId))- {- var layout = await categoryLayoutService.GetCategoryLayoutById(x.CategoryLayoutId);- if (layout == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.CategoryLayoutId.NotExists"));-- RuleFor(x => x).MustAsync(async (x, _, _) =>+ var layout = await categoryLayoutService.GetCategoryLayoutById(x.CategoryLayoutId);+ if (layout == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.CategoryLayoutId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var category = await categoryService.GetCategoryById(x.Id);- if (category == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.Id.NotExists"));- }+ var category = await categoryService.GetCategoryById(x.Id);+ if (category == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Category.Fields.Id.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/CollectionValidator.cs b/src/API/Grand.Api/Validators/Catalog/CollectionValidator.csindex 1aae9211b..bf80eb01b 100644--- a/src/API/Grand.Api/Validators/Catalog/CollectionValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/CollectionValidator.cs@@ -5,47 +5,51 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Storage;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class CollectionValidator : BaseGrandValidator<CollectionDto>{- public class CollectionValidator : BaseGrandValidator<CollectionDto>+ public CollectionValidator(IEnumerable<IValidatorConsumer<CollectionDto>> validators,+ ITranslationService translationService, IPictureService pictureService, ICollectionService collectionService,+ ICollectionLayoutService collectionLayoutService)+ : base(validators){- public CollectionValidator(IEnumerable<IValidatorConsumer<CollectionDto>> validators,- ITranslationService translationService, IPictureService pictureService, ICollectionService collectionService, ICollectionLayoutService collectionLayoutService)- : base(validators)+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.Name.Required"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ if (!string.IsNullOrEmpty(x.PictureId)){- if (!string.IsNullOrEmpty(x.PictureId))- {- var picture = await pictureService.GetPictureById(x.PictureId);- if (picture == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.PictureId.NotExists"));+ var picture = await pictureService.GetPictureById(x.PictureId);+ if (picture == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.PictureId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.CollectionLayoutId)){- if (!string.IsNullOrEmpty(x.CollectionLayoutId))- {- var layout = await collectionLayoutService.GetCollectionLayoutById(x.CollectionLayoutId);- if (layout == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.CollectionLayoutId.NotExists"));+ var layout = await collectionLayoutService.GetCollectionLayoutById(x.CollectionLayoutId);+ if (layout == null)+ return false;+ }- RuleFor(x => x).MustAsync(async (x, _, _) =>+ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.CollectionLayoutId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var collection = await collectionService.GetCollectionById(x.Id);- if (collection == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.Id.NotExists"));- }+ var collection = await collectionService.GetCollectionById(x.Id);+ if (collection == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Collection.Fields.Id.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductAttributeMappingValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductAttributeMappingValidator.csindex 4740fd37d..1ea7455c5 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductAttributeMappingValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductAttributeMappingValidator.cs@@ -4,20 +4,20 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductAttributeMappingValidator : BaseGrandValidator<ProductAttributeMappingDto>{- public class ProductAttributeMappingValidator : BaseGrandValidator<ProductAttributeMappingDto>+ public ProductAttributeMappingValidator(+ IEnumerable<IValidatorConsumer<ProductAttributeMappingDto>> validators,+ ITranslationService translationService, IProductAttributeService productAttributeService)+ : base(validators){- public ProductAttributeMappingValidator(- IEnumerable<IValidatorConsumer<ProductAttributeMappingDto>> validators,- ITranslationService translationService, IProductAttributeService productAttributeService)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- var productAttribute = await productAttributeService.GetProductAttributeById(x.ProductAttributeId);- return productAttribute != null;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductAttributeMapping.Fields.ProductAttributeId.NotExists"));- }+ var productAttribute = await productAttributeService.GetProductAttributeById(x.ProductAttributeId);+ return productAttribute != null;+ }).WithMessage(+ translationService.GetResource("Api.Catalog.ProductAttributeMapping.Fields.ProductAttributeId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductAttributeValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductAttributeValidator.csindex b52587b85..615f137d4 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductAttributeValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductAttributeValidator.cs@@ -4,34 +4,34 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductAttributeValidator : BaseGrandValidator<ProductAttributeDto>{- public class ProductAttributeValidator : BaseGrandValidator<ProductAttributeDto>+ public ProductAttributeValidator(IEnumerable<IValidatorConsumer<ProductAttributeDto>> validators,+ ITranslationService translationService, IProductAttributeService productAttributeService)+ : base(validators){- public ProductAttributeValidator(IEnumerable<IValidatorConsumer<ProductAttributeDto>> validators,- ITranslationService translationService, IProductAttributeService productAttributeService)- : base(validators)+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.ProductAttribute.Fields.Name.Required"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.ProductAttribute.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- if (!string.IsNullOrEmpty(x.Id))- {- var pa = await productAttributeService.GetProductAttributeById(x.Id);- if (pa == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductAttribute.Fields.Id.NotExists"));- RuleFor(x => x).Must((x, _) =>+ if (!string.IsNullOrEmpty(x.Id)){- foreach (var item in x.PredefinedProductAttributeValues)- {- if (string.IsNullOrEmpty(item.Name))- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.PredefinedProductAttributeValue.Fields.Name.Required"));- }+ var pa = await productAttributeService.GetProductAttributeById(x.Id);+ if (pa == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductAttribute.Fields.Id.NotExists"));+ RuleFor(x => x).Must((x, _) =>+ {+ foreach (var item in x.PredefinedProductAttributeValues)+ if (string.IsNullOrEmpty(item.Name))+ return false;+ return true;+ }).WithMessage(+ translationService.GetResource("Api.Catalog.PredefinedProductAttributeValue.Fields.Name.Required"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductCategoryValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductCategoryValidator.csindex a4de9b37b..37389a2d9 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductCategoryValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductCategoryValidator.cs@@ -4,18 +4,18 @@ using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductCategoryValidator : BaseGrandValidator<ProductCategoryDto>{- public class ProductCategoryValidator : BaseGrandValidator<ProductCategoryDto>+ public ProductCategoryValidator(IEnumerable<IValidatorConsumer<ProductCategoryDto>> validators,+ ITranslationService translationService, ICategoryService categoryService)+ : base(validators){- public ProductCategoryValidator(IEnumerable<IValidatorConsumer<ProductCategoryDto>> validators, ITranslationService translationService, ICategoryService categoryService)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- var category = await categoryService.GetCategoryById(x.CategoryId);- return category != null;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductCategory.Fields.CategoryId.NotExists"));- }+ var category = await categoryService.GetCategoryById(x.CategoryId);+ return category != null;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductCategory.Fields.CategoryId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductCollectionValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductCollectionValidator.csindex cfc99ace7..1fe0cc0ba 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductCollectionValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductCollectionValidator.cs@@ -4,19 +4,18 @@ using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductCollectionValidator : BaseGrandValidator<ProductCollectionDto>{- public class ProductCollectionValidator : BaseGrandValidator<ProductCollectionDto>+ public ProductCollectionValidator(IEnumerable<IValidatorConsumer<ProductCollectionDto>> validators,+ ITranslationService translationService, ICollectionService collectionService)+ : base(validators){- public ProductCollectionValidator(IEnumerable<IValidatorConsumer<ProductCollectionDto>> validators,- ITranslationService translationService, ICollectionService collectionService)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- var collection = await collectionService.GetCollectionById(x.CollectionId);- return collection != null;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductCollection.Fields.CollectionId.NotExists"));- }+ var collection = await collectionService.GetCollectionById(x.CollectionId);+ return collection != null;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductCollection.Fields.CollectionId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductPictureValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductPictureValidator.csindex 7e3fa812c..d6e5235bb 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductPictureValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductPictureValidator.cs@@ -4,19 +4,18 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Storage;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductPictureValidator : BaseGrandValidator<ProductPictureDto>{- public class ProductPictureValidator : BaseGrandValidator<ProductPictureDto>+ public ProductPictureValidator(IEnumerable<IValidatorConsumer<ProductPictureDto>> validators,+ ITranslationService translationService, IPictureService pictureService)+ : base(validators){- public ProductPictureValidator(IEnumerable<IValidatorConsumer<ProductPictureDto>> validators,- ITranslationService translationService, IPictureService pictureService)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- var picture = await pictureService.GetPictureById(x.PictureId);- return picture != null;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductPicture.Fields.PictureId.NotExists"));- }+ var picture = await pictureService.GetPictureById(x.PictureId);+ return picture != null;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductPicture.Fields.PictureId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductSpecificationAttributeValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductSpecificationAttributeValidator.csindex ab9ae8c0a..2b3323d47 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductSpecificationAttributeValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductSpecificationAttributeValidator.cs@@ -4,31 +4,36 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductSpecificationAttributeValidator : BaseGrandValidator<ProductSpecificationAttributeDto>{- public class ProductSpecificationAttributeValidator : BaseGrandValidator<ProductSpecificationAttributeDto>+ public ProductSpecificationAttributeValidator(+ IEnumerable<IValidatorConsumer<ProductSpecificationAttributeDto>> validators,+ ITranslationService translationService, ISpecificationAttributeService specificationAttributeService)+ : base(validators){- public ProductSpecificationAttributeValidator(- IEnumerable<IValidatorConsumer<ProductSpecificationAttributeDto>> validators,- ITranslationService translationService, ISpecificationAttributeService specificationAttributeService)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- var specification = await specificationAttributeService.GetSpecificationAttributeById(x.SpecificationAttributeId);- return specification != null;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductSpecificationAttribute.Fields.SpecificationAttributeId.NotExists"));+ var specification =+ await specificationAttributeService.GetSpecificationAttributeById(x.SpecificationAttributeId);+ return specification != null;+ }).WithMessage(+ translationService.GetResource(+ "Api.Catalog.ProductSpecificationAttribute.Fields.SpecificationAttributeId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.SpecificationAttributeOptionId)){- if (!string.IsNullOrEmpty(x.SpecificationAttributeOptionId))- {- var sa = await specificationAttributeService.GetSpecificationAttributeByOptionId(x.SpecificationAttributeOptionId);- if (sa == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductSpecificationAttribute.Fields.SpecificationAttributeOptionId.NotExists"));- }+ var sa = await specificationAttributeService.GetSpecificationAttributeByOptionId(+ x.SpecificationAttributeOptionId);+ if (sa == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource(+ "Api.Catalog.ProductSpecificationAttribute.Fields.SpecificationAttributeOptionId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductTierPriceValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductTierPriceValidator.csindex da3a383b8..6a55e3ba1 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductTierPriceValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductTierPriceValidator.cs@@ -5,38 +5,41 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Stores;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductTierPriceValidator : BaseGrandValidator<ProductTierPriceDto>{- public class ProductTierPriceValidator : BaseGrandValidator<ProductTierPriceDto>+ public ProductTierPriceValidator(+ IEnumerable<IValidatorConsumer<ProductTierPriceDto>> validators,+ ITranslationService translationService, IStoreService storeService, IGroupService groupService)+ : base(validators){- public ProductTierPriceValidator(- IEnumerable<IValidatorConsumer<ProductTierPriceDto>> validators,- ITranslationService translationService, IStoreService storeService, IGroupService groupService)- : base(validators)- {- RuleFor(x => x.Quantity).GreaterThan(0).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.Quantity.GreaterThan0"));- RuleFor(x => x.Price).GreaterThan(0).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.Price.GreaterThan0"));+ RuleFor(x => x.Quantity).GreaterThan(0)+ .WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.Quantity.GreaterThan0"));+ RuleFor(x => x.Price).GreaterThan(0)+ .WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.Price.GreaterThan0"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.StoreId)){- if (!string.IsNullOrEmpty(x.StoreId))- {- var store = await storeService.GetStoreById(x.StoreId);- if (store == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.StoreId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ var store = await storeService.GetStoreById(x.StoreId);+ if (store == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.StoreId.NotExists"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.CustomerGroupId)){- if (!string.IsNullOrEmpty(x.CustomerGroupId))- {- var group = await groupService.GetCustomerGroupById(x.CustomerGroupId);- if (group == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.CustomerGroupId.NotExists"));- }+ var group = await groupService.GetCustomerGroupById(x.CustomerGroupId);+ if (group == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.ProductTierPrice.Fields.CustomerGroupId.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/ProductValidator.cs b/src/API/Grand.Api/Validators/Catalog/ProductValidator.csindex 5f3e3c9dc..75e72132a 100644--- a/src/API/Grand.Api/Validators/Catalog/ProductValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/ProductValidator.cs@@ -8,87 +8,94 @@ using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class ProductValidator : BaseGrandValidator<ProductDto>{- public class ProductValidator : BaseGrandValidator<ProductDto>+ public ProductValidator(+ IEnumerable<IValidatorConsumer<ProductDto>> validators,+ ITranslationService translationService, IProductService productService,+ IProductLayoutService productLayoutService,+ IBrandService brandService,+ IVendorService vendorService, CommonSettings commonSettings)+ : base(validators){- public ProductValidator(- IEnumerable<IValidatorConsumer<ProductDto>> validators,- ITranslationService translationService, IProductService productService, IProductLayoutService productLayoutService,- IBrandService brandService,- IVendorService vendorService, CommonSettings commonSettings)- : base(validators)- {- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.Name.Required"));- //RuleFor(x => x.ProductType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ProductType.Required"));- //RuleFor(x => x.BackorderMode).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.BackorderMode.Required"));- //RuleFor(x => x.DownloadActivationType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.DownloadActivationType.Required"));- //RuleFor(x => x.IntervalUnitType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.IntervalUnitType.Required"));- //RuleFor(x => x.GiftCardType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.GiftCardType.Required"));- //RuleFor(x => x.LowStockActivity).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.LowStockActivity.Required"));- //RuleFor(x => x.ManageInventoryMethod).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ManageInventoryMethod.Required"));- //RuleFor(x => x.RecurringCyclePeriod).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.RecurringCyclePeriod.Required"));+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.Name.Required"));+ //RuleFor(x => x.ProductType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ProductType.Required"));+ //RuleFor(x => x.BackorderMode).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.BackorderMode.Required"));+ //RuleFor(x => x.DownloadActivationType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.DownloadActivationType.Required"));+ //RuleFor(x => x.IntervalUnitType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.IntervalUnitType.Required"));+ //RuleFor(x => x.GiftCardType).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.GiftCardType.Required"));+ //RuleFor(x => x.LowStockActivity).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.LowStockActivity.Required"));+ //RuleFor(x => x.ManageInventoryMethod).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ManageInventoryMethod.Required"));+ //RuleFor(x => x.RecurringCyclePeriod).IsInEnum().WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.RecurringCyclePeriod.Required"));- if (!commonSettings.AllowEditProductEndedAuction)- RuleFor(x => x.AuctionEnded && x.ProductTypeId == ProductType.Auction).Equal(false).WithMessage(translationService.GetResource("Api.Catalog.Products.Cannoteditauction"));+ if (!commonSettings.AllowEditProductEndedAuction)+ RuleFor(x => x.AuctionEnded && x.ProductTypeId == ProductType.Auction).Equal(false)+ .WithMessage(translationService.GetResource("Api.Catalog.Products.Cannoteditauction"));- RuleFor(x => x.ProductTypeId == ProductType.Auction && !x.AvailableEndDateTimeUtc.HasValue).Equal(false).WithMessage(translationService.GetResource("Api.Catalog.Products.Fields.AvailableEndDateTime.Required"));+ RuleFor(x => x.ProductTypeId == ProductType.Auction && !x.AvailableEndDateTimeUtc.HasValue).Equal(false)+ .WithMessage(translationService.GetResource("Api.Catalog.Products.Fields.AvailableEndDateTime.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.ParentGroupedProductId)){- if (!string.IsNullOrEmpty(x.ParentGroupedProductId))- {- var product = await productService.GetProductById(x.ParentGroupedProductId);- if (product == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ParentGroupedProductId.NotExists"));+ var product = await productService.GetProductById(x.ParentGroupedProductId);+ if (product == null)+ return false;+ }- RuleFor(x => x).MustAsync(async (x, _, _) =>+ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ParentGroupedProductId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.ProductLayoutId)){- if (!string.IsNullOrEmpty(x.ProductLayoutId))- {- var layout = await productLayoutService.GetProductLayoutById(x.ProductLayoutId);- if (layout == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ProductLayoutId.NotExists"));+ var layout = await productLayoutService.GetProductLayoutById(x.ProductLayoutId);+ if (layout == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.ProductLayoutId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.VendorId)){- if (!string.IsNullOrEmpty(x.VendorId))- {- var vendor = await vendorService.GetVendorById(x.VendorId);- if (vendor == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.VendorId.NotExists"));+ var vendor = await vendorService.GetVendorById(x.VendorId);+ if (vendor == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.VendorId.NotExists"));- RuleFor(x => x).MustAsync(async (x, _, _) =>+ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.BrandId)){- if (!string.IsNullOrEmpty(x.BrandId))- {- var brand = await brandService.GetBrandById(x.BrandId);- if (brand == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.BrandId.NotExists"));+ var brand = await brandService.GetBrandById(x.BrandId);+ if (brand == null)+ return false;+ }- RuleFor(x => x).MustAsync(async (x, _, _) =>+ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.BrandId.NotExists"));++ RuleFor(x => x).MustAsync(async (x, _, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var product = await productService.GetProductById(x.Id);- if (product == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.Id.NotExists"));+ var product = await productService.GetProductById(x.Id);+ if (product == null)+ return false;+ }- }+ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.Product.Fields.Id.NotExists"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Catalog/SpecificationAttributeValidator.cs b/src/API/Grand.Api/Validators/Catalog/SpecificationAttributeValidator.csindex 8d5720808..290abcf6a 100644--- a/src/API/Grand.Api/Validators/Catalog/SpecificationAttributeValidator.cs+++ b/src/API/Grand.Api/Validators/Catalog/SpecificationAttributeValidator.cs@@ -4,35 +4,35 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Catalog+namespace Grand.Api.Validators.Catalog;++public class SpecificationAttributeValidator : BaseGrandValidator<SpecificationAttributeDto>{- public class SpecificationAttributeValidator : BaseGrandValidator<SpecificationAttributeDto>+ public SpecificationAttributeValidator(+ IEnumerable<IValidatorConsumer<SpecificationAttributeDto>> validators,+ ITranslationService translationService, ISpecificationAttributeService specificationAttributeService)+ : base(validators){- public SpecificationAttributeValidator(- IEnumerable<IValidatorConsumer<SpecificationAttributeDto>> validators,- ITranslationService translationService, ISpecificationAttributeService specificationAttributeService)- : base(validators)+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Catalog.SpecificationAttribute.Fields.Name.Required"));+ RuleFor(x => x).MustAsync(async (x, _, _) =>{- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Catalog.SpecificationAttribute.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _, _) =>- {- if (!string.IsNullOrEmpty(x.Id))- {- var sa = await specificationAttributeService.GetSpecificationAttributeById(x.Id);- if (sa == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.SpecificationAttribute.Fields.Id.NotExists"));- RuleFor(x => x).Must((x, _) =>+ if (!string.IsNullOrEmpty(x.Id)){- foreach (var item in x.SpecificationAttributeOptions)- {- if (string.IsNullOrEmpty(item.Name))- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Catalog.SpecificationAttributeOptions.Fields.Name.Required"));- }+ var sa = await specificationAttributeService.GetSpecificationAttributeById(x.Id);+ if (sa == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Catalog.SpecificationAttribute.Fields.Id.NotExists"));+ RuleFor(x => x).Must((x, _) =>+ {+ foreach (var item in x.SpecificationAttributeOptions)+ if (string.IsNullOrEmpty(item.Name))+ return false;+ return true;+ }).WithMessage(+ translationService.GetResource("Api.Catalog.SpecificationAttributeOptions.Fields.Name.Required"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Common/LoginValidator.cs b/src/API/Grand.Api/Validators/Common/LoginValidator.csindex 715cf0083..5bcd04255 100644--- a/src/API/Grand.Api/Validators/Common/LoginValidator.cs+++ b/src/API/Grand.Api/Validators/Common/LoginValidator.cs@@ -6,45 +6,47 @@ using Grand.Domain.Customers;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Common+namespace Grand.Api.Validators.Common;++public class LoginValidator : BaseGrandValidator<LoginModel>{- public class LoginValidator : BaseGrandValidator<LoginModel>+ public LoginValidator(+ IEnumerable<IValidatorConsumer<LoginModel>> validators,+ BackendAPIConfig apiConfig, ICustomerService customerService, IUserApiService userApiService,+ IEncryptionService encryptionService)+ : base(validators){- public LoginValidator(- IEnumerable<IValidatorConsumer<LoginModel>> validators,- BackendAPIConfig apiConfig, ICustomerService customerService, IUserApiService userApiService, IEncryptionService encryptionService)- : base(validators)- {- if (!apiConfig.Enabled)- RuleFor(x => x).Must(_ => false).WithMessage("API is disabled");+ if (!apiConfig.Enabled)+ RuleFor(x => x).Must(_ => false).WithMessage("API is disabled");- RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required");- RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required");- RuleFor(x => x).MustAsync(async (x, _) =>- {- if (!string.IsNullOrEmpty(x.Email))- {- var userapi = await userApiService.GetUserByEmail(x.Email.ToLowerInvariant());- if (userapi is { IsActive: true })- {- var base64EncodedBytes = Convert.FromBase64String(x.Password);- var password = Encoding.UTF8.GetString(base64EncodedBytes);- if (userapi.Password == encryptionService.EncryptText(password, userapi.PrivateKey))- return true;- }- }- return false;- }).WithMessage("User not exists or password is wrong");- RuleFor(x => x).MustAsync(async (x, _) =>+ RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required");+ RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required");+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ if (!string.IsNullOrEmpty(x.Email)){- if (!string.IsNullOrEmpty(x.Email))+ var userapi = await userApiService.GetUserByEmail(x.Email.ToLowerInvariant());+ if (userapi is { IsActive: true }){- var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant());- if (customer is { Active: true } && !customer.IsSystemAccount())+ var base64EncodedBytes = Convert.FromBase64String(x.Password);+ var password = Encoding.UTF8.GetString(base64EncodedBytes);+ if (userapi.Password == encryptionService.EncryptText(password, userapi.PrivateKey))return true;}- return false;- }).WithMessage("Customer not exist");- }+ }++ return false;+ }).WithMessage("User not exists or password is wrong");+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ if (!string.IsNullOrEmpty(x.Email))+ {+ var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant());+ if (customer is { Active: true } && !customer.IsSystemAccount())+ return true;+ }++ return false;+ }).WithMessage("Customer not exist");}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Common/LoginWebValidator.cs b/src/API/Grand.Api/Validators/Common/LoginWebValidator.csindex c96e4b45c..12a5b7d70 100644--- a/src/API/Grand.Api/Validators/Common/LoginWebValidator.cs+++ b/src/API/Grand.Api/Validators/Common/LoginWebValidator.cs@@ -5,39 +5,41 @@ using Grand.Domain.Customers;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Common+namespace Grand.Api.Validators.Common;++public class LoginWebValidator : BaseGrandValidator<LoginWebModel>{- public class LoginWebValidator : BaseGrandValidator<LoginWebModel>+ public LoginWebValidator(+ IEnumerable<IValidatorConsumer<LoginWebModel>> validators,+ FrontendAPIConfig apiConfig,+ ICustomerService customerService,+ ICustomerManagerService customerManagerService)+ : base(validators){- public LoginWebValidator(- IEnumerable<IValidatorConsumer<LoginWebModel>> validators,- FrontendAPIConfig apiConfig,- ICustomerService customerService,- ICustomerManagerService customerManagerService)- : base(validators)+ if (!apiConfig.Enabled)+ {+ RuleFor(x => x).Must(_ => false).WithMessage("API is disabled");+ }+ else{- if (!apiConfig.Enabled)- RuleFor(x => x).Must(_ => false).WithMessage("API is disabled");- else+ RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required");+ RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required");+ RuleFor(x => x).MustAsync(async (x, _) =>{- RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required");- RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required");- RuleFor(x => x).MustAsync(async (x, _) =>+ if (!string.IsNullOrEmpty(x.Email)){- if (!string.IsNullOrEmpty(x.Email))+ var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant());+ if (customer is { Active: true } && !customer.IsSystemAccount()){- var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant());- if (customer is { Active: true } && !customer.IsSystemAccount())- {- var base64EncodedBytes = Convert.FromBase64String(x.Password);- var password = Encoding.UTF8.GetString(base64EncodedBytes);- var result = await customerManagerService.LoginCustomer(x.Email, password);- return result == CustomerLoginResults.Successful;- }+ var base64EncodedBytes = Convert.FromBase64String(x.Password);+ var password = Encoding.UTF8.GetString(base64EncodedBytes);+ var result = await customerManagerService.LoginCustomer(x.Email, password);+ return result == CustomerLoginResults.Successful;}- return false;- }).WithMessage("Customer not exist or password is wrong");- }+ }++ return false;+ }).WithMessage("Customer not exist or password is wrong");}}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Common/PictureValidator.cs b/src/API/Grand.Api/Validators/Common/PictureValidator.csindex 8660ac366..6004931aa 100644--- a/src/API/Grand.Api/Validators/Common/PictureValidator.cs+++ b/src/API/Grand.Api/Validators/Common/PictureValidator.cs@@ -1,26 +1,23 @@using FluentValidation;using Grand.Api.DTOs.Common;-using Grand.Infrastructure.Validators;using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Infrastructure.Validators;++namespace Grand.Api.Validators.Common;-namespace Grand.Api.Validators.Common+public class PictureValidator : BaseGrandValidator<PictureDto>{- public class PictureValidator : BaseGrandValidator<PictureDto>+ public PictureValidator(+ IEnumerable<IValidatorConsumer<PictureDto>> validators,+ ITranslationService translationService)+ : base(validators){- public PictureValidator(- IEnumerable<IValidatorConsumer<PictureDto>> validators,- ITranslationService translationService)- : base(validators)+ RuleFor(x => x.MimeType).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Common.Picture.Fields.MimeType.Required"));+ RuleFor(x => x.PictureBinary).Must((x, _) =>{- RuleFor(x => x.MimeType).NotEmpty().WithMessage(translationService.GetResource("Api.Common.Picture.Fields.MimeType.Required"));- RuleFor(x => x.PictureBinary).Must((x, _) =>- {- if (!string.IsNullOrEmpty(x.Id) && (x.PictureBinary==null || x.PictureBinary.Length == 0))- {- return true;- }- return !string.IsNullOrEmpty(x.Id) || (x.PictureBinary != null && x.PictureBinary.Length != 0);- }).WithMessage(translationService.GetResource("Api.Common.Picture.Fields.PictureBinary.Required"));- }+ if (!string.IsNullOrEmpty(x.Id) && (x.PictureBinary == null || x.PictureBinary.Length == 0)) return true;+ return !string.IsNullOrEmpty(x.Id) || (x.PictureBinary != null && x.PictureBinary.Length != 0);+ }).WithMessage(translationService.GetResource("Api.Common.Picture.Fields.PictureBinary.Required"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Customers/AddressValidator.cs b/src/API/Grand.Api/Validators/Customers/AddressValidator.csindex 45e84d95f..3ead38822 100644--- a/src/API/Grand.Api/Validators/Customers/AddressValidator.cs+++ b/src/API/Grand.Api/Validators/Customers/AddressValidator.cs@@ -5,88 +5,75 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Domain.Common;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Customers+namespace Grand.Api.Validators.Customers;++public class AddressValidator : BaseGrandValidator<AddressDto>{- public class AddressValidator : BaseGrandValidator<AddressDto>+ public AddressValidator(+ IEnumerable<IValidatorConsumer<AddressDto>> validators,+ ITranslationService translationService, ICountryService countryService, AddressSettings addressSettings)+ : base(validators){- public AddressValidator(- IEnumerable<IValidatorConsumer<AddressDto>> validators,- ITranslationService translationService, ICountryService countryService, AddressSettings addressSettings)- : base(validators)+ RuleFor(x => x.FirstName)+ .NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.FirstName.Required"));+ RuleFor(x => x.LastName)+ .NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.LastName.Required"));+ RuleFor(x => x.Email)+ .NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Email.Required"));+ RuleFor(x => x.Email)+ .EmailAddress()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Common.WrongEmail"));+ if (addressSettings.CountryEnabled){- RuleFor(x => x.FirstName)- .NotEmpty()- .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.FirstName.Required"));- RuleFor(x => x.LastName)- .NotEmpty()- .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.LastName.Required"));- RuleFor(x => x.Email)- .NotEmpty()- .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Email.Required"));- RuleFor(x => x.Email)- .EmailAddress()- .WithMessage(translationService.GetResource("Api.Customers.Address.Common.WrongEmail"));- if (addressSettings.CountryEnabled)- {- RuleFor(x => x.CountryId)- .NotNull()- .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Country.Required"));- RuleFor(x => x.CountryId)- .NotEqual("")- .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Country.Required"));- }- if (addressSettings.CountryEnabled && addressSettings.StateProvinceEnabled)+ RuleFor(x => x.CountryId)+ .NotNull()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Country.Required"));+ RuleFor(x => x.CountryId)+ .NotEqual("")+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Country.Required"));+ }++ if (addressSettings.CountryEnabled && addressSettings.StateProvinceEnabled)+ RuleFor(x => x.StateProvinceId).MustAsync(async (x, y, _) =>{- RuleFor(x => x.StateProvinceId).MustAsync(async (x, y, _) =>+ var countryId = !string.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";+ var country = await countryService.GetCountryById(countryId);+ if (country != null && country.StateProvinces.Any()){- var countryId = !string.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";- var country = await countryService.GetCountryById(countryId);- if (country != null && country.StateProvinces.Any())- {- //if yes, then ensure that state is selected- if (String.IsNullOrEmpty(y))- {- return false;- }- if (country.StateProvinces.FirstOrDefault(stateProvince => stateProvince.Id == y) != null)- return true;- }- return false;- }).WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StateProvince.Required"));- }- if (addressSettings.CompanyRequired && addressSettings.CompanyEnabled)- {- RuleFor(x => x.Company).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Company.Required"));- }- if (addressSettings.VatNumberRequired && addressSettings.VatNumberEnabled)- {- RuleFor(x => x.VatNumber).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.VatNumber.Required"));- }- if (addressSettings.StreetAddressRequired && addressSettings.StreetAddressEnabled)- {- RuleFor(x => x.Address1).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StreetAddress.Required"));- }- if (addressSettings.StreetAddress2Required && addressSettings.StreetAddress2Enabled)- {- RuleFor(x => x.Address2).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StreetAddress2.Required"));- }- if (addressSettings.ZipPostalCodeRequired && addressSettings.ZipPostalCodeEnabled)- {- RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.ZipPostalCode.Required"));- }- if (addressSettings.CityRequired && addressSettings.CityEnabled)- {- RuleFor(x => x.City).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.City.Required"));- }- if (addressSettings.PhoneRequired && addressSettings.PhoneEnabled)- {- RuleFor(x => x.PhoneNumber).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Phone.Required"));- }- if (addressSettings.FaxRequired && addressSettings.FaxEnabled)- {- RuleFor(x => x.FaxNumber).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Fax.Required"));- }- }- }+ //if yes, then ensure that state is selected+ if (string.IsNullOrEmpty(y)) return false;+ if (country.StateProvinces.FirstOrDefault(stateProvince => stateProvince.Id == y) != null)+ return true;+ }-}+ return false;+ }).WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StateProvince.Required"));+ if (addressSettings.CompanyRequired && addressSettings.CompanyEnabled)+ RuleFor(x => x.Company).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Company.Required"));+ if (addressSettings.VatNumberRequired && addressSettings.VatNumberEnabled)+ RuleFor(x => x.VatNumber).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.VatNumber.Required"));+ if (addressSettings.StreetAddressRequired && addressSettings.StreetAddressEnabled)+ RuleFor(x => x.Address1).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StreetAddress.Required"));+ if (addressSettings.StreetAddress2Required && addressSettings.StreetAddress2Enabled)+ RuleFor(x => x.Address2).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.StreetAddress2.Required"));+ if (addressSettings.ZipPostalCodeRequired && addressSettings.ZipPostalCodeEnabled)+ RuleFor(x => x.ZipPostalCode).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.ZipPostalCode.Required"));+ if (addressSettings.CityRequired && addressSettings.CityEnabled)+ RuleFor(x => x.City).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.City.Required"));+ if (addressSettings.PhoneRequired && addressSettings.PhoneEnabled)+ RuleFor(x => x.PhoneNumber).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Phone.Required"));+ if (addressSettings.FaxRequired && addressSettings.FaxEnabled)+ RuleFor(x => x.FaxNumber).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.Address.Fields.Fax.Required"));+ }+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Customers/CustomerGroupValidator.cs b/src/API/Grand.Api/Validators/Customers/CustomerGroupValidator.csindex 1b93979ad..d86db112f 100644--- a/src/API/Grand.Api/Validators/Customers/CustomerGroupValidator.cs+++ b/src/API/Grand.Api/Validators/Customers/CustomerGroupValidator.cs@@ -4,51 +4,49 @@ using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Customers+namespace Grand.Api.Validators.Customers;++public class CustomerGroupValidator : BaseGrandValidator<CustomerGroupDto>{- public class CustomerGroupValidator : BaseGrandValidator<CustomerGroupDto>+ public CustomerGroupValidator(+ IEnumerable<IValidatorConsumer<CustomerGroupDto>> validators,+ ITranslationService translationService, IGroupService groupService)+ : base(validators){- public CustomerGroupValidator(- IEnumerable<IValidatorConsumer<CustomerGroupDto>> validators,- ITranslationService translationService, IGroupService groupService)- : base(validators)- {- RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Name.Required"));+ RuleFor(x => x.Name).NotEmpty()+ .WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Name.Required"));- RuleFor(x => x).MustAsync(async (x, _) =>+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var group = await groupService.GetCustomerGroupById(x.Id);- if (group == null)- return false;- }- return true;- }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Id.NotExists"));- RuleFor(x => x).MustAsync(async (x, _) =>+ var group = await groupService.GetCustomerGroupById(x.Id);+ if (group == null)+ return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Id.NotExists"));+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var customerGroup = await groupService.GetCustomerGroupById(x.Id);- if (customerGroup.IsSystem && !x.Active)- {- return false;- }- }- return true;- }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Active.CantEditSystem"));- RuleFor(x => x).MustAsync(async (x, _) =>+ var customerGroup = await groupService.GetCustomerGroupById(x.Id);+ if (customerGroup.IsSystem && !x.Active) return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.Active.CantEditSystem"));+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ if (!string.IsNullOrEmpty(x.Id)){- if (!string.IsNullOrEmpty(x.Id))- {- var customerGroup = await groupService.GetCustomerGroupById(x.Id);- if (customerGroup.IsSystem && !customerGroup.SystemName.Equals(x.SystemName, StringComparison.OrdinalIgnoreCase))- {- return false;- }- }- return true;- }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.SystemName.CantEditSystem"));- }+ var customerGroup = await groupService.GetCustomerGroupById(x.Id);+ if (customerGroup.IsSystem &&+ !customerGroup.SystemName.Equals(x.SystemName, StringComparison.OrdinalIgnoreCase)) return false;+ }++ return true;+ }).WithMessage(translationService.GetResource("Api.Customers.CustomerGroup.Fields.SystemName.CantEditSystem"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Customers/CustomerValidator.cs b/src/API/Grand.Api/Validators/Customers/CustomerValidator.csindex ce94ec02d..88a175fb0 100644--- a/src/API/Grand.Api/Validators/Customers/CustomerValidator.cs+++ b/src/API/Grand.Api/Validators/Customers/CustomerValidator.cs@@ -7,85 +7,91 @@ using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Customers+namespace Grand.Api.Validators.Customers;++public class CustomerValidator : BaseGrandValidator<CustomerDto>{- public class CustomerValidator : BaseGrandValidator<CustomerDto>+ public CustomerValidator(+ IEnumerable<IValidatorConsumer<CustomerDto>> validators,+ ITranslationService translationService, ICountryService countryService,+ ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings)+ : base(validators){- public CustomerValidator(- IEnumerable<IValidatorConsumer<CustomerDto>> validators,- ITranslationService translationService, ICountryService countryService,- ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings)- : base(validators)+ RuleFor(x => x).MustAsync(async (x, _) =>{+ var customer = await customerService.GetCustomerByEmail(x.Email);+ return customer == null || customer.Id == x.Id;+ }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Email.Registered"));- RuleFor(x => x).MustAsync(async (x, _) =>- {- var customer = await customerService.GetCustomerByEmail(x.Email);- return customer == null || customer.Id == x.Id;- }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Email.Registered"));-- RuleFor(x => x).MustAsync(async (x, _) =>- {- var username = await customerService.GetCustomerByUsername(x.Username);- return username == null || username.Id == x.Id || !customerSettings.UsernamesEnabled;- }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Username.Registered"));+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ var username = await customerService.GetCustomerByUsername(x.Username);+ return username == null || username.Id == x.Id || !customerSettings.UsernamesEnabled;+ }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Username.Registered"));- RuleFor(x => x).MustAsync(async (x, _) =>- {- var customer = await customerService.GetCustomerByGuid(x.CustomerGuid);- return customer == null || customer.Id == x.Id;- }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Guid.Exists"));+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ var customer = await customerService.GetCustomerByGuid(x.CustomerGuid);+ return customer == null || customer.Id == x.Id;+ }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Guid.Exists"));- RuleFor(x => x).MustAsync(async (x, _) =>- {- var store = await storeService.GetStoreById(x.StoreId);- return store != null;- }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.StoreId.NotExists"));+ RuleFor(x => x).MustAsync(async (x, _) =>+ {+ var store = await storeService.GetStoreById(x.StoreId);+ return store != null;+ }).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.StoreId.NotExists"));- //form fields- if (customerSettings.CountryEnabled && customerSettings.CountryRequired)+ //form fields+ if (customerSettings.CountryEnabled && customerSettings.CountryRequired)+ RuleFor(x => x.CountryId)+ .NotEqual("")+ .WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Country.Required"));+ if (customerSettings.CountryEnabled &&+ customerSettings.StateProvinceEnabled &&+ customerSettings.StateProvinceRequired)+ RuleFor(x => x.StateProvinceId).MustAsync(async (x, y, _) =>{- RuleFor(x => x.CountryId)- .NotEqual("")- .WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Country.Required"));- }- if (customerSettings.CountryEnabled &&- customerSettings.StateProvinceEnabled &&- customerSettings.StateProvinceRequired)- {-- RuleFor(x => x.StateProvinceId).MustAsync(async (x, y, _) =>+ var countryId = !string.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";+ var country = await countryService.GetCountryById(countryId);+ if (country != null && country.StateProvinces.Any()){- var countryId = !string.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";- var country = await countryService.GetCountryById(countryId);- if (country != null && country.StateProvinces.Any())- {- //if yes, then ensure that state is selected- if (string.IsNullOrEmpty(y))- {- return false;- }- if (country.StateProvinces.FirstOrDefault(stateProvince => stateProvince.Id == y) != null)- return true;- }- return false;- }).WithMessage(translationService.GetResource("pi.Customers.Customer.Fields.StateProvince.Required"));- }- if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)- RuleFor(x => x.Company).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Company.Required"));- if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)- RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.StreetAddress.Required"));- if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)- RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.StreetAddress2.Required"));- if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)- RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.ZipPostalCode.Required"));- if (customerSettings.CityRequired && customerSettings.CityEnabled)- RuleFor(x => x.City).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.City.Required"));- if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)- RuleFor(x => x.Phone).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Phone.Required"));- if (customerSettings.FaxRequired && customerSettings.FaxEnabled)- RuleFor(x => x.Fax).NotEmpty().WithMessage(translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Fax.Required"));- }+ //if yes, then ensure that state is selected+ if (string.IsNullOrEmpty(y)) return false;+ if (country.StateProvinces.FirstOrDefault(stateProvince => stateProvince.Id == y) != null)+ return true;+ }++ return false;+ }).WithMessage(translationService.GetResource("pi.Customers.Customer.Fields.StateProvince.Required"));+ if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)+ RuleFor(x => x.Company).NotEmpty()+ .WithMessage(+ translationService.GetResource(+ "Api.Customers.Customer.Customers.Customers.Fields.Company.Required"));+ if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)+ RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(+ translationService.GetResource(+ "Api.Customers.Customer.Customers.Customers.Fields.StreetAddress.Required"));+ if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)+ RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(+ translationService.GetResource(+ "Api.Customers.Customer.Customers.Customers.Fields.StreetAddress2.Required"));+ if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)+ RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(+ translationService.GetResource(+ "Api.Customers.Customer.Customers.Customers.Fields.ZipPostalCode.Required"));+ if (customerSettings.CityRequired && customerSettings.CityEnabled)+ RuleFor(x => x.City).NotEmpty()+ .WithMessage(+ translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.City.Required"));+ if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)+ RuleFor(x => x.Phone).NotEmpty()+ .WithMessage(+ translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Phone.Required"));+ if (customerSettings.FaxRequired && customerSettings.FaxEnabled)+ RuleFor(x => x.Fax).NotEmpty()+ .WithMessage(+ translationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Fax.Required"));}-}+}\ No newline at end of filediff --git a/src/API/Grand.Api/Validators/Customers/PasswordValidator.cs b/src/API/Grand.Api/Validators/Customers/PasswordValidator.csindex 462325d8c..8463ef5f1 100644--- a/src/API/Grand.Api/Validators/Customers/PasswordValidator.cs+++ b/src/API/Grand.Api/Validators/Customers/PasswordValidator.cs@@ -4,21 +4,21 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Domain.Customers;using Grand.Infrastructure.Validators;-namespace Grand.Api.Validators.Customers+namespace Grand.Api.Validators.Customers;++public class PasswordValidator : BaseGrandValidator<PasswordDto>{- public class PasswordValidator : BaseGrandValidator<PasswordDto>+ public PasswordValidator(+ IEnumerable<IValidatorConsumer<PasswordDto>> validators,+ ITranslationService translationService,+ CustomerSettings customerSettings)+ : base(validators){- public PasswordValidator(- IEnumerable<IValidatorConsumer<PasswordDto>> validators,- ITranslationService translationService,- CustomerSettings customerSettings)- : base(validators)- {- RuleFor(x => x.Password).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Password.Required"));-- if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))- RuleFor(x => x.Password).Matches(customerSettings.PasswordRegularExpression).WithMessage(string.Format(translationService.GetResource("Account.Fields.Password.Validation")));+ RuleFor(x => x.Password).NotEmpty()+ .WithMessage(translationService.GetResource("Account.Fields.Password.Required"));- }+ if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))+ RuleFor(x => x.Password).Matches(customerSettings.PasswordRegularExpression)+ .WithMessage(string.Format(translationService.GetResource("Account.Fields.Password.Validation")));}-}+}\ No newline at end of file