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
Minor refactoring with add new comments on the news
supportebb1583d27df
diff --git a/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.csindex a35f99f04..1540d6e16 100644--- a/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs@@ -39,8 +39,8 @@ namespace Grand.Web.Commands.Handler.NewsNewsItemId = request.NewsItem.Id,CustomerId = _workContext.CurrentCustomer.Id,StoreId = _workContext.CurrentStore.Id,- CommentTitle = request.Model.AddNewComment.CommentTitle,- CommentText = request.Model.AddNewComment.CommentText,+ CommentTitle = request.Model.CommentTitle,+ CommentText = request.Model.CommentText,CreatedOnUtc = DateTime.UtcNow};request.NewsItem.NewsComments.Add(comment);diff --git a/src/Web/Grand.Web/Commands/Models/News/InsertNewsCommentCommand.cs b/src/Web/Grand.Web/Commands/Models/News/InsertNewsCommentCommand.csindex b71ef8348..c3b26f40d 100644--- a/src/Web/Grand.Web/Commands/Models/News/InsertNewsCommentCommand.cs+++ b/src/Web/Grand.Web/Commands/Models/News/InsertNewsCommentCommand.cs@@ -7,6 +7,6 @@ namespace Grand.Web.Commands.Models.Newspublic class InsertNewsCommentCommand : IRequest<NewsComment>{public NewsItem NewsItem { get; set; }- public NewsItemModel Model { get; set; }+ public AddNewsCommentModel Model { get; set; }}}diff --git a/src/Web/Grand.Web/Controllers/NewsController.cs b/src/Web/Grand.Web/Controllers/NewsController.csindex c12e91239..53a0ad809 100644--- a/src/Web/Grand.Web/Controllers/NewsController.cs+++ b/src/Web/Grand.Web/Controllers/NewsController.cs@@ -1,9 +1,10 @@-using Grand.Business.Core.Extensions;-using Grand.Business.Core.Interfaces.Cms;+using Grand.Business.Core.Interfaces.Cms;+using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Logging;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Customers;using Grand.Domain.News;using Grand.Infrastructure;using Grand.Web.Commands.Models.News;@@ -13,7 +14,9 @@ using Grand.Web.Events;using Grand.Web.Features.Models.News;using Grand.Web.Models.News;using MediatR;+using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.DependencyInjection;namespace Grand.Web.Controllers{@@ -57,6 +60,7 @@ namespace Grand.Web.Controllers#region Methods[HttpGet]+ [ProducesResponseType(typeof(NewsItemListModel), StatusCodes.Status200OK)]public virtual async Task<IActionResult> List(NewsPagingFilteringModel command){if (!_newsSettings.Enabled)@@ -66,6 +70,7 @@ namespace Grand.Web.Controllersreturn View(model);}[HttpGet]+ [ProducesResponseType(typeof(NewsItemModel), StatusCodes.Status200OK)]public virtual async Task<IActionResult> NewsItem(string newsItemId){if (!_newsSettings.Enabled)@@ -91,34 +96,50 @@ namespace Grand.Web.Controllers[HttpPost][AutoValidateAntiforgeryToken][DenySystemAccount]- public virtual async Task<IActionResult> NewsCommentAdd(NewsItemModel model)+ public virtual async Task<IActionResult> NewsCommentAdd(AddNewsCommentModel model){if (!_newsSettings.Enabled)- return RedirectToRoute("HomePage");+ return Json(new+ {+ success = false+ });- var newsItem = await _newsService.GetNewsById(model.NewsItemId);+ var newsItem = await _newsService.GetNewsById(model.Id);if (newsItem is not { Published: true } || !newsItem.AllowComments)- return RedirectToRoute("HomePage");+ return Json(new+ {+ success = false+ });if (ModelState.IsValid){- await _mediator.Send(new InsertNewsCommentCommand { NewsItem = newsItem, Model = model });+ var newsComment = await _mediator.Send(new InsertNewsCommentCommand { NewsItem = newsItem, Model = model });//notification- await _mediator.Publish(new NewsCommentEvent(newsItem, model.AddNewComment));+ await _mediator.Publish(new NewsCommentEvent(newsItem, model));//activity log_ = _customerActivityService.InsertActivity("PublicStore.AddNewsComment", newsItem.Id,_workContext.CurrentCustomer, HttpContext.Connection?.RemoteIpAddress?.ToString(),_translationService.GetResource("ActivityLog.PublicStore.AddNewsComment"));- //The text boxes should be cleared after a comment has been posted- TempData["Grand.news.addcomment.result"] = _translationService.GetResource("News.Comments.SuccessfullyAdded");- return RedirectToRoute("NewsItem", new { SeName = newsItem.GetSeName(_workContext.WorkingLanguage.Id) });+ return Json(new+ {+ success = true,+ message = _translationService.GetResource("News.Comments.SuccessfullyAdded"),+ model = new {+ newsComment.CommentText,+ newsComment.CommentTitle,+ CreatedOn = HttpContext.RequestServices.GetService<IDateTimeService>().ConvertToUserTime(newsComment.CreatedOnUtc, DateTimeKind.Utc),+ CustomerName = _workContext.CurrentCustomer.FormatUserName(HttpContext.RequestServices.GetService<CustomerSettings>().CustomerNameFormat)+ }+ });}-- model = await _mediator.Send(new GetNewsItem { NewsItem = newsItem });- return View("NewsItem", model);+ return Json(new+ {+ success = false,+ message = string.Join(',', ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage)))+ });}#endregion}diff --git a/src/Web/Grand.Web/Models/News/AddNewsCommentModel.cs b/src/Web/Grand.Web/Models/News/AddNewsCommentModel.csindex e23ab2c8c..d0b40707b 100644--- a/src/Web/Grand.Web/Models/News/AddNewsCommentModel.cs+++ b/src/Web/Grand.Web/Models/News/AddNewsCommentModel.cs@@ -5,6 +5,12 @@ namespace Grand.Web.Models.News{public class AddNewsCommentModel : BaseModel{+ public AddNewsCommentModel()+ {+ Captcha = new CaptchaModel();+ }+ public string Id { get; set; }+[GrandResourceDisplayName("News.Comments.CommentTitle")]public string CommentTitle { get; set; }@@ -12,5 +18,6 @@ namespace Grand.Web.Models.Newspublic string CommentText { get; set; }public bool DisplayCaptcha { get; set; }+ public ICaptchaValidModel Captcha { get; set; }}}\ No newline at end of filediff --git a/src/Web/Grand.Web/Models/News/NewsItemModel.cs b/src/Web/Grand.Web/Models/News/NewsItemModel.csindex 165445d1a..4fdb0721c 100644--- a/src/Web/Grand.Web/Models/News/NewsItemModel.cs+++ b/src/Web/Grand.Web/Models/News/NewsItemModel.cs@@ -10,7 +10,6 @@ namespace Grand.Web.Models.NewsComments = new List<NewsCommentModel>();AddNewComment = new AddNewsCommentModel();PictureModel = new PictureModel();- Captcha = new CaptchaModel();}public string NewsItemId { get; set; }public string MetaKeywords { get; set; }@@ -26,6 +25,6 @@ namespace Grand.Web.Models.Newspublic DateTime CreatedOn { get; set; }public IList<NewsCommentModel> Comments { get; set; }public AddNewsCommentModel AddNewComment { get; set; }- public ICaptchaValidModel Captcha { get; set; }+}}\ No newline at end of filediff --git a/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs b/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.csindex f2f6ce364..44461d0a9 100644--- a/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs+++ b/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs@@ -1,7 +1,15 @@using FluentValidation;+using Grand.Business.Core.Interfaces.Cms;+using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.News;+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.News;+using Microsoft.AspNetCore.Http;namespace Grand.Web.Validators.News;@@ -9,10 +17,31 @@ public class AddNewsCommentValidator : BaseGrandValidator<AddNewsCommentModel>{public AddNewsCommentValidator(IEnumerable<IValidatorConsumer<AddNewsCommentModel>> validators,+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,+ IWorkContext workContext, IGroupService groupService, INewsService newsService,+ CaptchaSettings captchaSettings, NewsSettings newsSettings,+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,ITranslationService translationService): base(validators){RuleFor(x => x.CommentTitle).NotEmpty().WithMessage(translationService.GetResource("News.Comments.CommentTitle.Required"));RuleFor(x => x.CommentTitle).Length(1, 200).WithMessage(string.Format(translationService.GetResource("News.Comments.CommentTitle.MaxLengthValidation"), 200));RuleFor(x => x.CommentText).NotEmpty().WithMessage(translationService.GetResource("News.Comments.CommentText.Required"));+ RuleFor(x => x).CustomAsync(async (x, context, _) =>+ {+ if (await groupService.IsGuest(workContext.CurrentCustomer) && !newsSettings.AllowNotRegisteredUsersToLeaveComments)+ {+ context.AddFailure(translationService.GetResource("News.Comments.OnlyRegisteredUsersLeaveComments"));+ }+ var newsItem = await newsService.GetNewsById(x.Id);+ if (newsItem is not { Published: true } || !newsItem.AllowComments)+ context.AddFailure(translationService.GetResource("News.Comments.NotAllowed"));+ });+ if (captchaSettings.Enabled && captchaSettings.ShowOnNewsCommentPage)+ {+ RuleFor(x => x.Captcha).NotNull()+ .WithMessage(translationService.GetResource("Account.Captcha.Required"));+ RuleFor(x => x.Captcha)+ .SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));+ }}}\ No newline at end of filediff --git a/src/Web/Grand.Web/Validators/News/NewsItemValidator.cs b/src/Web/Grand.Web/Validators/News/NewsItemValidator.csdeleted file mode 100644index 3fa4f65e4..000000000--- a/src/Web/Grand.Web/Validators/News/NewsItemValidator.cs+++ /dev/null@@ -1,48 +0,0 @@-using FluentValidation;-using Grand.Business.Core.Interfaces.Cms;-using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Domain.News;-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.News;-using Microsoft.AspNetCore.Http;--namespace Grand.Web.Validators.News-{- public class NewsItemValidator : BaseGrandValidator<NewsItemModel>- {- public NewsItemValidator(- IEnumerable<IValidatorConsumer<NewsItemModel>> validators,- IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,- IWorkContext workContext, IGroupService groupService, INewsService newsService,- CaptchaSettings captchaSettings, NewsSettings newsSettings,- IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,- ITranslationService translationService)- : base(validators)- {- RuleFor(x => x.AddNewComment.CommentTitle).NotEmpty().WithMessage(translationService.GetResource("News.Comments.CommentTitle.Required"));- RuleFor(x => x.AddNewComment.CommentTitle).Length(1, 200).WithMessage(string.Format(translationService.GetResource("News.Comments.CommentTitle.MaxLengthValidation"), 200));- RuleFor(x => x.AddNewComment.CommentText).NotEmpty().WithMessage(translationService.GetResource("News.Comments.CommentText.Required"));- RuleFor(x => x).CustomAsync(async (x, context, _) =>- {- if (await groupService.IsGuest(workContext.CurrentCustomer) && !newsSettings.AllowNotRegisteredUsersToLeaveComments)- {- context.AddFailure(translationService.GetResource("News.Comments.OnlyRegisteredUsersLeaveComments"));- }- var newsItem = await newsService.GetNewsById(x.NewsItemId);- if (newsItem is not { Published: true } || !newsItem.AllowComments)- context.AddFailure(translationService.GetResource("News.Comments.NotAllowed"));- });- if (captchaSettings.Enabled && captchaSettings.ShowOnNewsCommentPage)- {- RuleFor(x => x.Captcha).NotNull()- .WithMessage(translationService.GetResource("Account.Captcha.Required"));- RuleFor(x => x.Captcha)- .SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));- }- }}-}\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml b/src/Web/Grand.Web/Views/Blog/BlogPost.cshtmlindex 0eb95a414..9195c5899 100644--- a/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml+++ b/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml@@ -61,16 +61,6 @@{<div class="fieldset new-comment generalMarginSupporter" id="comments"><h4 class="generalTitle generalMarginSupporter">@Loc["Blog.Comments.LeaveYourComment"]</h4>- <div class="notifications">- <div asp-validation-summary="All" class="message-error"></div>- @{- var result = TempData["Grand.blog.addcomment.result"] as string;- }- @if (!string.IsNullOrEmpty(result))- {- <div class="result alert alert-info">@result</div>- }- </div><validation-observer v-slot="{ handleSubmit }"><form id="addBlogComment" asp-controller="Blog" asp-action="BlogPost" asp-route-id="@Model.Id" method="post" v-on:submit.prevent="handleSubmit(blog.submitBlogComment)"><input type="hidden" name="Id" value="@Model.Id"/>diff --git a/src/Web/Grand.Web/Views/News/NewsItem.cshtml b/src/Web/Grand.Web/Views/News/NewsItem.cshtmlindex bad155837..4ea6806bb 100644--- a/src/Web/Grand.Web/Views/News/NewsItem.cshtml+++ b/src/Web/Grand.Web/Views/News/NewsItem.cshtml@@ -31,89 +31,115 @@@if (Model.AllowComments){<fieldset class="new-comment py-3 px-0" id="comments">- <h5><strong>@Loc["News.Comments.LeaveYourComment"]</strong></h5>- <div class="notifications">- <div asp-validation-summary="All" class="message-error"></div>- @{- var result = TempData["Grand.news.addcomment.result"] as string;- }- @if (!string.IsNullOrEmpty(result))- {- <div class="result alert alert-info">@result</div>- }- </div>+ <h5>+ <strong>@Loc["News.Comments.LeaveYourComment"]</strong>+ </h5><validation-observer v-slot="{ handleSubmit }">- <form asp-action="NewsCommentAdd" asp-controller="News" asp-route-sename="@Model.SeName" method="post" ref="form" v-on:submit.prevent="handleSubmit(formSubmit)">- <input type="hidden" name="newsItemId" value="@Model.Id" />+ <form id="addNewsComment" asp-action="NewsCommentAdd" asp-controller="News" method="post" v-on:submit.prevent="handleSubmit(news.submitNewsComment)">+ <input type="hidden" name="Id" value="@Model.Id"/><fieldset class="form-group">- <validation-provider tag="div" rules="required" name="AddNewComment.CommentTitle" v-slot="{ errors, classes }">- <label asp-for="AddNewComment.CommentTitle" class="col-form-label">@Loc["News.Comments.CommentTitle"]:</label>+ <validation-provider tag="div" rules="required" name="CommentTitle" v-slot="{ errors, classes }">+ <label for="CommentTitle" class="col-form-label">@Loc["News.Comments.CommentTitle"]:</label><span class="required">*</span>- <input asp-for="AddNewComment.CommentTitle" v-bind:class="[classes , 'form-control enter-comment-title']" v-model="news.CommentTitle" />+ <input name="CommentTitle" v-bind:class="[classes , 'form-control enter-comment-title']"+ data-val-required="@Loc["News.Comments.CommentTitle.Required"]"+ v-model="news.CommentTitle"/><span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="AddNewComment.CommentTitle"></span></validation-provider></fieldset><fieldset class="form-group">- <validation-provider tag="div" rules="required" name="AddNewComment.CommentText" v-slot="{ errors, classes }">- <label asp-for="AddNewComment.CommentText" class="col-form-label">@Loc["News.Comments.CommentText"]:</label>+ <validation-provider tag="div" rules="required" name="CommentText" v-slot="{ errors, classes }">+ <label for="CommentText" class="col-form-label">@Loc["News.Comments.CommentText"]:</label><span class="required">*</span>- <textarea asp-for="AddNewComment.CommentText" v-model="news.CommentText" v-bind:class="[classes , 'form-control']" autofocus="autofocus" rows="4"></textarea>+ <textarea name="CommentText" v-model="news.CommentText"+ data-val-required="@Loc["News.Comments.CommentText.Required"]"+ v-bind:class="[classes , 'form-control']" autofocus="autofocus" rows="4"></textarea><span class="field-validation-error">{{ errors[0] }}</span>- <span asp-validation-for="AddNewComment.CommentText"></span></validation-provider></fieldset>@if (Model.AddNewComment.DisplayCaptcha){<div class="captcha-box">- <captcha />+ <captcha/></div>}<div class="buttons text-xs-center text-md-left generalMarginSupporter">- <input type="submit" name="add-comment" class="btn btn-info news-item-add-comment-button" value="@Loc["News.Comments.SubmitButton"]" />+ <input type="submit" name="add-comment" class="btn btn-info news-item-add-comment-button" value="@Loc["News.Comments.SubmitButton"]"/></div></form></validation-observer></fieldset><script asp-location="Footer" asp-order="300">var news = new Vue({- data: () => ({- @{- <text>- CommentTitle: '',- CommentText: '',- </text>+ data: () => {+ return {+ Model: null,+ CommentTitle: '',+ CommentText: ''+ }+ },+ created() {+ this.Model = @Json.Serialize(Model.Comments);+ },+ methods: {+ submitNewsComment() {+ var form = document.getElementById("addNewsComment");+ var url = form.getAttribute("action");+ var bodyFormData = new FormData(form);+ axios({+ url: url,+ data: bodyFormData,+ method: 'post',+ headers: {+ 'Accept': 'application/json'+ }+ }).then(function (response) {+ if (response.data.success == true){+ news.CommentTitle = ' ';+ news.CommentText = ' ';+ vm.displayBarNotification(response.data.message, '', 'success', 3000);+ if (response.data.model){+ news.addComment(response.data.model)+ }+ } else {+ vm.displayBarNotification(response.data.message, '', 'error', 3500);+ }+ })+ },+ addComment(model) {+ // Add object item to array+ this.Model.push(model);}- })+ }});</script>- if (Model.Comments.Any())- {+ <template v-if="news.Model.length > 0"><div class="comment-list">- <h4 class="generalTitle generalMarginSupporter"><strong>@Loc["News.Comments"]</strong></h4>+ <h4 class="generalTitle generalMarginSupporter">+ <strong>@Loc["News.Comments"]</strong>+ </h4><div class="comments">- @foreach (var comment in Model.Comments)- {+ <template v-for="comment in news.Model"><div class="card mb-3"><div class="card-header"><div class="d-inline-flex w-100">- <h6 class="mb-0">@comment.CustomerName</h6>+ <h6 class="mb-0">{{comment.CustomerName}}</h6><b-icon icon="calendar2-check" variant="info" class="mx-2"></b-icon><small class="date text-muted"><span>@Loc["News.Comments.CreatedOn"]:</span>- <span>@comment.CreatedOn.ToString("g")</span>+ <span>{{new Date( comment.CreatedOn).toDateString()}}</span></small></div></div><div class="card-body">- <h5>@comment.CommentTitle</h5>- @comment.CommentText+ <h5>{{comment.CommentTitle}}</h5>+ {{comment.CommentText}}</div></div>- }+ </template></div></div>- }+ </template>}@await Component.InvokeAsync("Widget", new { widgetZone = "newsitem_page_after_comments", additionalData = Model.Id })</div>\ No newline at end of file