Skip to content

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.

ProductController - move validator logic from Controller to Validator

supportf5d2bb01747e
diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.cs
index 52cdde7ea..e621659a5 100644
--- a/src/Web/Grand.Web/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web/Controllers/ProductController.cs
@@ -40,7 +40,6 @@ namespace Grand.Web.Controllers
private readonly ICustomerActivityService _customerActivityService;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
- private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly CaptchaSettings _captchaSettings;
#endregion
@@ -58,7 +57,6 @@ namespace Grand.Web.Controllers
ICustomerActivityService customerActivityService,
IMediator mediator,
CatalogSettings catalogSettings,
- ShoppingCartSettings shoppingCartSettings,
CaptchaSettings captchaSettings
)
{
@@ -72,7 +70,6 @@ namespace Grand.Web.Controllers
_customerActivityService = customerActivityService;
_mediator = mediator;
_catalogSettings = catalogSettings;
- _shoppingCartSettings = shoppingCartSettings;
_captchaSettings = captchaSettings;
}
@@ -80,7 +77,7 @@ namespace Grand.Web.Controllers
#region Product details page
- public virtual async Task<IActionResult> ProductDetails(string productId, string updatecartitemid = "")
+ public virtual async Task<IActionResult> ProductDetails(string productId)
{
var product = await _productService.GetProductById(productId);
if (product == null)
@@ -116,31 +113,12 @@ namespace Grand.Web.Controllers
var parentGroupedProduct = await _productService.GetProductById(product.ParentGroupedProductId);
return parentGroupedProduct == null ? RedirectToRoute("HomePage") : RedirectToRoute("Product", new { SeName = parentGroupedProduct.GetSeName(_workContext.WorkingLanguage.Id) });
}
- //update existing shopping cart item?
- ShoppingCartItem updatecartitem = null;
- if (_shoppingCartSettings.AllowCartItemEditing && !string.IsNullOrEmpty(updatecartitemid))
- {
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id);
-
- updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);
- //not found?
- if (updatecartitem == null)
- {
- return RedirectToRoute("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) });
- }
- //is it this product?
- if (product.Id != updatecartitem.ProductId)
- {
- return RedirectToRoute("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) });
- }
- }
-
+
//prepare the model
var model = await _mediator.Send(new GetProductDetailsPage {
Store = _workContext.CurrentStore,
Product = product,
- IsAssociatedProduct = false,
- UpdateCartItem = updatecartitem
+ IsAssociatedProduct = false
});
//product layout
@@ -172,7 +150,7 @@ namespace Grand.Web.Controllers
//handle product attribute selection event. this way we return new price, overridden gtin/sku/mpn
//currently we use this method on the product details pages
[HttpPost]
- public virtual async Task<IActionResult> ProductDetails_AttributeChange(ProductModel model, bool loadPicture)
+ public virtual async Task<IActionResult> ProductDetails_AttributeChange(ProductModel model)
{
var product = await _productService.GetProductById(model.ProductId);
if (product == null)
@@ -182,8 +160,7 @@ namespace Grand.Web.Controllers
Currency = _workContext.WorkingCurrency,
Customer = _workContext.CurrentCustomer,
Store = _workContext.CurrentStore,
- Model = model,
- LoadPicture = loadPicture,
+ Model = model,
Product = product
});
@@ -205,15 +182,14 @@ namespace Grand.Web.Controllers
}
//handle product warehouse selection event. this way we return stock
- //currently we use this method on the product details pages
[HttpPost]
- public virtual async Task<IActionResult> ProductDetails_WarehouseChange(string productId, string warehouseId, [FromServices] IStockQuantityService stockQuantityService)
+ public virtual async Task<IActionResult> ProductDetails_WarehouseChange(ProductModel model, [FromServices] IStockQuantityService stockQuantityService)
{
- var product = await _productService.GetProductById(productId);
+ var product = await _productService.GetProductById(model.ProductId);
if (product == null)
return new JsonResult("");
- var stock = stockQuantityService.FormatStockMessage(product, warehouseId, null);
+ var stock = stockQuantityService.FormatStockMessage(product, model.WarehouseId, null);
return Json(new
{
stockAvailability = stock
@@ -496,42 +472,14 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- [ValidateCaptcha]
[DenySystemAccount]
public virtual async Task<IActionResult> ProductReviews(
- ProductReviewsModel model,
- [FromServices] IGroupService groupService,
- [FromServices] IOrderService orderService,
- [FromServices] IProductReviewService productReviewService)
+ ProductReviewsModel model)
{
var product = await _productService.GetProductById(model.ProductId);
if (product is not { Published: true } || !product.AllowCustomerReviews)
return Content("");
- //validate CAPTCHA
- if (_captchaSettings.Enabled && _captchaSettings.ShowOnProductReviewPage && !model.CaptchaValid)
- {
- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));
- }
-
- if (await groupService.IsGuest(_workContext.CurrentCustomer) && !_catalogSettings.AllowAnonymousUsersToReviewProduct)
- {
- ModelState.AddModelError("", _translationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"));
- }
-
- if (_catalogSettings.ProductReviewPossibleOnlyAfterPurchasing &&
- !(await orderService.SearchOrders(customerId: _workContext.CurrentCustomer.Id, productId: model.ProductId, os: (int)OrderStatusSystem.Complete)).Any())
- ModelState.AddModelError(string.Empty, _translationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"));
-
- if (_catalogSettings.ProductReviewPossibleOnlyOnce)
- {
- var reviews = await productReviewService.GetAllProductReviews(customerId: _workContext.CurrentCustomer.Id,
- productId: model.ProductId,
- pageSize: 1);
- if (reviews.Any())
- ModelState.AddModelError(string.Empty, _translationService.GetResource("Reviews.ProductReviewPossibleOnlyOnce"));
- }
-
if (ModelState.IsValid)
{
var productReview = await _mediator.Send(new InsertProductReviewCommand {
@@ -671,30 +619,15 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- [ValidateCaptcha]
[DenySystemAccount]
- public virtual async Task<IActionResult> ProductEmailAFriend(ProductEmailAFriendModel model, bool captchaValid,
- [FromServices] IGroupService groupService)
+ public virtual async Task<IActionResult> ProductEmailAFriend(ProductEmailAFriendModel model)
{
var product = await _productService.GetProductById(model.ProductId);
if (product is not { Published: true } || !_catalogSettings.EmailAFriendEnabled)
return Content("");
- //validate CAPTCHA
- if (_captchaSettings.Enabled && _captchaSettings.ShowOnEmailProductToFriendPage && !captchaValid)
- {
- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));
- }
-
- //check whether the current customer is guest and ia allowed to email a friend
- if (await groupService.IsGuest(_workContext.CurrentCustomer) && !_catalogSettings.AllowAnonymousUsersToEmailAFriend)
- {
- ModelState.AddModelError("", _translationService.GetResource("Products.EmailAFriend.OnlyRegisteredUsers"));
- }
-
if (ModelState.IsValid)
{
- //email
await _mediator.Send(new SendProductEmailAFriendMessageCommand {
Customer = _workContext.CurrentCustomer,
Product = product,
@@ -730,9 +663,8 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- [ValidateCaptcha]
[DenySystemAccount]
- public virtual async Task<IActionResult> AskQuestionOnProduct(ProductAskQuestionSimpleModel model, bool captchaValid)
+ public virtual async Task<IActionResult> AskQuestionOnProduct(ProductAskQuestionSimpleModel model)
{
var product = await _productService.GetProductById(model.Id);
if (product is not { Published: true } || !_catalogSettings.AskQuestionOnProduct)
@@ -742,22 +674,13 @@ namespace Grand.Web.Controllers
message = "Product not found"
});
- // validate CAPTCHA
- if (_captchaSettings.Enabled && _captchaSettings.ShowOnAskQuestionPage && !captchaValid)
- {
- return Json(new
- {
- success = false,
- message = _captchaSettings.GetWrongCaptchaMessage(_translationService)
- });
- }
-
if (!ModelState.IsValid)
return Json(new {
success = false,
message = string.Join(",", ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage))
});
+
var productaskqestionmodel = new ProductAskQuestionModel {
Email = model.AskQuestionEmail,
FullName = model.AskQuestionFullName,
diff --git a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs
index 24886191a..902d92ac2 100644
--- a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs
+++ b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs
@@ -296,7 +296,7 @@ namespace Grand.Web.Endpoints
//product email a friend
endpointRouteBuilder.MapControllerRoute("ProductEmailAFriend",
- pattern + "productemailafriend/{productId?}",
+ pattern + "productemailafriend",
new { controller = "Product", action = "ProductEmailAFriend" });
//product ask question on product page
@@ -306,7 +306,7 @@ namespace Grand.Web.Endpoints
//reviews
endpointRouteBuilder.MapControllerRoute("ProductReviews",
- pattern + "productreviews/{productId}",
+ pattern + "productreviews",
new { controller = "Product", action = "ProductReviews" });
//set review helpfulness (AJAX link)
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs
index 8098e7b65..d1e92191d 100644
--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs
@@ -155,7 +155,7 @@ namespace Grand.Web.Features.Handlers.Products
}
//picture. used when we want to override a default product picture when some attribute is selected
- if (!request.LoadPicture) return model;
+ if (!request.Model.LoadPicture) return model;
//first, try to get product attribute combination picture
var pictureId = request.Product.FindProductAttributeCombination(customAttributes)?.PictureId;
diff --git a/src/Web/Grand.Web/Features/Models/Products/GetProductDetailsAttributeChange.cs b/src/Web/Grand.Web/Features/Models/Products/GetProductDetailsAttributeChange.cs
index 718931d21..ecf925de0 100644
--- a/src/Web/Grand.Web/Features/Models/Products/GetProductDetailsAttributeChange.cs
+++ b/src/Web/Grand.Web/Features/Models/Products/GetProductDetailsAttributeChange.cs
@@ -13,7 +13,6 @@ namespace Grand.Web.Features.Models.Products
public Currency Currency { get; set; }
public Store Store { get; set; }
public Product Product { get; set; }
- public bool LoadPicture { get; set; }
public ProductModel Model { get; set; }
}
}
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductAskQuestionSimpleModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductAskQuestionSimpleModel.cs
index d34c96a41..fe6aca608 100644
--- a/src/Web/Grand.Web/Models/Catalog/ProductAskQuestionSimpleModel.cs
+++ b/src/Web/Grand.Web/Models/Catalog/ProductAskQuestionSimpleModel.cs
@@ -1,10 +1,12 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
+using Grand.Web.Models.Common;
namespace Grand.Web.Models.Catalog
{
public class ProductAskQuestionSimpleModel : BaseEntityModel
{
+
[GrandResourceDisplayName("Products.AskQuestion.Email")]
public string AskQuestionEmail { get; set; }
@@ -18,6 +20,7 @@ namespace Grand.Web.Models.Catalog
public string AskQuestionMessage { get; set; }
public bool DisplayCaptcha { get; set; }
+ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductEmailAFriendModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductEmailAFriendModel.cs
index a25bef613..6af046816 100644
--- a/src/Web/Grand.Web/Models/Catalog/ProductEmailAFriendModel.cs
+++ b/src/Web/Grand.Web/Models/Catalog/ProductEmailAFriendModel.cs
@@ -1,5 +1,6 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
+using Grand.Web.Models.Common;
namespace Grand.Web.Models.Catalog
{
@@ -24,5 +25,6 @@ namespace Grand.Web.Models.Catalog
public string Result { get; set; }
public bool DisplayCaptcha { get; set; }
+ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductModel.cs
index 019b32135..35498e114 100644
--- a/src/Web/Grand.Web/Models/Catalog/ProductModel.cs
+++ b/src/Web/Grand.Web/Models/Catalog/ProductModel.cs
@@ -10,7 +10,7 @@ public class ProductModel
public string WarehouseId { get; set; }
public string ReservationDatepickerFrom { get; set; }
public string ReservationDatepickerTo { get; set; }
-
+ public bool LoadPicture { get; set; }
[ModelBinder(BinderType = typeof(CustomAttributesBinder))]
public IList<CustomAttributeModel> Attributes { get; set; }
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductReviewModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductReviewModel.cs
index ef107e274..4f1646a94 100644
--- a/src/Web/Grand.Web/Models/Catalog/ProductReviewModel.cs
+++ b/src/Web/Grand.Web/Models/Catalog/ProductReviewModel.cs
@@ -1,5 +1,6 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
+using Grand.Web.Models.Common;
namespace Grand.Web.Models.Catalog
{
@@ -24,6 +25,7 @@ namespace Grand.Web.Models.Catalog
public string ProductId { get; set; }
public bool CaptchaValid { get; set; }
+ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();
public string ProductName { get; set; }
public string ProductSeName { get; set; }
diff --git a/src/Web/Grand.Web/Validators/Catalog/ProductAskQuestionSimpleValidator.cs b/src/Web/Grand.Web/Validators/Catalog/ProductAskQuestionSimpleValidator.cs
index f7e880e2b..ed2d53a18 100644
--- a/src/Web/Grand.Web/Validators/Catalog/ProductAskQuestionSimpleValidator.cs
+++ b/src/Web/Grand.Web/Validators/Catalog/ProductAskQuestionSimpleValidator.cs
@@ -1,7 +1,15 @@
using FluentValidation;
+using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Models;
using Grand.Infrastructure.Validators;
+using Grand.Web.Common.Security.Captcha;
+using Grand.Web.Common.Validators;
using Grand.Web.Models.Catalog;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Validators.Catalog
{
@@ -9,6 +17,10 @@ namespace Grand.Web.Validators.Catalog
{
public ProductAskQuestionSimpleValidator(
IEnumerable<IValidatorConsumer<ProductAskQuestionSimpleModel>> validators,
+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
+ CaptchaSettings captchaSettings, CatalogSettings catalogSettings,
+ IProductService productService,
+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
: base(validators)
{
@@ -16,6 +28,19 @@ namespace Grand.Web.Validators.Catalog
RuleFor(x => x.AskQuestionEmail).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
RuleFor(x => x.AskQuestionMessage).NotEmpty().WithMessage(translationService.GetResource("Products.AskQuestion.Message.Required"));
RuleFor(x => x.AskQuestionFullName).NotEmpty().WithMessage(translationService.GetResource("Products.AskQuestion.FullName.Required"));
+
+ if (captchaSettings.Enabled && captchaSettings.ShowOnAskQuestionPage)
+ {
+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));;
+ RuleFor(x => x.Captcha).SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));
+ }
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var product = await productService.GetProductById(x.Id);
+ if (product is not { Published: true } || !catalogSettings.AskQuestionOnProduct)
+ context.AddFailure("Product is disabled");
+
+ });
}
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs b/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
index 240574ff7..e5f650f5f 100644
--- a/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
+++ b/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
@@ -1,7 +1,15 @@
using FluentValidation;
+using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Models;
using Grand.Infrastructure.Validators;
+using Grand.Web.Common.Security.Captcha;
+using Grand.Web.Common.Validators;
using Grand.Web.Models.Catalog;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Validators.Catalog
{
@@ -9,6 +17,10 @@ namespace Grand.Web.Validators.Catalog
{
public ProductEmailAFriendValidator(
IEnumerable<IValidatorConsumer<ProductEmailAFriendModel>> validators,
+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
+ CaptchaSettings captchaSettings, CatalogSettings catalogSettings,
+ IWorkContext workContext, IGroupService groupService, IProductService productService,
+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
: base(validators)
{
@@ -17,5 +29,23 @@ namespace Grand.Web.Validators.Catalog
RuleFor(x => x.YourEmailAddress).NotEmpty().WithMessage(translationService.GetResource("Products.EmailAFriend.YourEmailAddress.Required"));
RuleFor(x => x.YourEmailAddress).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
+
+ if (captchaSettings.Enabled && captchaSettings.ShowOnEmailProductToFriendPage)
+ {
+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));;
+ RuleFor(x => x.Captcha).SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));
+ }
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var product = await productService.GetProductById(x.ProductId);
+ if (product is not { Published: true } || !catalogSettings.EmailAFriendEnabled)
+ context.AddFailure("Product is disabled");
+
+ if (await groupService.IsGuest(workContext.CurrentCustomer) && !catalogSettings.AllowAnonymousUsersToEmailAFriend)
+ {
+ context.AddFailure(translationService.GetResource("Products.EmailAFriend.OnlyRegisteredUsers"));
+ }
+ });
+
}}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs b/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
index 4276344bd..66c73ddcd 100644
--- a/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
+++ b/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
@@ -1,13 +1,24 @@
using FluentValidation;
+using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Catalog;
+using Grand.Domain.Orders;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Models;
using Grand.Infrastructure.Validators;
+using Grand.Web.Common.Security.Captcha;
+using Grand.Web.Common.Validators;
+using Grand.Web.Features.Models.Customers;
using Grand.Web.Models.Catalog;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Validators.Catalog
{
- public class ProductReviewsValidator : BaseGrandValidator<AddProductReviewModel>
+ public class AddProductReviewValidator : BaseGrandValidator<AddProductReviewModel>
{
- public ProductReviewsValidator(
+ public AddProductReviewValidator(
IEnumerable<IValidatorConsumer<AddProductReviewModel>> validators,
ITranslationService translationService)
: base(validators)
@@ -17,4 +28,55 @@ namespace Grand.Web.Validators.Catalog
RuleFor(x => x.ReviewText).NotEmpty().WithMessage(translationService.GetResource("Reviews.Fields.ReviewText.Required"));
}
}
+ public class ProductReviewsValidator : BaseGrandValidator<ProductReviewsModel>
+ {
+ public ProductReviewsValidator(
+ IEnumerable<IValidatorConsumer<ProductReviewsModel>> validators,
+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
+ IGroupService groupService, IProductService productService,
+ IOrderService orderService,
+ IProductReviewService productReviewService,
+ CaptchaSettings captchaSettings, CatalogSettings catalogSettings,
+ IWorkContext workContext,
+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
+ ITranslationService translationService)
+ : base(validators)
+ {
+ RuleFor(x => x.AddProductReview.Title).NotEmpty().WithMessage(translationService.GetResource("Reviews.Fields.Title.Required"));
+ RuleFor(x => x.AddProductReview.Title).Length(1, 200).WithMessage(string.Format(translationService.GetResource("Reviews.Fields.Title.MaxLengthValidation"), 200));
+ RuleFor(x => x.AddProductReview.ReviewText).NotEmpty().WithMessage(translationService.GetResource("Reviews.Fields.ReviewText.Required"));
+
+ if (captchaSettings.Enabled && captchaSettings.ShowOnProductReviewPage)
+ {
+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));;
+ RuleFor(x => x.Captcha).SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));
+ }
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var product = await productService.GetProductById(x.ProductId);
+ if (product is not { Published: true } || !product.AllowCustomerReviews)
+ context.AddFailure("Product is disabled");
+
+ if (await groupService.IsGuest(workContext.CurrentCustomer) && !catalogSettings.AllowAnonymousUsersToReviewProduct)
+ {
+ context.AddFailure(translationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"));
+ }
+
+ if (catalogSettings.ProductReviewPossibleOnlyAfterPurchasing &&
+ !(await orderService.SearchOrders(customerId: workContext.CurrentCustomer.Id, productId: x.ProductId, os: (int)OrderStatusSystem.Complete)).Any())
+ context.AddFailure(translationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"));
+
+ if (catalogSettings.ProductReviewPossibleOnlyOnce)
+ {
+ var reviews = await productReviewService.GetAllProductReviews(customerId: workContext.CurrentCustomer.Id,
+ productId: x.ProductId,
+ pageSize: 1);
+ if (reviews.Any())
+ context.AddFailure(translationService.GetResource("Reviews.ProductReviewPossibleOnlyOnce"));
+ }
+
+ });
+
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Views/Product/Components/ProductEmailAFriend/Default.cshtml b/src/Web/Grand.Web/Views/Product/Components/ProductEmailAFriend/Default.cshtml
index 5aedc79f7..7f10ea82b 100644
--- a/src/Web/Grand.Web/Views/Product/Components/ProductEmailAFriend/Default.cshtml
+++ b/src/Web/Grand.Web/Views/Product/Components/ProductEmailAFriend/Default.cshtml
@@ -25,6 +25,7 @@
<validation-observer ref="ProductEmailAFriendObserver">
<form asp-route="ProductEmailAFriend" id="ProductEmailAFriend" method="post" ref="form" v-on:submit.prevent="formSubmitParam($event, vm.$refs.ProductEmailAFriendObserver)">
<div asp-validation-summary="ModelOnly" class="message-error"></div>
+ <input type="hidden" name="productId" value="@Model.ProductId"/>
<div class="form-fields">
<div class="form-group">
<validation-provider tag="div" rules="required|email" name="FriendEmail" v-slot="{ errors, classes }">
@@ -56,7 +57,7 @@
}
</div>
<div class="btn-group">
- <input type="submit" name="send-email" class="btn btn-info send-email-a-friend-button" data-form="emailafriend.submitEmailAFriend('@Url.RouteUrl("ProductEmailAFriend", new { productId = Model.ProductId })')" value="@Loc["Products.EmailAFriend.Button"]" />
+ <input type="submit" name="send-email" class="btn btn-info send-email-a-friend-button" data-form="emailafriend.submitEmailAFriend('@Url.RouteUrl("ProductEmailAFriend")')" value="@Loc["Products.EmailAFriend.Button"]" />
</div>
</form>
</validation-observer>
@@ -102,10 +103,10 @@
data: bodyFormData,
method: 'post',
headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
+ 'Accept': 'application/json'
}
}).then(function (response) {
+ console.log(response);
emailafriend.Message.Result = response.data.Result;
emailafriend.Message.SuccessfullySent = response.data.SuccessfullySent;
diff --git a/src/Web/Grand.Web/Views/Product/Components/ProductReviews/Partials/ProductReview.Modal.cshtml b/src/Web/Grand.Web/Views/Product/Components/ProductReviews/Partials/ProductReview.Modal.cshtml
index f8808ae73..c41c6266d 100644
--- a/src/Web/Grand.Web/Views/Product/Components/ProductReviews/Partials/ProductReview.Modal.cshtml
+++ b/src/Web/Grand.Web/Views/Product/Components/ProductReviews/Partials/ProductReview.Modal.cshtml
@@ -12,7 +12,7 @@
<div class="write-review" id="review-form">
<h5 class="generalTitle"><strong>@Loc["Reviews.Write"]</strong></h5>
<validation-observer v-slot="{ handleSubmit }">
- <form id="addReviewForm" asp-route="ProductReviews" asp-route-ProductId="@Model.ProductId" method="post" ref="modalForm"
+ <form id="addReviewForm" asp-route="ProductReviews" method="post" ref="modalForm"
v-on:submit.prevent="handleSubmit(productreviews.submitProductReview)" :data-title="'@Loc["Reviews.ProductReviewsFor"] ' + productreviews.Model.ProductName">
<input type="hidden" asp-for="@Model.ProductId" />
<div asp-validation-summary="ModelOnly" class="message-error alert alert-danger my-3"></div>
diff --git a/src/Web/Grand.Web/Views/Product/Partials/Warehouses.cshtml b/src/Web/Grand.Web/Views/Product/Partials/Warehouses.cshtml
index 14258157a..b8b6b0258 100644
--- a/src/Web/Grand.Web/Views/Product/Partials/Warehouses.cshtml
+++ b/src/Web/Grand.Web/Views/Product/Partials/Warehouses.cshtml
@@ -26,12 +26,12 @@
{
<script asp-location="Footer" asp-order="300">
function warehouse_change_handler() {
- var bodyFormData = new FormData();
- bodyFormData.append('warehouseId', document.getElementById('WarehouseId').value);
+ var data = new FormData();
+ data.append('warehouseId', document.getElementById('WarehouseId').value);
+ data.append('productId', '@Model.Id');
axios({
- url: '@Html.Raw(Url.Action("productdetails_warehousechange", "product", new { productId = Model.Id }))',
- data: bodyFormData,
- params: { product: '@Model.Id' },
+ url: '@Html.Raw(Url.Action("productdetails_warehousechange", "product"))',
+ data: data,
method: 'post',
}).then(function (response) {
if (response.data.stockAvailability) {
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/QuickView/Warehouses.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/QuickView/Warehouses.cshtml
index 776f37f96..b2179d39e 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/QuickView/Warehouses.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/QuickView/Warehouses.cshtml
@@ -6,7 +6,7 @@
<div class="mb-3">
<label for="warehouseId" class="col-form-label">@Loc["Products.Warehouse"]:</label>
<template v-if="PopupQuickViewVueModal.ProductAttributes.length > 0">
- <select class="custom-select form-control" name="WarehouseId" id="WarehouseId" @@change="vm.attrchange(PopupQuickViewVueModal.Id)">
+ <select class="custom-select form-control" name="WarehouseId" id="WarehouseId" @@change="vm.warehouse_change_handler(PopupQuickViewVueModal.Id)">
<template v-for="warehouse in PopupQuickViewVueModal.ProductWarehouses">
<option :selected="warehouse.Selected" :value="warehouse.WarehouseId">{{warehouse.Name}}</option>
</template>
diff --git a/src/Web/Grand.Web/wwwroot/theme/script/app.js b/src/Web/Grand.Web/wwwroot/theme/script/app.js
index e4e8fb6c2..b92a77da7 100644
--- a/src/Web/Grand.Web/wwwroot/theme/script/app.js
+++ b/src/Web/Grand.Web/wwwroot/theme/script/app.js
@@ -416,9 +416,6 @@ var vm = new Vue({
if (response.data.stockAvailability) {
vm.PopupQuickViewVueModal.StockAvailability = response.data.stockAvailability;
}
- if (response.data.buttonTextOutOfStockSubscription) {
- PopupQuickViewVueModal.StockAvailability = response.data.stockAvailability;
- }
if (response.data.enabledattributemappingids) {
for (var i = 0; i < response.data.enabledattributemappingids.length; i++) {
document.querySelector('#product_attribute_label_' + response.data.enabledattributemappingids[i]).style.display = "table-cell";
@@ -493,7 +490,6 @@ var vm = new Vue({
}
},
getLinkedProductsQV: function (id) {
- var data = { productId: id };
axios({
url: '/Product/RelatedProducts',
method: 'get',
@@ -507,17 +503,13 @@ var vm = new Vue({
});
},
warehouse_change_handler(id, url) {
- var whId = document.getElementById('WarehouseId').value;
- var data = { warehouseId: whId }
+ var data = new FormData();
+ data.append('warehouseId', document.getElementById('WarehouseId').value);
+ data.append('productId', id);
axios({
- url: url + '?productId=' + id,
- data: JSON.stringify(data),
- params: { product: id },
- method: 'post',
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- }
+ url: url,
+ data: data,
+ method: 'post'
}).then(function (response) {
if (response.data.stockAvailability) {
vm.PopupQuickViewVueModal.StockAvailability = response.data.stockAvailability;