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 changes with ProductService
support5e59d69e86e5
diff --git a/src/Business/Grand.Business.Catalog/Commands/UpdateIntervalPropertiesCommandHandler.cs b/src/Business/Grand.Business.Catalog/Commands/UpdateIntervalPropertiesCommandHandler.csdeleted file mode 100644index 4c2bb863d..000000000--- a/src/Business/Grand.Business.Catalog/Commands/UpdateIntervalPropertiesCommandHandler.cs+++ /dev/null@@ -1,39 +0,0 @@-using Grand.Business.Core.Commands.Catalog;-using Grand.Domain.Catalog;-using Grand.Domain.Data;-using Grand.Infrastructure.Caching;-using Grand.Infrastructure.Caching.Constants;-using MediatR;--namespace Grand.Business.Catalog.Commands.Handlers-{- public class UpdateIntervalPropertiesCommandHandler : IRequestHandler<UpdateIntervalPropertiesCommand, bool>- {- private readonly IRepository<Product> _productRepository;- private readonly ICacheBase _cacheBase;-- public UpdateIntervalPropertiesCommandHandler(IRepository<Product> productRepository, ICacheBase cacheBase)- {- _productRepository = productRepository;- _cacheBase = cacheBase;- }-- public async Task<bool> Handle(UpdateIntervalPropertiesCommand request, CancellationToken cancellationToken)- {- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));-- var update = UpdateBuilder<Product>.Create()- .Set(x => x.Interval, request.Interval)- .Set(x => x.IntervalUnitId, request.IntervalUnit)- .Set(x => x.IncBothDate, request.IncludeBothDates);-- await _productRepository.UpdateOneAsync(x => x.Id == request.Product.Id, update);-- //cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, request.Product.Id));-- return true;- }- }-}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.csindex 09d84111f..891956e48 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs@@ -12,6 +12,7 @@ using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;using MediatR;+using System.Linq.Expressions;namespace Grand.Business.Catalog.Services.Products{@@ -97,7 +98,10 @@ namespace Grand.Business.Catalog.Services.Productsreturn await _productRepository.GetByIdAsync(productId);var key = string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId);- return await _cacheBase.GetAsync(key, () => _productRepository.GetByIdAsync(productId));+ return await _cacheBase.GetAsync(key, () =>+ {+ return _productRepository.GetByIdAsync(productId);+ });}/// <summary>@@ -329,6 +333,42 @@ namespace Grand.Business.Catalog.Services.Products//event notificationawait _mediator.EntityUpdated(product);}++ public virtual async Task UpdateProductField<T>(Product product,+ Expression<Func<Product, T>> expression, T value)+ {+ if (product == null)+ throw new ArgumentNullException(nameof(product));++ //update field+ await _productRepository.UpdateField<T>(product.Id, expression, value);++ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);++ //event notification+ await _mediator.EntityUpdated(product);++ }+ /// <summary>+ /// Increases the value of a number field - this method do not clear cache related with product+ /// </summary>+ /// <typeparam name="T"></typeparam>+ /// <param name="product"></param>+ /// <param name="expression"></param>+ /// <param name="value"></param>+ /// <returns></returns>+ /// <exception cref="ArgumentNullException"></exception>+ public virtual async Task IncrementProductField<T>(Product product,+ Expression<Func<Product, T>> expression, T value)+ {+ if (product == null)+ throw new ArgumentNullException(nameof(product));++ //inc field+ await _productRepository.IncField<T>(product.Id, expression, value);+ }+/// <summary>/// Delete a product/// </summary>@@ -348,16 +388,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _mediator.EntityDeleted(product);}- public virtual async Task UpdateMostView(Product product)- {- await _productRepository.UpdateField(product.Id, x => x.Viewed, product.Viewed + 1);- }-- public virtual async Task UpdateSold(Product product, int qty)- {- await _productRepository.UpdateField(product.Id, x => x.Sold, product.Sold + qty);- }-+public virtual async Task UnpublishProduct(Product product){var update = UpdateBuilder<Product>.Create()diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.csindex 483e19499..a6bb66782 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs@@ -1,23 +1,23 @@-using Grand.Business.Core.Extensions;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Events.Checkout.Orders;+using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Catalog.Tax;-using Grand.Business.Core.Utilities.Catalog;-using Grand.Business.Core.Commands.Checkout.Orders;-using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Business.Core.Utilities.Checkout;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.Pdf;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Queries.Checkout.Orders;+using Grand.Business.Core.Utilities.Catalog;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;@@ -1063,7 +1063,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersawait _inventoryManageService.AdjustReserved(product, -sc.Quantity, sc.Attributes, orderItem.WarehouseId);//update sold- await _productService.UpdateSold(product, sc.Quantity);+ _ = _productService.IncrementProductField(product, x => x.Sold, sc.Quantity);}//insert orderdiff --git a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateIntervalPropertiesCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/UpdateIntervalPropertiesCommand.csdeleted file mode 100644index 4eefb43fa..000000000--- a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateIntervalPropertiesCommand.cs+++ /dev/null@@ -1,13 +0,0 @@-using Grand.Domain.Catalog;-using MediatR;--namespace Grand.Business.Core.Commands.Catalog-{- public class UpdateIntervalPropertiesCommand : IRequest<bool>- {- public Product Product { get; set; }- public int Interval { get; set; }- public IntervalUnit IntervalUnit { get; set; }- public bool IncludeBothDates { get; set; }- }-}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.csindex d3c0479da..df35b4684 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs@@ -2,6 +2,7 @@ using Grand.Domain;using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;+using System.Linq.Expressions;namespace Grand.Business.Core.Interfaces.Catalog.Products{@@ -73,23 +74,25 @@ namespace Grand.Business.Core.Interfaces.Catalog.ProductsTask DeleteProduct(Product product);/// <summary>- /// Updates most view on the product+ /// Set product as unpublished/// </summary>- /// <param name="product">Product</param>- Task UpdateMostView(Product product);+ /// <param name="product"></param>+ Task UnpublishProduct(Product product);/// <summary>- /// Updates best sellers on the product+ /// Updates the product field/// </summary>/// <param name="product">Product</param>- /// <param name="qty">Count</param>- Task UpdateSold(Product product, int qty);+ Task UpdateProductField<T>(Product product,+ Expression<Func<Product, T>> expression, T value);+/// <summary>- /// Set product as unpublished+ /// Increment the product field/// </summary>- /// <param name="product"></param>- Task UnpublishProduct(Product product);+ /// <param name="product">Product</param>+ Task IncrementProductField<T>(Product product,+ Expression<Func<Product, T>> expression, T value);/// <summary>/// Get (visible) product number in certain categorydiff --git a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateIntervalPropertiesCommandHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateIntervalPropertiesCommandHandlerTests.csdeleted file mode 100644index 135ba3502..000000000--- a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateIntervalPropertiesCommandHandlerTests.cs+++ /dev/null@@ -1,50 +0,0 @@-using Grand.Business.Catalog.Commands.Handlers;-using Grand.Business.Core.Commands.Catalog;-using Grand.Domain.Catalog;-using Grand.Domain.Data.Mongo;-using Grand.Infrastructure.Caching;-using Grand.SharedKernel.Extensions;-using Microsoft.VisualStudio.TestTools.UnitTesting;-using Moq;--namespace Grand.Business.Catalog.Tests.Handlers-{- [TestClass()]- public class UpdateIntervalPropertiesCommandHandlerTests- {- private Mock<MongoRepository<Product>> _repositoryMock;- private Mock<ICacheBase> _cacheMock;- private UpdateIntervalPropertiesCommandHandler _handler;-- [TestInitialize()]- public void Init()- {- CommonPath.BaseDirectory = "";-- _repositoryMock = new Mock<MongoRepository<Product>>();- _cacheMock = new Mock<ICacheBase>();- _handler = new UpdateIntervalPropertiesCommandHandler(_repositoryMock.Object, _cacheMock.Object);- }-- [TestMethod()]- public void Handle_NullProduct_ThrowError()- {- var command = new UpdateIntervalPropertiesCommand() { Product = null };- Assert.ThrowsExceptionAsync<ArgumentNullException>(() => _handler.Handle(command, default));- }-- [TestMethod()]- public async Task Handle_ValidArgument_UpdateClearCachAndPublishEvent()- {- var product = new Product();- var command = new UpdateIntervalPropertiesCommand() { Product = product };- //var collectionMock = new Mock<IMongoCollection<Product>>();- //_repositoryMock.Setup(c => c.Collection).Returns(collectionMock.Object);- await _handler.Handle(command, default);- //TODO- //collectionMock.Verify(c => c.UpdateOneAsync(x => x.Id == product.Id, It.IsAny<UpdateDefinition<Product>>(), null, default), Times.Once);- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);-- }- }-}diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.csindex 29d27194d..f03e79ba4 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs@@ -196,38 +196,6 @@ namespace Grand.Business.Catalog.Services.Products.TestsAssert.IsNull(result);}- [TestMethod()]- public async Task UpdateMostViewTest()- {- //Arrange- var product = new Product() { Id = "101", Viewed = 10 };- await _productService.InsertProduct(product);-- //Act- await _productService.UpdateMostView(product);- var result = await _productService.GetProductById("101");-- //Assert- Assert.IsNotNull(result);- Assert.IsTrue(result.Viewed == 11);- }-- [TestMethod()]- public async Task UpdateSoldTest()- {- //Arrange- var product = new Product() { Id = "104", Sold = 10 };- await _productService.InsertProduct(product);-- //Act- await _productService.UpdateSold(product, 1);- var result = await _productService.GetProductById("104");-- //Assert- Assert.IsNotNull(result);- Assert.IsTrue(result.Sold == 11);- }-[TestMethod()]public async Task UnpublishProductTest(){@@ -296,7 +264,39 @@ namespace Grand.Business.Catalog.Services.Products.Tests//AssertAssert.IsNotNull(result);}+ [TestMethod()]+ public async Task UpdateProductFieldTest()+ {+ //Arrange+ var product = new Product();+ await _productService.InsertProduct(product);+ //Act+ await _productService.UpdateProductField(product, x => x.Name, "test");++ var result = await _productService.GetProductById(product.Id);++ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual("test", result.Name);+ }+ [TestMethod()]+ public async Task IncrementProductFieldTest()+ {+ //Arrange+ var product = new Product();+ await _productService.InsertProduct(product);+ //Act+ await _productService.IncrementProductField(product, x => x.Viewed, 1);+ await _productService.IncrementProductField(product, x => x.Viewed, 1);+ await _productService.IncrementProductField(product, x => x.Viewed, 1);++ var result = await _productService.GetProductById(product.Id, true);++ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual(3, result.Viewed);+ }[TestMethod()]public async Task UpdateAssociatedProductTest(){diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductController.csindex a0f325875..08b27c1db 100644--- a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs@@ -1,19 +1,19 @@-using Grand.Business.Core.Commands.Catalog;-using Grand.Business.Core.Interfaces.Catalog.Products;+using Grand.Business.Catalog.Services.ExportImport.Dto;using Grand.Business.Core.Extensions;+using Grand.Business.Core.Interfaces.Catalog.Products;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.Interfaces.Common.Stores;-using Grand.Business.Core.Utilities.Common.Security;using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.ExportImport;using Grand.Business.Core.Interfaces.Storage;+using Grand.Business.Core.Utilities.Common.Security;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Media;using Grand.Infrastructure;-using Grand.Infrastructure.Extensions;using Grand.Web.Admin.Extensions;using Grand.Web.Admin.Interfaces;using Grand.Web.Admin.Models.Catalog;@@ -22,13 +22,10 @@ using Grand.Web.Common.DataSource;using Grand.Web.Common.Extensions;using Grand.Web.Common.Filters;using Grand.Web.Common.Security.Authorization;-using MediatR;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.StaticFiles;-using Grand.Business.Core.Interfaces.ExportImport;-using Grand.Business.Catalog.Services.ExportImport.Dto;namespace Grand.Web.Admin.Controllers{@@ -50,7 +47,6 @@ namespace Grand.Web.Admin.Controllersprivate readonly IAuctionService _auctionService;private readonly IDateTimeService _dateTimeService;private readonly IPermissionService _permissionService;- private readonly IMediator _mediator;#endregion@@ -69,8 +65,7 @@ namespace Grand.Web.Admin.ControllersIProductReservationService productReservationService,IAuctionService auctionService,IDateTimeService dateTimeService,- IPermissionService permissionService,- IMediator mediator)+ IPermissionService permissionService){_productViewModelService = productViewModelService;_productService = productService;@@ -85,7 +80,6 @@ namespace Grand.Web.Admin.Controllers_auctionService = auctionService;_dateTimeService = dateTimeService;_permissionService = permissionService;- _mediator = mediator;}#endregion@@ -1447,7 +1441,7 @@ namespace Grand.Web.Admin.ControllersError(ModelState);model.AvailableAttributes = await PrepareAvailableAttributes(specificationAttributeService);-+return View(model);}private async Task<List<SelectListItem>> PrepareAvailableAttributes(ISpecificationAttributeService specificationAttributeService)@@ -2680,12 +2674,6 @@ namespace Grand.Web.Admin.Controllers}}- //update fields on product- await _mediator.Send(new UpdateIntervalPropertiesCommand() { Product = product, IncludeBothDates = model.IncBothDate, Interval = model.Interval, IntervalUnit = (IntervalUnit)model.IntervalUnit });-- //event notification- await _mediator.EntityUpdated(product);-if (!ModelState.IsValid){Dictionary<string, Dictionary<string, object>> error = (Dictionary<string, Dictionary<string, object>>)ModelState.SerializeErrors();@@ -2702,6 +2690,11 @@ namespace Grand.Web.Admin.Controllersreturn Json(new { errors = s });}+ //update fields on product+ await _productService.UpdateProductField(product, x => x.Interval, model.Interval);+ await _productService.UpdateProductField(product, x => x.IntervalUnitId, (IntervalUnit)model.IntervalUnit);+ await _productService.UpdateProductField(product, x => x.IncBothDate, model.IncBothDate);+int minutesToAdd = 0;if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Minute){diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.csindex 1dc77eda1..56136c81a 100644--- a/src/Web/Grand.Web/Controllers/ProductController.cs+++ b/src/Web/Grand.Web/Controllers/ProductController.cs@@ -168,7 +168,7 @@ namespace Grand.Web.Controllers_ = _customerActivityService.InsertActivity("PublicStore.ViewProduct", product.Id, _workContext.CurrentCustomer, HttpContext.Connection?.RemoteIpAddress?.ToString(),_translationService.GetResource("ActivityLog.PublicStore.ViewProduct"), product.Name);- await _productService.UpdateMostView(product);+ _ = _productService.IncrementProductField(product, x => x.Viewed, 1);return View(productLayoutViewPath, model);}@@ -415,7 +415,7 @@ namespace Grand.Web.Controllers_ = _customerActivityService.InsertActivity("PublicStore.ViewProduct", product.Id, _workContext.CurrentCustomer, HttpContext.Connection?.RemoteIpAddress?.ToString(),_translationService.GetResource("ActivityLog.PublicStore.ViewProduct"), product.Name);- await _productService.UpdateMostView(product);+ _ = _productService.IncrementProductField(product, x => x.Viewed, 1);return Json(new{