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.

Grand.Business.Catalog - Code cleanup (ReSharper)

supportc01254793696
diff --git a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs
index 54d6bf3d9..f33173529 100644
--- a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs
@@ -1,77 +1,76 @@
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Commands
+namespace Grand.Business.Catalog.Commands;
+
+public class UpdateProductReviewTotalsCommandHandler : IRequestHandler<UpdateProductReviewTotalsCommand, bool>
{
- public class UpdateProductReviewTotalsCommandHandler : IRequestHandler<UpdateProductReviewTotalsCommand, bool>
+ public UpdateProductReviewTotalsCommandHandler(IRepository<Product> productRepository,
+ IProductReviewService productReviewService, ICacheBase cacheBase)
{
- #region Fields
-
- private readonly IRepository<Product> _productRepository;
- private readonly IProductReviewService _productReviewService;
- private readonly ICacheBase _cacheBase;
-
- #endregion
-
- public UpdateProductReviewTotalsCommandHandler(IRepository<Product> productRepository,
- IProductReviewService productReviewService, ICacheBase cacheBase)
- {
- _productRepository = productRepository;
- _cacheBase = cacheBase;
- _productReviewService = productReviewService;
- }
+ _productRepository = productRepository;
+ _cacheBase = cacheBase;
+ _productReviewService = productReviewService;
+ }
- public async Task<bool> Handle(UpdateProductReviewTotalsCommand request, CancellationToken cancellationToken)
- {
- if (request.Product == null)
- throw new ArgumentNullException(nameof(request.Product));
+ public async Task<bool> Handle(UpdateProductReviewTotalsCommand request, CancellationToken cancellationToken)
+ {
+ if (request.Product == null)
+ throw new ArgumentNullException(nameof(request.Product));
- var approvedRatingSum = 0;
- var notApprovedRatingSum = 0;
- var approvedTotalReviews = 0;
- var notApprovedTotalReviews = 0;
+ var approvedRatingSum = 0;
+ var notApprovedRatingSum = 0;
+ var approvedTotalReviews = 0;
+ var notApprovedTotalReviews = 0;
- var reviews = await _productReviewService.GetAllProductReviews(null, null, null, null, null,
- null, request.Product.Id);
+ var reviews = await _productReviewService.GetAllProductReviews(null, null, null, null, null,
+ null, request.Product.Id);
- foreach (var pr in reviews)
+ foreach (var pr in reviews)
+ if (pr.IsApproved)
+ {
+ approvedRatingSum += pr.Rating;
+ approvedTotalReviews++;
+ }
+ else
{
- if (pr.IsApproved)
- {
- approvedRatingSum += pr.Rating;
- approvedTotalReviews++;
- }
- else
- {
- notApprovedRatingSum += pr.Rating;
- notApprovedTotalReviews++;
- }
+ notApprovedRatingSum += pr.Rating;
+ notApprovedTotalReviews++;
}
- request.Product.ApprovedRatingSum = approvedRatingSum;
- request.Product.NotApprovedRatingSum = notApprovedRatingSum;
- request.Product.ApprovedTotalReviews = approvedTotalReviews;
- request.Product.NotApprovedTotalReviews = notApprovedTotalReviews;
- request.Product.AvgRating = approvedTotalReviews > 0 ? Math.Round((double)approvedRatingSum / approvedTotalReviews, 2) : 0;
-
- var update = UpdateBuilder<Product>.Create()
- .Set(x => x.ApprovedRatingSum, request.Product.ApprovedRatingSum)
- .Set(x => x.NotApprovedRatingSum, request.Product.NotApprovedRatingSum)
- .Set(x => x.ApprovedTotalReviews, request.Product.ApprovedTotalReviews)
- .Set(x => x.AvgRating, request.Product.AvgRating)
- .Set(x => x.NotApprovedTotalReviews, request.Product.NotApprovedTotalReviews);
+ request.Product.ApprovedRatingSum = approvedRatingSum;
+ request.Product.NotApprovedRatingSum = notApprovedRatingSum;
+ request.Product.ApprovedTotalReviews = approvedTotalReviews;
+ request.Product.NotApprovedTotalReviews = notApprovedTotalReviews;
+ request.Product.AvgRating = approvedTotalReviews > 0
+ ? Math.Round((double)approvedRatingSum / approvedTotalReviews, 2)
+ : 0;
+
+ var update = UpdateBuilder<Product>.Create()
+ .Set(x => x.ApprovedRatingSum, request.Product.ApprovedRatingSum)
+ .Set(x => x.NotApprovedRatingSum, request.Product.NotApprovedRatingSum)
+ .Set(x => x.ApprovedTotalReviews, request.Product.ApprovedTotalReviews)
+ .Set(x => x.AvgRating, request.Product.AvgRating)
+ .Set(x => x.NotApprovedTotalReviews, request.Product.NotApprovedTotalReviews);
- await _productRepository.UpdateOneAsync(x => x.Id == request.Product.Id, update);
+ await _productRepository.UpdateOneAsync(x => x.Id == request.Product.Id, update);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, request.Product.Id));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, request.Product.Id));
- return true;
- }
+ return true;
}
+
+ #region Fields
+
+ private readonly IRepository<Product> _productRepository;
+ private readonly IProductReviewService _productReviewService;
+ private readonly ICacheBase _cacheBase;
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/BrandDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/BrandDeletedEventHandler.cs
index 1b306db3e..a93adb30e 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/BrandDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/BrandDeletedEventHandler.cs
@@ -1,23 +1,22 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class BrandDeletedEventHandler : INotificationHandler<EntityDeleted<Brand>>
{
- public class BrandDeletedEventHandler : INotificationHandler<EntityDeleted<Brand>>
- {
- private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<Product> _productRepository;
- public BrandDeletedEventHandler(IRepository<Product> productRepository)
- {
- _productRepository = productRepository;
- }
+ public BrandDeletedEventHandler(IRepository<Product> productRepository)
+ {
+ _productRepository = productRepository;
+ }
- public async Task Handle(EntityDeleted<Brand> notification, CancellationToken cancellationToken)
- {
- await _productRepository.UpdateManyAsync(x => x.BrandId == notification.Entity.Id,
- UpdateBuilder<Product>.Create().Set(x => x.BrandId, ""));
- }
+ public async Task Handle(EntityDeleted<Brand> notification, CancellationToken cancellationToken)
+ {
+ await _productRepository.UpdateManyAsync(x => x.BrandId == notification.Entity.Id,
+ UpdateBuilder<Product>.Create().Set(x => x.BrandId, ""));
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs
index 5b0c4b1e3..285d42162 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs
@@ -1,42 +1,41 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class CategoryDeletedEventHandler : INotificationHandler<EntityDeleted<Category>>
{
- public class CategoryDeletedEventHandler : INotificationHandler<EntityDeleted<Category>>
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<EntityUrl> _entityUrlRepository;
+ private readonly IRepository<Product> _productRepository;
+
+ public CategoryDeletedEventHandler(
+ IRepository<EntityUrl> entityUrlRepository,
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase)
{
- private readonly IRepository<EntityUrl> _entityUrlRepository;
- private readonly IRepository<Product> _productRepository;
-
- private readonly ICacheBase _cacheBase;
-
- public CategoryDeletedEventHandler(
- IRepository<EntityUrl> entityUrlRepository,
- IRepository<Product> productRepository,
- ICacheBase cacheBase)
- {
- _entityUrlRepository = entityUrlRepository;
- _productRepository = productRepository;
+ _entityUrlRepository = entityUrlRepository;
+ _productRepository = productRepository;
- _cacheBase = cacheBase;
- }
-
- public async Task Handle(EntityDeleted<Category> notification, CancellationToken cancellationToken)
- {
- //delete url
- await _entityUrlRepository.DeleteManyAsync(x => x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Category);
+ _cacheBase = cacheBase;
+ }
- //delete on the product
- await _productRepository.PullFilter(string.Empty, x => x.ProductCategories, z => z.CategoryId, notification.Entity.Id);
+ public async Task Handle(EntityDeleted<Category> notification, CancellationToken cancellationToken)
+ {
+ //delete url
+ await _entityUrlRepository.DeleteManyAsync(x =>
+ x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Category);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //delete on the product
+ await _productRepository.PullFilter(string.Empty, x => x.ProductCategories, z => z.CategoryId,
+ notification.Entity.Id);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs
index bf03f5ce7..6aa857433 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs
@@ -1,40 +1,40 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
-{
- public class CollectionDeletedEventHandler : INotificationHandler<EntityDeleted<Collection>>
- {
- private readonly IRepository<EntityUrl> _entityUrlRepository;
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
+namespace Grand.Business.Catalog.Events.Handlers;
- public CollectionDeletedEventHandler(
- IRepository<EntityUrl> entityUrlRepository,
- IRepository<Product> productRepository,
- ICacheBase cacheBase)
- {
- _entityUrlRepository = entityUrlRepository;
- _productRepository = productRepository;
- _cacheBase = cacheBase;
- }
+public class CollectionDeletedEventHandler : INotificationHandler<EntityDeleted<Collection>>
+{
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<EntityUrl> _entityUrlRepository;
+ private readonly IRepository<Product> _productRepository;
- public async Task Handle(EntityDeleted<Collection> notification, CancellationToken cancellationToken)
- {
- //delete url
- await _entityUrlRepository.DeleteManyAsync(x => x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Collection);
+ public CollectionDeletedEventHandler(
+ IRepository<EntityUrl> entityUrlRepository,
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase)
+ {
+ _entityUrlRepository = entityUrlRepository;
+ _productRepository = productRepository;
+ _cacheBase = cacheBase;
+ }
- //delete on the product
- await _productRepository.PullFilter(string.Empty, x => x.ProductCollections, z => z.CollectionId, notification.Entity.Id);
+ public async Task Handle(EntityDeleted<Collection> notification, CancellationToken cancellationToken)
+ {
+ //delete url
+ await _entityUrlRepository.DeleteManyAsync(x =>
+ x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Collection);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //delete on the product
+ await _productRepository.PullFilter(string.Empty, x => x.ProductCollections, z => z.CollectionId,
+ notification.Entity.Id);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/DeleteMeasureUnitOnProductEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/DeleteMeasureUnitOnProductEventHandler.cs
index 65a02b4b4..5eb980509 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/DeleteMeasureUnitOnProductEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/DeleteMeasureUnitOnProductEventHandler.cs
@@ -1,24 +1,23 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Directory;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class DeleteMeasureUnitOnProductEventHandler : INotificationHandler<EntityDeleted<MeasureUnit>>
{
- public class DeleteMeasureUnitOnProductEventHandler : INotificationHandler<EntityDeleted<MeasureUnit>>
- {
- private readonly IRepository<Product> _repositoryProduct;
+ private readonly IRepository<Product> _repositoryProduct;
- public DeleteMeasureUnitOnProductEventHandler(IRepository<Product> repositoryProduct)
- {
- _repositoryProduct = repositoryProduct;
- }
+ public DeleteMeasureUnitOnProductEventHandler(IRepository<Product> repositoryProduct)
+ {
+ _repositoryProduct = repositoryProduct;
+ }
- public async Task Handle(EntityDeleted<MeasureUnit> notification, CancellationToken cancellationToken)
- {
- await _repositoryProduct.UpdateManyAsync(x => x.UnitId == notification.Entity.Id,
- UpdateBuilder<Product>.Create().Set(x => x.UnitId, ""));
- }
+ public async Task Handle(EntityDeleted<MeasureUnit> notification, CancellationToken cancellationToken)
+ {
+ await _repositoryProduct.UpdateManyAsync(x => x.UnitId == notification.Entity.Id,
+ UpdateBuilder<Product>.Create().Set(x => x.UnitId, ""));
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/DeliveryDateDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/DeliveryDateDeletedEventHandler.cs
index bdd57771c..3d0c9428d 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/DeliveryDateDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/DeliveryDateDeletedEventHandler.cs
@@ -1,24 +1,23 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class DeliveryDateDeletedEventHandler : INotificationHandler<EntityDeleted<DeliveryDate>>
{
- public class DeliveryDateDeletedEventHandler : INotificationHandler<EntityDeleted<DeliveryDate>>
- {
- private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<Product> _productRepository;
- public DeliveryDateDeletedEventHandler(IRepository<Product> productRepository)
- {
- _productRepository = productRepository;
- }
+ public DeliveryDateDeletedEventHandler(IRepository<Product> productRepository)
+ {
+ _productRepository = productRepository;
+ }
- public async Task Handle(EntityDeleted<DeliveryDate> notification, CancellationToken cancellationToken)
- {
- await _productRepository.UpdateManyAsync(x => x.DeliveryDateId == notification.Entity.Id,
- UpdateBuilder<Product>.Create().Set(x => x.DeliveryDateId, ""));
- }
+ public async Task Handle(EntityDeleted<DeliveryDate> notification, CancellationToken cancellationToken)
+ {
+ await _productRepository.UpdateManyAsync(x => x.DeliveryDateId == notification.Entity.Id,
+ UpdateBuilder<Product>.Create().Set(x => x.DeliveryDateId, ""));
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs
index 49e3aaba4..3590c96a6 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs
@@ -1,5 +1,5 @@
-using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Discounts;
using Grand.Domain.Vendors;
using Grand.Infrastructure.Caching;
@@ -7,91 +7,89 @@ using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class DiscountDeletedEventHandler : INotificationHandler<EntityDeleted<Discount>>
{
- public class DiscountDeletedEventHandler : INotificationHandler<EntityDeleted<Discount>>
+ public DiscountDeletedEventHandler(
+ IRepository<Product> productRepository,
+ IRepository<Category> categoryRepository,
+ IRepository<Brand> brandRepository,
+ IRepository<Collection> collectionRepository,
+ IRepository<Vendor> vendorRepository,
+ IRepository<DiscountCoupon> discountCouponRepository,
+ ICacheBase cacheBase
+ )
{
+ _productRepository = productRepository;
+ _categoryRepository = categoryRepository;
+ _brandRepository = brandRepository;
+ _collectionRepository = collectionRepository;
+ _vendorRepository = vendorRepository;
+ _vendorRepository = vendorRepository;
+ _discountCouponRepository = discountCouponRepository;
+ _cacheBase = cacheBase;
+ }
- #region Fields
-
- private readonly IRepository<Product> _productRepository;
- private readonly IRepository<Category> _categoryRepository;
- private readonly IRepository<Brand> _brandRepository;
- private readonly IRepository<Collection> _collectionRepository;
- private readonly IRepository<Vendor> _vendorRepository;
- private readonly IRepository<DiscountCoupon> _discountCouponRepository;
- private readonly ICacheBase _cacheBase;
-
- #endregion
+ public async Task Handle(EntityDeleted<Discount> notification, CancellationToken cancellationToken)
+ {
+ var discount = notification.Entity;
- public DiscountDeletedEventHandler(
- IRepository<Product> productRepository,
- IRepository<Category> categoryRepository,
- IRepository<Brand> brandRepository,
- IRepository<Collection> collectionRepository,
- IRepository<Vendor> vendorRepository,
- IRepository<DiscountCoupon> discountCouponRepository,
- ICacheBase cacheBase
- )
+ switch (discount.DiscountTypeId)
{
- _productRepository = productRepository;
- _categoryRepository = categoryRepository;
- _brandRepository = brandRepository;
- _collectionRepository = collectionRepository;
- _vendorRepository = vendorRepository;
- _vendorRepository = vendorRepository;
- _discountCouponRepository = discountCouponRepository;
- _cacheBase = cacheBase;
+ case DiscountType.AssignedToSkus:
+ //delete on the product
+ await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ break;
+ case DiscountType.AssignedToCategories:
+ //delete on the category
+ await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
+ break;
+ case DiscountType.AssignedToBrands:
+ //delete on the brand
+ await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
+ break;
+ case DiscountType.AssignedToCollections:
+ //delete on the collection
+ await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
+ break;
+ case DiscountType.AssignedToVendors:
+ //delete on the vendor
+ await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ break;
+ case DiscountType.AssignedToOrderTotal:
+ break;
+ case DiscountType.AssignedToShipping:
+ break;
+ case DiscountType.AssignedToOrderSubTotal:
+ break;
+ case DiscountType.AssignedToAllProducts:
+ break;
}
- public async Task Handle(EntityDeleted<Discount> notification, CancellationToken cancellationToken)
- {
- var discount = notification.Entity;
+ //remove coupon codes
+ await _discountCouponRepository.DeleteManyAsync(x => x.DiscountId == discount.Id);
+ }
- switch (discount.DiscountTypeId)
- {
- case DiscountType.AssignedToSkus:
- //delete on the product
- await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
+ #region Fields
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- break;
- case DiscountType.AssignedToCategories:
- //delete on the category
- await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
- break;
- case DiscountType.AssignedToBrands:
- //delete on the brand
- await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
- break;
- case DiscountType.AssignedToCollections:
- //delete on the collection
- await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
- break;
- case DiscountType.AssignedToVendors:
- //delete on the vendor
- await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- break;
- case DiscountType.AssignedToOrderTotal:
- break;
- case DiscountType.AssignedToShipping:
- break;
- case DiscountType.AssignedToOrderSubTotal:
- break;
- case DiscountType.AssignedToAllProducts:
- break;
- }
+ private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<Category> _categoryRepository;
+ private readonly IRepository<Brand> _brandRepository;
+ private readonly IRepository<Collection> _collectionRepository;
+ private readonly IRepository<Vendor> _vendorRepository;
+ private readonly IRepository<DiscountCoupon> _discountCouponRepository;
+ private readonly ICacheBase _cacheBase;
- //remove coupon codes
- await _discountCouponRepository.DeleteManyAsync(x => x.DiscountId == discount.Id);
- }
- }
-}
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs
index 26e27c530..3dfb8d79e 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs
@@ -1,85 +1,86 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Events;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Seo;
+using Grand.Infrastructure.Events;
using MediatR;
using System.Text.Json;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<Product>>
{
- public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<Product>>
- {
- private readonly IRepository<Product> _productRepository;
- private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
- private readonly IRepository<Customer> _customerRepository;
- private readonly IRepository<EntityUrl> _entityUrlRepository;
- private readonly IRepository<ProductTag> _productTagRepository;
- private readonly IRepository<ProductReview> _productReviewRepository;
- private readonly IRepository<ProductDeleted> _productDeletedRepository;
- private readonly IProductTagService _productTagService;
+ private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
+ private readonly IRepository<Customer> _customerRepository;
+ private readonly IRepository<EntityUrl> _entityUrlRepository;
+ private readonly IRepository<ProductDeleted> _productDeletedRepository;
+ private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<ProductReview> _productReviewRepository;
+ private readonly IRepository<ProductTag> _productTagRepository;
+ private readonly IProductTagService _productTagService;
- public ProductDeletedEventHandler(
- IRepository<Product> productRepository,
- IRepository<CustomerGroupProduct> customerGroupProductRepository,
- IRepository<Customer> customerRepository,
- IRepository<EntityUrl> entityUrlRepository,
- IRepository<ProductTag> productTagRepository,
- IRepository<ProductReview> productReviewRepository,
- IRepository<ProductDeleted> productDeletedRepository,
- IProductTagService productTagService)
- {
- _productRepository = productRepository;
- _customerGroupProductRepository = customerGroupProductRepository;
- _customerRepository = customerRepository;
- _entityUrlRepository = entityUrlRepository;
- _productTagRepository = productTagRepository;
- _productReviewRepository = productReviewRepository;
- _productDeletedRepository = productDeletedRepository;
- _productTagService = productTagService;
- }
+ public ProductDeletedEventHandler(
+ IRepository<Product> productRepository,
+ IRepository<CustomerGroupProduct> customerGroupProductRepository,
+ IRepository<Customer> customerRepository,
+ IRepository<EntityUrl> entityUrlRepository,
+ IRepository<ProductTag> productTagRepository,
+ IRepository<ProductReview> productReviewRepository,
+ IRepository<ProductDeleted> productDeletedRepository,
+ IProductTagService productTagService)
+ {
+ _productRepository = productRepository;
+ _customerGroupProductRepository = customerGroupProductRepository;
+ _customerRepository = customerRepository;
+ _entityUrlRepository = entityUrlRepository;
+ _productTagRepository = productTagRepository;
+ _productReviewRepository = productReviewRepository;
+ _productDeletedRepository = productDeletedRepository;
+ _productTagService = productTagService;
+ }
- public async Task Handle(EntityDeleted<Product> notification, CancellationToken cancellationToken)
- {
- //delete related product
- await _productRepository.PullFilter(string.Empty, x => x.RelatedProducts, z => z.ProductId2, notification.Entity.Id);
+ public async Task Handle(EntityDeleted<Product> notification, CancellationToken cancellationToken)
+ {
+ //delete related product
+ await _productRepository.PullFilter(string.Empty, x => x.RelatedProducts, z => z.ProductId2,
+ notification.Entity.Id);
- //delete similar product
- await _productRepository.PullFilter(string.Empty, x => x.SimilarProducts, z => z.ProductId2, notification.Entity.Id);
+ //delete similar product
+ await _productRepository.PullFilter(string.Empty, x => x.SimilarProducts, z => z.ProductId2,
+ notification.Entity.Id);
- //delete cross sales product
- await _productRepository.Pull(string.Empty, x => x.CrossSellProduct, notification.Entity.Id);
+ //delete cross sales product
+ await _productRepository.Pull(string.Empty, x => x.CrossSellProduct, notification.Entity.Id);
- //delete recommended product
- await _productRepository.Pull(string.Empty, x => x.RecommendedProduct, notification.Entity.Id);
+ //delete recommended product
+ await _productRepository.Pull(string.Empty, x => x.RecommendedProduct, notification.Entity.Id);
- //delete review
- await _productReviewRepository.DeleteManyAsync(x=>x.ProductId == notification.Entity.Id);
+ //delete review
+ await _productReviewRepository.DeleteManyAsync(x => x.ProductId == notification.Entity.Id);
- //delete from shopping cart
- await _customerRepository.PullFilter(string.Empty, x => x.ShoppingCartItems, z => z.ProductId, notification.Entity.Id);
+ //delete from shopping cart
+ await _customerRepository.PullFilter(string.Empty, x => x.ShoppingCartItems, z => z.ProductId,
+ notification.Entity.Id);
- //delete customer group product
- await _customerGroupProductRepository.DeleteManyAsync(x => x.ProductId == notification.Entity.Id);
+ //delete customer group product
+ await _customerGroupProductRepository.DeleteManyAsync(x => x.ProductId == notification.Entity.Id);
- //delete url
- await _entityUrlRepository.DeleteManyAsync(x => x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Product);
+ //delete url
+ await _entityUrlRepository.DeleteManyAsync(x =>
+ x.EntityId == notification.Entity.Id && x.EntityName == EntityTypes.Product);
- //delete product tags
- var existingProductTags = _productTagRepository.Table.Where(x => notification.Entity.ProductTags.ToList().Contains(x.Name)).ToList();
- foreach (var tag in existingProductTags)
- {
- await _productTagService.DetachProductTag(tag, notification.Entity.Id);
- }
+ //delete product tags
+ var existingProductTags = _productTagRepository.Table
+ .Where(x => notification.Entity.ProductTags.ToList().Contains(x.Name)).ToList();
+ foreach (var tag in existingProductTags) await _productTagService.DetachProductTag(tag, notification.Entity.Id);
- //insert to deleted products
- var productDeleted = JsonSerializer.Deserialize<ProductDeleted>(JsonSerializer.Serialize(notification.Entity));
- if (productDeleted != null)
- {
- productDeleted.DeletedOnUtc = DateTime.UtcNow;
- await _productDeletedRepository.InsertAsync(productDeleted);
- }
+ //insert to deleted products
+ var productDeleted = JsonSerializer.Deserialize<ProductDeleted>(JsonSerializer.Serialize(notification.Entity));
+ if (productDeleted != null)
+ {
+ productDeleted.DeletedOnUtc = DateTime.UtcNow;
+ await _productDeletedRepository.InsertAsync(productDeleted);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductPublishEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductPublishEventHandler.cs
index 4a52cb421..a64f360cc 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductPublishEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductPublishEventHandler.cs
@@ -3,21 +3,20 @@ using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class ProductPublishEventHandler : INotificationHandler<ProductPublishEvent>
{
- public class ProductPublishEventHandler : INotificationHandler<ProductPublishEvent>
- {
- private readonly ICacheBase _cacheBase;
+ private readonly ICacheBase _cacheBase;
- public ProductPublishEventHandler(ICacheBase cacheBase)
- {
- _cacheBase = cacheBase;
- }
+ public ProductPublishEventHandler(ICacheBase cacheBase)
+ {
+ _cacheBase = cacheBase;
+ }
- public async Task Handle(ProductPublishEvent notification, CancellationToken cancellationToken)
- {
- if (notification.Product.ShowOnHomePage)
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_SHOWONHOMEPAGE);
- }
+ public async Task Handle(ProductPublishEvent notification, CancellationToken cancellationToken)
+ {
+ if (notification.Product.ShowOnHomePage)
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_SHOWONHOMEPAGE);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductUnPublishEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductUnPublishEventHandler.cs
index 18d271b72..60043dfd3 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductUnPublishEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductUnPublishEventHandler.cs
@@ -3,21 +3,20 @@ using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class ProductUnPublishEventHandler : INotificationHandler<ProductUnPublishEvent>
{
- public class ProductUnPublishEventHandler : INotificationHandler<ProductUnPublishEvent>
- {
- private readonly ICacheBase _cacheBase;
+ private readonly ICacheBase _cacheBase;
- public ProductUnPublishEventHandler(ICacheBase cacheBase)
- {
- _cacheBase = cacheBase;
- }
+ public ProductUnPublishEventHandler(ICacheBase cacheBase)
+ {
+ _cacheBase = cacheBase;
+ }
- public async Task Handle(ProductUnPublishEvent notification, CancellationToken cancellationToken)
- {
- if (notification.Product.ShowOnHomePage)
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_SHOWONHOMEPAGE);
- }
+ public async Task Handle(ProductUnPublishEvent notification, CancellationToken cancellationToken)
+ {
+ if (notification.Product.ShowOnHomePage)
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_SHOWONHOMEPAGE);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/TaxCategoryDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/TaxCategoryDeletedEventHandler.cs
index b7ab41236..b13a28223 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/TaxCategoryDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/TaxCategoryDeletedEventHandler.cs
@@ -4,21 +4,20 @@ using Grand.Domain.Tax;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class TaxCategoryDeletedEventHandler : INotificationHandler<EntityDeleted<TaxCategory>>
{
- public class TaxCategoryDeletedEventHandler : INotificationHandler<EntityDeleted<TaxCategory>>
- {
- private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<Product> _productRepository;
- public TaxCategoryDeletedEventHandler(IRepository<Product> productRepository)
- {
- _productRepository = productRepository;
- }
+ public TaxCategoryDeletedEventHandler(IRepository<Product> productRepository)
+ {
+ _productRepository = productRepository;
+ }
- public async Task Handle(EntityDeleted<TaxCategory> notification, CancellationToken cancellationToken)
- {
- await _productRepository.UpdateManyAsync(x => x.TaxCategoryId == notification.Entity.Id,
- UpdateBuilder<Product>.Create().Set(x => x.TaxCategoryId, ""));
- }
+ public async Task Handle(EntityDeleted<TaxCategory> notification, CancellationToken cancellationToken)
+ {
+ await _productRepository.UpdateManyAsync(x => x.TaxCategoryId == notification.Entity.Id,
+ UpdateBuilder<Product>.Create().Set(x => x.TaxCategoryId, ""));
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/UpdateProductOnCartEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/UpdateProductOnCartEventHandler.cs
index fbe4e8a08..35c1d67bc 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/UpdateProductOnCartEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/UpdateProductOnCartEventHandler.cs
@@ -1,35 +1,33 @@
using Grand.Business.Core.Events.Catalog;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
+namespace Grand.Business.Catalog.Events.Handlers;
+
+public class UpdateProductOnCartEventHandler : INotificationHandler<UpdateProductOnCartEvent>
{
- public class UpdateProductOnCartEventHandler : INotificationHandler<UpdateProductOnCartEvent>
- {
- private readonly IRepository<Customer> _customerRepository;
+ private readonly IRepository<Customer> _customerRepository;
- public UpdateProductOnCartEventHandler(IRepository<Customer> customerRepository)
- {
- _customerRepository = customerRepository;
- }
+ public UpdateProductOnCartEventHandler(IRepository<Customer> customerRepository)
+ {
+ _customerRepository = customerRepository;
+ }
- public async Task Handle(UpdateProductOnCartEvent notification, CancellationToken cancellationToken)
+ public async Task Handle(UpdateProductOnCartEvent notification, CancellationToken cancellationToken)
+ {
+ var customers = _customerRepository.Table
+ .Where(x => x.ShoppingCartItems.Any(y => y.ProductId == notification.Product.Id)).ToList();
+ foreach (var cs in customers)
+ foreach (var item in cs.ShoppingCartItems.Where(x => x.ProductId == notification.Product.Id))
{
- var customers = _customerRepository.Table.Where(x => x.ShoppingCartItems.Any(y => y.ProductId == notification.Product.Id)).ToList();
- foreach (var cs in customers)
- {
- foreach (var item in cs.ShoppingCartItems.Where(x => x.ProductId == notification.Product.Id))
- {
- item.AdditionalShippingChargeProduct = notification.Product.AdditionalShippingCharge;
- item.IsFreeShipping = notification.Product.IsFreeShipping;
- item.IsGiftVoucher = notification.Product.IsGiftVoucher;
- item.IsShipEnabled = notification.Product.IsShipEnabled;
- item.IsTaxExempt = notification.Product.IsTaxExempt;
+ item.AdditionalShippingChargeProduct = notification.Product.AdditionalShippingCharge;
+ item.IsFreeShipping = notification.Product.IsFreeShipping;
+ item.IsGiftVoucher = notification.Product.IsGiftVoucher;
+ item.IsShipEnabled = notification.Product.IsShipEnabled;
+ item.IsTaxExempt = notification.Product.IsTaxExempt;
- await _customerRepository.UpdateToSet(cs.Id, x => x.ShoppingCartItems, z => z.Id, item.Id, item);
- }
- }
+ await _customerRepository.UpdateToSet(cs.Id, x => x.ShoppingCartItems, z => z.Id, item.Id, item);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs
index 1655ac8a8..0386b4053 100644
--- a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs
@@ -4,24 +4,23 @@ using Grand.Domain.Shipping;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Catalog.Events.Handlers
-{
- public class WarehouseDeletedEventHandler : INotificationHandler<EntityDeleted<Warehouse>>
- {
- private readonly IRepository<Product> _productRepository;
+namespace Grand.Business.Catalog.Events.Handlers;
- public WarehouseDeletedEventHandler(IRepository<Product> productRepository)
- {
- _productRepository = productRepository;
- }
+public class WarehouseDeletedEventHandler : INotificationHandler<EntityDeleted<Warehouse>>
+{
+ private readonly IRepository<Product> _productRepository;
- public async Task Handle(EntityDeleted<Warehouse> notification, CancellationToken cancellationToken)
- {
- await _productRepository.PullFilter(string.Empty, x => x.ProductWarehouseInventory, z => z.WarehouseId, notification.Entity.Id);
+ public WarehouseDeletedEventHandler(IRepository<Product> productRepository)
+ {
+ _productRepository = productRepository;
+ }
- await _productRepository.UpdateManyAsync(x => x.WarehouseId == notification.Entity.Id,
- UpdateBuilder<Product>.Create().Set(x => x.WarehouseId, ""));
+ public async Task Handle(EntityDeleted<Warehouse> notification, CancellationToken cancellationToken)
+ {
+ await _productRepository.PullFilter(string.Empty, x => x.ProductWarehouseInventory, z => z.WarehouseId,
+ notification.Entity.Id);
- }
+ await _productRepository.UpdateManyAsync(x => x.WarehouseId == notification.Entity.Id,
+ UpdateBuilder<Product>.Create().Set(x => x.WarehouseId, ""));
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs
index 95864aa60..63e0b91b8 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs
@@ -20,18 +20,20 @@ public class GetDiscountAmountProviderHandler : IRequestHandler<GetDiscountAmoun
{
return GetDiscountAmountProvider(request.Discount, request.Customer, request.Product, request.Amount);
}
-
+
/// <summary>
- /// Get amount from discount amount provider
+ /// Get amount from discount amount provider
/// </summary>
/// <param name="discount"></param>
/// <param name="product"></param>
/// <param name="amount"></param>
/// <param name="customer"></param>
/// <returns></returns>
- private async Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product, double amount)
+ private async Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product,
+ double amount)
{
- var discountAmountProvider = _discountProviderLoader.LoadDiscountAmountProviderBySystemName(discount.DiscountPluginName);
+ var discountAmountProvider =
+ _discountProviderLoader.LoadDiscountAmountProviderBySystemName(discount.DiscountPluginName);
if (discountAmountProvider == null)
return 0;
return await discountAmountProvider.DiscountAmount(discount, customer, product, amount);
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs
index c26d64250..76fe942ea 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs
@@ -6,7 +6,9 @@ using MediatR;
namespace Grand.Business.Catalog.Queries.Handlers;
-public class GetDiscountUsageHistoryQueryHandler : IRequestHandler<GetDiscountUsageHistoryQuery, IPagedList<DiscountUsageHistory>>
+public class
+ GetDiscountUsageHistoryQueryHandler : IRequestHandler<GetDiscountUsageHistoryQuery,
+ IPagedList<DiscountUsageHistory>>
{
private readonly IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;
@@ -15,7 +17,8 @@ public class GetDiscountUsageHistoryQueryHandler : IRequestHandler<GetDiscountUs
_discountUsageHistoryRepository = discountUsageHistoryRepository;
}
- public async Task<IPagedList<DiscountUsageHistory>> Handle(GetDiscountUsageHistoryQuery request, CancellationToken cancellationToken)
+ public async Task<IPagedList<DiscountUsageHistory>> Handle(GetDiscountUsageHistoryQuery request,
+ CancellationToken cancellationToken)
{
var query = from d in _discountUsageHistoryRepository.Table
select d;
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs
index 9e1d7458d..a9dbdc34d 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPersonalizedProductsQueryHandler.cs
@@ -1,39 +1,40 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Queries.Catalog;
-using Grand.Infrastructure.Caching;
-using Grand.Infrastructure.Caching.Constants;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetPersonalizedProductsQueryHandler : IRequestHandler<GetPersonalizedProductsQuery, IList<Product>>
{
- public class GetPersonalizedProductsQueryHandler : IRequestHandler<GetPersonalizedProductsQuery, IList<Product>>
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerProduct> _customerProductRepository;
+
+ private readonly IProductService _productService;
+
+ public GetPersonalizedProductsQueryHandler(
+ IProductService productService,
+ ICacheBase cacheBase,
+ IRepository<CustomerProduct> customerProductRepository)
{
+ _productService = productService;
+ _cacheBase = cacheBase;
+ _customerProductRepository = customerProductRepository;
+ }
- private readonly IProductService _productService;
- private readonly ICacheBase _cacheBase;
- private readonly IRepository<CustomerProduct> _customerProductRepository;
-
- public GetPersonalizedProductsQueryHandler(
- IProductService productService,
- ICacheBase cacheBase,
- IRepository<CustomerProduct> customerProductRepository)
- {
- _productService = productService;
- _cacheBase = cacheBase;
- _customerProductRepository = customerProductRepository;
- }
-
- public async Task<IList<Product>> Handle(GetPersonalizedProductsQuery request, CancellationToken cancellationToken)
- {
- return await _cacheBase.GetAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY, request.CustomerId), async () =>
+ public async Task<IList<Product>> Handle(GetPersonalizedProductsQuery request, CancellationToken cancellationToken)
+ {
+ return await _cacheBase.GetAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY, request.CustomerId),
+ async () =>
{
var query = from cr in _customerProductRepository.Table
- where cr.CustomerId == request.CustomerId
- orderby cr.DisplayOrder
- select cr.ProductId;
+ where cr.CustomerId == request.CustomerId
+ orderby cr.DisplayOrder
+ select cr.ProductId;
var productIds = query.Take(request.ProductsNumber).ToList();
@@ -41,7 +42,5 @@ namespace Grand.Business.Catalog.Queries.Handlers
return ids.Where(product => product.Published).ToList();
});
-
- }
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs
index b9980780a..fa79c12c6 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetPriceByCustomerProductQueryHandler.cs
@@ -1,36 +1,36 @@
using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
-using Grand.Domain.Customers;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetPriceByCustomerProductQueryHandler : IRequestHandler<GetPriceByCustomerProductQuery, double?>
{
- public class GetPriceByCustomerProductQueryHandler : IRequestHandler<GetPriceByCustomerProductQuery, double?>
- {
- private readonly ICacheBase _cacheBase;
- private readonly IRepository<CustomerProductPrice> _customerProductPriceRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerProductPrice> _customerProductPriceRepository;
- public GetPriceByCustomerProductQueryHandler(ICacheBase cacheBase, IRepository<CustomerProductPrice> customerProductPriceRepository)
- {
- _cacheBase = cacheBase;
- _customerProductPriceRepository = customerProductPriceRepository;
- }
+ public GetPriceByCustomerProductQueryHandler(ICacheBase cacheBase,
+ IRepository<CustomerProductPrice> customerProductPriceRepository)
+ {
+ _cacheBase = cacheBase;
+ _customerProductPriceRepository = customerProductPriceRepository;
+ }
- public async Task<double?> Handle(GetPriceByCustomerProductQuery request, CancellationToken cancellationToken)
+ public async Task<double?> Handle(GetPriceByCustomerProductQuery request, CancellationToken cancellationToken)
+ {
+ var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, request.CustomerId, request.ProductId);
+ var productPrice = _cacheBase.Get(key, () =>
{
- var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, request.CustomerId, request.ProductId);
- var productPrice = _cacheBase.Get(key, () =>
- {
- var pp = _customerProductPriceRepository.Table
- .FirstOrDefault(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId);
- return pp == null ? (null, false) : (pp, true);
- });
+ var pp = _customerProductPriceRepository.Table
+ .FirstOrDefault(x => x.CustomerId == request.CustomerId && x.ProductId == request.ProductId);
+ return pp == null ? (null, false) : (pp, true);
+ });
- if (!productPrice.Item2)
- return await Task.FromResult(default(double?));
- return await Task.FromResult(productPrice.pp.Price);
- }
+ if (!productPrice.Item2)
+ return await Task.FromResult(default(double?));
+ return await Task.FromResult(productPrice.pp.Price);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs
index abb30706a..6614bf31a 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs
@@ -1,22 +1,21 @@
using Grand.Business.Core.Queries.Catalog;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetProductArchByIdQueryHandler : IRequestHandler<GetProductArchByIdQuery, Product>
{
- public class GetProductArchByIdQueryHandler : IRequestHandler<GetProductArchByIdQuery, Product>
- {
- private readonly IRepository<ProductDeleted> _productDeletedRepository;
+ private readonly IRepository<ProductDeleted> _productDeletedRepository;
- public GetProductArchByIdQueryHandler(IRepository<ProductDeleted> productDeletedRepository)
- {
- _productDeletedRepository = productDeletedRepository;
- }
+ public GetProductArchByIdQueryHandler(IRepository<ProductDeleted> productDeletedRepository)
+ {
+ _productDeletedRepository = productDeletedRepository;
+ }
- public async Task<Product> Handle(GetProductArchByIdQuery request, CancellationToken cancellationToken)
- {
- return await _productDeletedRepository.GetByIdAsync(request.Id);
- }
+ public async Task<Product> Handle(GetProductArchByIdQuery request, CancellationToken cancellationToken)
+ {
+ return await _productDeletedRepository.GetByIdAsync(request.Id);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs
index 931061564..0d928772c 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetRecommendedProductsQueryHandler.cs
@@ -1,39 +1,41 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetRecommendedProductsQueryHandler : IRequestHandler<GetRecommendedProductsQuery, IList<Product>>
{
- public class GetRecommendedProductsQueryHandler : IRequestHandler<GetRecommendedProductsQuery, IList<Product>>
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
+
+ private readonly IProductService _productService;
+
+ public GetRecommendedProductsQueryHandler(
+ IProductService productService,
+ ICacheBase cacheBase,
+ IRepository<CustomerGroupProduct> customerGroupProductRepository)
{
+ _productService = productService;
+ _cacheBase = cacheBase;
+ _customerGroupProductRepository = customerGroupProductRepository;
+ }
- private readonly IProductService _productService;
- private readonly ICacheBase _cacheBase;
- private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
-
- public GetRecommendedProductsQueryHandler(
- IProductService productService,
- ICacheBase cacheBase,
- IRepository<CustomerGroupProduct> customerGroupProductRepository)
- {
- _productService = productService;
- _cacheBase = cacheBase;
- _customerGroupProductRepository = customerGroupProductRepository;
- }
-
- public async Task<IList<Product>> Handle(GetRecommendedProductsQuery request, CancellationToken cancellationToken)
- {
- return await _cacheBase.GetAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_GROUP, string.Join(",", request.CustomerGroupIds), request.StoreId), async () =>
+ public async Task<IList<Product>> Handle(GetRecommendedProductsQuery request, CancellationToken cancellationToken)
+ {
+ return await _cacheBase.GetAsync(
+ string.Format(CacheKey.PRODUCTS_CUSTOMER_GROUP, string.Join(",", request.CustomerGroupIds),
+ request.StoreId), async () =>
{
var query = from cr in _customerGroupProductRepository.Table
- where request.CustomerGroupIds.Contains(cr.CustomerGroupId)
- orderby cr.DisplayOrder
- select cr.ProductId;
+ where request.CustomerGroupIds.Contains(cr.CustomerGroupId)
+ orderby cr.DisplayOrder
+ select cr.ProductId;
var productIds = query.ToList();
@@ -41,7 +43,5 @@ namespace Grand.Business.Catalog.Queries.Handlers
return ids.Where(product => product.Published).ToList();
});
-
- }
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
index f53922c48..616360430 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs
@@ -1,382 +1,333 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Configuration;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQuery, (IPagedList<Product> products,
+ IList<string> filterableSpecificationAttributeOptionIds)>
{
- public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQuery, (IPagedList<Product> products,
- IList<string> filterableSpecificationAttributeOptionIds)>
+ private readonly AccessControlConfig _accessControlConfig;
+ private readonly CatalogSettings _catalogSettings;
+ private readonly IRepository<Product> _productRepository;
+ private readonly ISpecificationAttributeService _specificationAttributeService;
+
+ public GetSearchProductsQueryHandler(
+ IRepository<Product> productRepository,
+ ISpecificationAttributeService specificationAttributeService,
+ CatalogSettings catalogSettings,
+ AccessControlConfig accessControlConfig)
{
- private readonly IRepository<Product> _productRepository;
- private readonly ISpecificationAttributeService _specificationAttributeService;
- private readonly AccessControlConfig _accessControlConfig;
- private readonly CatalogSettings _catalogSettings;
-
- public GetSearchProductsQueryHandler(
- IRepository<Product> productRepository,
- ISpecificationAttributeService specificationAttributeService,
- CatalogSettings catalogSettings,
- AccessControlConfig accessControlConfig)
- {
- _productRepository = productRepository;
- _specificationAttributeService = specificationAttributeService;
- _catalogSettings = catalogSettings;
- _accessControlConfig = accessControlConfig;
- }
+ _productRepository = productRepository;
+ _specificationAttributeService = specificationAttributeService;
+ _catalogSettings = catalogSettings;
+ _accessControlConfig = accessControlConfig;
+ }
- public async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)>
- Handle(GetSearchProductsQuery request, CancellationToken cancellationToken)
- {
- var filterableSpecificationAttributeOptionIds = new List<string>();
+ public async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)>
+ Handle(GetSearchProductsQuery request, CancellationToken cancellationToken)
+ {
+ var filterableSpecificationAttributeOptionIds = new List<string>();
- //validate "categoryIds" parameter
- if (request.CategoryIds != null && request.CategoryIds.Contains(""))
- request.CategoryIds.Remove("");
+ //validate "categoryIds" parameter
+ if (request.CategoryIds != null && request.CategoryIds.Contains(""))
+ request.CategoryIds.Remove("");
- //Access control list. Allowed customer groups
- var allowedCustomerGroupsIds = request.Customer.GetCustomerGroupIds();
+ //Access control list. Allowed customer groups
+ var allowedCustomerGroupsIds = request.Customer.GetCustomerGroupIds();
- #region Search products
+ #region Search products
- //products
- var query = from p in _productRepository.Table
- select p;
+ //products
+ var query = from p in _productRepository.Table
+ select p;
- query = FilterQueryable(request, query, allowedCustomerGroupsIds);
+ query = FilterQueryable(request, query, allowedCustomerGroupsIds);
- var querySpecification = query;
+ var querySpecification = query;
- //search by specs
- if (request.FilteredSpecs != null && request.FilteredSpecs.Any())
+ //search by specs
+ if (request.FilteredSpecs != null && request.FilteredSpecs.Any())
+ {
+ var spec = new HashSet<string>();
+ var dictionary = new Dictionary<string, List<string>>();
+ foreach (var key in request.FilteredSpecs)
{
- var spec = new HashSet<string>();
- Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
- foreach (var key in request.FilteredSpecs)
+ var specification = await _specificationAttributeService.GetSpecificationAttributeByOptionId(key);
+ if (specification == null) continue;
+ spec.Add(specification.Id);
+ if (!dictionary.ContainsKey(specification.Id))
{
- var specification = await _specificationAttributeService.GetSpecificationAttributeByOptionId(key);
- if (specification == null) continue;
- spec.Add(specification.Id);
- if (!dictionary.ContainsKey(specification.Id))
- {
- //add
- dictionary.Add(specification.Id, new List<string>());
- querySpecification = querySpecification.Where(x =>
- x.ProductSpecificationAttributes.Any(y =>
- y.SpecificationAttributeId == specification.Id && y.AllowFiltering));
- }
-
- dictionary[specification.Id].Add(key);
+ //add
+ dictionary.Add(specification.Id, new List<string>());
+ querySpecification = querySpecification.Where(x =>
+ x.ProductSpecificationAttributes.Any(y =>
+ y.SpecificationAttributeId == specification.Id && y.AllowFiltering));
}
- foreach (var item in dictionary)
- {
- query = query.Where(x => x.ProductSpecificationAttributes.Any(y =>
- y.SpecificationAttributeId == item.Key && y.AllowFiltering
- && item.Value.Contains(
- y.SpecificationAttributeOptionId)));
- }
+ dictionary[specification.Id].Add(key);
}
- if (request.SpecificationOptions != null && request.SpecificationOptions.Any())
- {
+ foreach (var item in dictionary)
query = query.Where(x => x.ProductSpecificationAttributes.Any(y =>
- request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId)));
- }
+ y.SpecificationAttributeId == item.Key && y.AllowFiltering
+ && item.Value.Contains(
+ y.SpecificationAttributeOptionId)));
+ }
- query = OrderByQueryable(request, query);
+ if (request.SpecificationOptions != null && request.SpecificationOptions.Any())
+ query = query.Where(x => x.ProductSpecificationAttributes.Any(y =>
+ request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId)));
- var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);
-
- if (!request.LoadFilterableSpecificationAttributeOptionIds ||
- _catalogSettings.IgnoreFilterableSpecAttributeOption)
- return (products, filterableSpecificationAttributeOptionIds);
- {
- var filterSpecExists =
- querySpecification.Where(x => x.ProductSpecificationAttributes.Any(x => x.AllowFiltering));
+ query = OrderByQueryable(request, query);
- var spec = from p in filterSpecExists
- from item in p.ProductSpecificationAttributes
- select item;
+ var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);
- var groupQuerySpec = spec.Where(x => x.AllowFiltering).GroupBy(x =>
- new { x.SpecificationAttributeOptionId }).ToList();
- IList<string> specification =
- groupQuerySpec.Select(item => item.Key.SpecificationAttributeOptionId).ToList();
+ if (!request.LoadFilterableSpecificationAttributeOptionIds ||
+ _catalogSettings.IgnoreFilterableSpecAttributeOption)
+ return (products, filterableSpecificationAttributeOptionIds);
+ {
+ var filterSpecExists =
+ querySpecification.Where(x => x.ProductSpecificationAttributes.Any(x => x.AllowFiltering));
- filterableSpecificationAttributeOptionIds = specification.ToList();
- }
+ var spec = from p in filterSpecExists
+ from item in p.ProductSpecificationAttributes
+ select item;
- return (products, filterableSpecificationAttributeOptionIds);
+ var groupQuerySpec = spec.Where(x => x.AllowFiltering).GroupBy(x =>
+ new { x.SpecificationAttributeOptionId }).ToList();
+ IList<string> specification =
+ groupQuerySpec.Select(item => item.Key.SpecificationAttributeOptionId).ToList();
- #endregion
+ filterableSpecificationAttributeOptionIds = specification.ToList();
}
- private IQueryable<Product> FilterQueryable(GetSearchProductsQuery request, IQueryable<Product> query, string[] allowedCustomerGroupsIds)
+ return (products, filterableSpecificationAttributeOptionIds);
+
+ #endregion
+ }
+
+ private IQueryable<Product> FilterQueryable(GetSearchProductsQuery request, IQueryable<Product> query,
+ string[] allowedCustomerGroupsIds)
+ {
+ //category filtering
+ if (request.CategoryIds != null && request.CategoryIds.Any())
{
- //category filtering
- if (request.CategoryIds != null && request.CategoryIds.Any())
- {
- if (request.FeaturedProducts.HasValue)
- {
- query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)
- && y.IsFeaturedProduct ==
- request.FeaturedProducts));
- }
- else
- {
- query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)));
- }
- }
+ if (request.FeaturedProducts.HasValue)
+ query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)
+ && y.IsFeaturedProduct ==
+ request.FeaturedProducts));
+ else
+ query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)));
+ }
- //brand
- if (!string.IsNullOrEmpty(request.BrandId))
- {
- query = query.Where(x => x.BrandId == request.BrandId);
- }
+ //brand
+ if (!string.IsNullOrEmpty(request.BrandId)) query = query.Where(x => x.BrandId == request.BrandId);
- //collection filtering
- if (!string.IsNullOrEmpty(request.CollectionId))
- {
- if (request.FeaturedProducts.HasValue)
- {
- query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId
- && y.IsFeaturedProduct ==
- request.FeaturedProducts));
- }
- else
- {
- query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId));
- }
- }
+ //collection filtering
+ if (!string.IsNullOrEmpty(request.CollectionId))
+ {
+ if (request.FeaturedProducts.HasValue)
+ query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId
+ && y.IsFeaturedProduct ==
+ request.FeaturedProducts));
+ else
+ query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId));
+ }
- if (!request.OverridePublished.HasValue)
- {
- //process according to "showHidden"
- if (!request.ShowHidden)
- {
- query = query.Where(p => p.Published);
- }
- }
- else if (request.OverridePublished.Value)
- {
- //published only
- query = query.Where(p => p.Published);
- }
- else if (!request.OverridePublished.Value)
- {
- //unpublished only
- query = query.Where(p => !p.Published);
- }
+ if (!request.OverridePublished.HasValue)
+ {
+ //process according to "showHidden"
+ if (!request.ShowHidden) query = query.Where(p => p.Published);
+ }
+ else if (request.OverridePublished.Value)
+ {
+ //published only
+ query = query.Where(p => p.Published);
+ }
+ else if (!request.OverridePublished.Value)
+ {
+ //unpublished only
+ query = query.Where(p => !p.Published);
+ }
- if (request.VisibleIndividuallyOnly)
- {
- query = query.Where(p => p.VisibleIndividually);
- }
+ if (request.VisibleIndividuallyOnly) query = query.Where(p => p.VisibleIndividually);
- if (request.ProductType.HasValue)
- {
- query = query.Where(p => p.ProductTypeId == request.ProductType);
- }
+ if (request.ProductType.HasValue) query = query.Where(p => p.ProductTypeId == request.ProductType);
- if (request.ShowOnHomePage.HasValue)
- {
- query = query.Where(p => p.ShowOnHomePage == request.ShowOnHomePage.Value);
- }
+ if (request.ShowOnHomePage.HasValue) query = query.Where(p => p.ShowOnHomePage == request.ShowOnHomePage.Value);
- var nowUtc = DateTime.UtcNow;
- if (request.PriceMin.HasValue)
- {
- query = query.Where(p => p.Price >= request.PriceMin.Value);
- }
+ var nowUtc = DateTime.UtcNow;
+ if (request.PriceMin.HasValue) query = query.Where(p => p.Price >= request.PriceMin.Value);
- if (request.PriceMax.HasValue)
- {
- //max price
- query = query.Where(p => p.Price <= request.PriceMax.Value);
- }
+ if (request.PriceMax.HasValue)
+ //max price
+ query = query.Where(p => p.Price <= request.PriceMax.Value);
- if (request.Rating.HasValue)
- {
- //avg rating
- query = query.Where(p => p.AvgRating >= request.Rating);
- }
+ if (request.Rating.HasValue)
+ //avg rating
+ query = query.Where(p => p.AvgRating >= request.Rating);
- if (!request.ShowHidden && !_catalogSettings.IgnoreFilterableAvailableStartEndDateTime)
- {
- query = query.Where(p =>
- (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&
- (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));
- }
+ if (!request.ShowHidden && !_catalogSettings.IgnoreFilterableAvailableStartEndDateTime)
+ query = query.Where(p =>
+ (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&
+ (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));
- if (request.MarkedAsNewOnly)
- {
- query = query.Where(p => p.MarkAsNew);
- query = query.Where(p =>
- (!p.MarkAsNewStartDateTimeUtc.HasValue || p.MarkAsNewStartDateTimeUtc.Value < nowUtc) &&
- (!p.MarkAsNewEndDateTimeUtc.HasValue || p.MarkAsNewEndDateTimeUtc.Value > nowUtc));
- }
+ if (request.MarkedAsNewOnly)
+ {
+ query = query.Where(p => p.MarkAsNew);
+ query = query.Where(p =>
+ (!p.MarkAsNewStartDateTimeUtc.HasValue || p.MarkAsNewStartDateTimeUtc.Value < nowUtc) &&
+ (!p.MarkAsNewEndDateTimeUtc.HasValue || p.MarkAsNewEndDateTimeUtc.Value > nowUtc));
+ }
- //searching by keyword
- if (!string.IsNullOrWhiteSpace(request.Keywords))
- {
- if (!request.SearchDescriptions)
- query = query.Where(p =>
- p.Name.ToLower().Contains(request.Keywords.ToLower())
- ||
- p.Locales.Any(x =>
- x.LocaleKey == "Name" && x.LocaleValue != null &&
- x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))
- ||
- (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))
- );
- else
- {
- query = query.Where(p =>
- (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower()))
- ||
- (p.ShortDescription != null &&
- p.ShortDescription.ToLower().Contains(request.Keywords.ToLower()))
- ||
- (p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower()))
- ||
- p.Locales.Any(x =>
- x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))
- ||
- (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))
- );
- }
- }
+ //searching by keyword
+ if (!string.IsNullOrWhiteSpace(request.Keywords))
+ {
+ if (!request.SearchDescriptions)
+ query = query.Where(p =>
+ p.Name.ToLower().Contains(request.Keywords.ToLower())
+ ||
+ p.Locales.Any(x =>
+ x.LocaleKey == "Name" && x.LocaleValue != null &&
+ x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))
+ ||
+ (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))
+ );
+ else
+ query = query.Where(p =>
+ (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower()))
+ ||
+ (p.ShortDescription != null &&
+ p.ShortDescription.ToLower().Contains(request.Keywords.ToLower()))
+ ||
+ (p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower()))
+ ||
+ p.Locales.Any(x =>
+ x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))
+ ||
+ (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))
+ );
+ }
- if (!request.ShowHidden && !_accessControlConfig.IgnoreAcl)
- {
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
+ if (!request.ShowHidden && !_accessControlConfig.IgnoreAcl)
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
- if (!string.IsNullOrEmpty(request.StoreId) && !_accessControlConfig.IgnoreStoreLimitations)
- {
- query = query.Where(x => x.Stores.Any(y => y == request.StoreId) || !x.LimitedToStores);
- }
+ if (!string.IsNullOrEmpty(request.StoreId) && !_accessControlConfig.IgnoreStoreLimitations)
+ query = query.Where(x => x.Stores.Any(y => y == request.StoreId) || !x.LimitedToStores);
- //vendor filtering
- if (!string.IsNullOrEmpty(request.VendorId))
- {
- query = query.Where(x => x.VendorId == request.VendorId);
- }
+ //vendor filtering
+ if (!string.IsNullOrEmpty(request.VendorId)) query = query.Where(x => x.VendorId == request.VendorId);
- //warehouse filtering
- if (!string.IsNullOrEmpty(request.WarehouseId))
- {
- query = query.Where(x =>
- (x.UseMultipleWarehouses &&
- x.ProductWarehouseInventory.Any(y => y.WarehouseId == request.WarehouseId))
- || (!x.UseMultipleWarehouses && x.WarehouseId == request.WarehouseId));
- }
+ //warehouse filtering
+ if (!string.IsNullOrEmpty(request.WarehouseId))
+ query = query.Where(x =>
+ (x.UseMultipleWarehouses &&
+ x.ProductWarehouseInventory.Any(y => y.WarehouseId == request.WarehouseId))
+ || (!x.UseMultipleWarehouses && x.WarehouseId == request.WarehouseId));
- //tag filtering
- if (!string.IsNullOrEmpty(request.ProductTag))
- {
- query = query.Where(x => x.ProductTags.Any(y => y == request.ProductTag));
- }
+ //tag filtering
+ if (!string.IsNullOrEmpty(request.ProductTag))
+ query = query.Where(x => x.ProductTags.Any(y => y == request.ProductTag));
- return query;
- }
+ return query;
+ }
- private IQueryable<Product> OrderByQueryable(GetSearchProductsQuery request, IQueryable<Product> query)
+ private IQueryable<Product> OrderByQueryable(GetSearchProductsQuery request, IQueryable<Product> query)
+ {
+ switch (request.OrderBy)
{
- switch (request.OrderBy)
- {
- case ProductSortingEnum.Position when request.CategoryIds != null && request.CategoryIds.Any():
- //category position
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory)
- : query.OrderBy(x => x.DisplayOrderCategory);
- break;
- case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.BrandId):
- //brand position
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand)
- : query.OrderBy(x => x.DisplayOrderBrand);
- break;
- case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.CollectionId):
- //collection position
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection)
- : query.OrderBy(x => x.DisplayOrderCollection);
- break;
- case ProductSortingEnum.Position:
- //otherwise sort by name
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)
- : query.OrderBy(x => x.Name);
- break;
- case ProductSortingEnum.NameAsc:
- //Name: A to Z
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)
- : query.OrderBy(x => x.Name);
- break;
- case ProductSortingEnum.NameDesc:
- //Name: Z to A
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name)
- : query.OrderByDescending(x => x.Name);
- break;
- case ProductSortingEnum.PriceAsc:
- //Price: Low to High
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Price)
- : query.OrderBy(x => x.Price);
- break;
- case ProductSortingEnum.PriceDesc:
- //Price: High to Low
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price)
- : query.OrderByDescending(x => x.Price);
- break;
- case ProductSortingEnum.CreatedOn:
- //creation date
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc)
- : query.OrderBy(x => x.CreatedOnUtc);
- break;
- case ProductSortingEnum.OnSale:
- //on sale
- query = query.OrderBy(x => x.OnSale);
-
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale)
- : query.OrderBy(x => x.OnSale);
- break;
- case ProductSortingEnum.MostViewed:
- //most viewed
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed)
- : query.OrderByDescending(x => x.Viewed);
- break;
- case ProductSortingEnum.BestSellers:
- //best seller
- query = query.OrderByDescending(x => x.Sold);
-
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold)
- : query.OrderByDescending(x => x.Sold);
- break;
- case ProductSortingEnum.Rating:
- //most viewed
- query = _catalogSettings.SortingByAvailability
- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.AvgRating)
- : query.OrderByDescending(x => x.AvgRating).ThenByDescending(x => x.ApprovedTotalReviews);
- break;
- }
-
- return query;
+ case ProductSortingEnum.Position when request.CategoryIds != null && request.CategoryIds.Any():
+ //category position
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory)
+ : query.OrderBy(x => x.DisplayOrderCategory);
+ break;
+ case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.BrandId):
+ //brand position
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand)
+ : query.OrderBy(x => x.DisplayOrderBrand);
+ break;
+ case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.CollectionId):
+ //collection position
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection)
+ : query.OrderBy(x => x.DisplayOrderCollection);
+ break;
+ case ProductSortingEnum.Position:
+ //otherwise sort by name
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)
+ : query.OrderBy(x => x.Name);
+ break;
+ case ProductSortingEnum.NameAsc:
+ //Name: A to Z
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)
+ : query.OrderBy(x => x.Name);
+ break;
+ case ProductSortingEnum.NameDesc:
+ //Name: Z to A
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name)
+ : query.OrderByDescending(x => x.Name);
+ break;
+ case ProductSortingEnum.PriceAsc:
+ //Price: Low to High
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Price)
+ : query.OrderBy(x => x.Price);
+ break;
+ case ProductSortingEnum.PriceDesc:
+ //Price: High to Low
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price)
+ : query.OrderByDescending(x => x.Price);
+ break;
+ case ProductSortingEnum.CreatedOn:
+ //creation date
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc)
+ : query.OrderBy(x => x.CreatedOnUtc);
+ break;
+ case ProductSortingEnum.OnSale:
+ //on sale
+ query = query.OrderBy(x => x.OnSale);
+
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale)
+ : query.OrderBy(x => x.OnSale);
+ break;
+ case ProductSortingEnum.MostViewed:
+ //most viewed
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed)
+ : query.OrderByDescending(x => x.Viewed);
+ break;
+ case ProductSortingEnum.BestSellers:
+ //best seller
+ query = query.OrderByDescending(x => x.Sold);
+
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold)
+ : query.OrderByDescending(x => x.Sold);
+ break;
+ case ProductSortingEnum.Rating:
+ //most viewed
+ query = _catalogSettings.SortingByAvailability
+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.AvgRating)
+ : query.OrderByDescending(x => x.AvgRating).ThenByDescending(x => x.ApprovedTotalReviews);
+ break;
}
+
+ return query;
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs
index 85fc5e9b2..dbb2688be 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSuggestedProductsQueryHandler.cs
@@ -1,42 +1,35 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Queries.Catalog;
-using Grand.Infrastructure.Caching;
-using Grand.Infrastructure.Caching.Constants;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Caching.Constants;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetSuggestedProductsQueryHandler : IRequestHandler<GetSuggestedProductsQuery, IList<Product>>
{
- public class GetSuggestedProductsQueryHandler : IRequestHandler<GetSuggestedProductsQuery, IList<Product>>
+ public GetSuggestedProductsQueryHandler(
+ IProductService productService,
+ ICacheBase cacheBase,
+ IRepository<CustomerTagProduct> customerTagProductRepository)
{
- #region Fields
-
- private readonly IProductService _productService;
- private readonly ICacheBase _cacheBase;
- private readonly IRepository<CustomerTagProduct> _customerTagProductRepository;
-
- #endregion
-
- public GetSuggestedProductsQueryHandler(
- IProductService productService,
- ICacheBase cacheBase,
- IRepository<CustomerTagProduct> customerTagProductRepository)
- {
- _productService = productService;
- _cacheBase = cacheBase;
- _customerTagProductRepository = customerTagProductRepository;
- }
-
- public async Task<IList<Product>> Handle(GetSuggestedProductsQuery request, CancellationToken cancellationToken)
- {
- return await _cacheBase.GetAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_TAG, string.Join(",", request.CustomerTagIds)), async () =>
+ _productService = productService;
+ _cacheBase = cacheBase;
+ _customerTagProductRepository = customerTagProductRepository;
+ }
+
+ public async Task<IList<Product>> Handle(GetSuggestedProductsQuery request, CancellationToken cancellationToken)
+ {
+ return await _cacheBase.GetAsync(
+ string.Format(CacheKey.PRODUCTS_CUSTOMER_TAG, string.Join(",", request.CustomerTagIds)), async () =>
{
var query = from cr in _customerTagProductRepository.Table
- where request.CustomerTagIds.Contains(cr.CustomerTagId)
- orderby cr.DisplayOrder
- select cr.ProductId;
+ where request.CustomerTagIds.Contains(cr.CustomerTagId)
+ orderby cr.DisplayOrder
+ select cr.ProductId;
var productIds = query.Take(request.ProductsNumber).ToList();
@@ -44,7 +37,13 @@ namespace Grand.Business.Catalog.Queries.Handlers
return ids.Where(product => product.Published).ToList();
});
-
- }
}
-}
+
+ #region Fields
+
+ private readonly IProductService _productService;
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerTagProduct> _customerTagProductRepository;
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs
index b886cdb6a..93d07b5b2 100644
--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs
+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs
@@ -3,20 +3,21 @@ using Grand.Data;
using Grand.Domain.Vendors;
using MediatR;
-namespace Grand.Business.Catalog.Queries.Handlers
+namespace Grand.Business.Catalog.Queries.Handlers;
+
+public class GetVendorByIdQueryHandler : IRequestHandler<GetVendorByIdQuery, Vendor>
{
- public class GetVendorByIdQueryHandler : IRequestHandler<GetVendorByIdQuery, Vendor>
- {
- private readonly IRepository<Vendor> _vendorRepository;
+ private readonly IRepository<Vendor> _vendorRepository;
- public GetVendorByIdQueryHandler(IRepository<Vendor> vendorRepository)
- {
- _vendorRepository = vendorRepository;
- }
+ public GetVendorByIdQueryHandler(IRepository<Vendor> vendorRepository)
+ {
+ _vendorRepository = vendorRepository;
+ }
- public Task<Vendor> Handle(GetVendorByIdQuery request, CancellationToken cancellationToken)
- {
- return string.IsNullOrWhiteSpace(request.Id) ? Task.FromResult<Vendor>(null) : _vendorRepository.GetByIdAsync(request.Id);
- }
+ public Task<Vendor> Handle(GetVendorByIdQuery request, CancellationToken cancellationToken)
+ {
+ return string.IsNullOrWhiteSpace(request.Id)
+ ? Task.FromResult<Vendor>(null)
+ : _vendorRepository.GetByIdAsync(request.Id);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs
index 407fce196..528ad87f7 100644
--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs
@@ -1,125 +1,123 @@
using Grand.Business.Core.Interfaces.Catalog.Brands;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Brands
+namespace Grand.Business.Catalog.Services.Brands;
+
+/// <summary>
+/// Brand layout service
+/// </summary>
+public class BrandLayoutService : IBrandLayoutService
{
+ #region Ctor
+
/// <summary>
- /// Brand layout service
+ /// Ctor
/// </summary>
- public class BrandLayoutService : IBrandLayoutService
+ /// <param name="brandLayoutRepository">Brand layout repository</param>
+ /// <param name="cacheBase">Cache base</param>
+ /// <param name="mediator">Mediator</param>
+ public BrandLayoutService(IRepository<BrandLayout> brandLayoutRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<BrandLayout> _brandLayoutRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _brandLayoutRepository = brandLayoutRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="brandLayoutRepository">Brand layout repository</param>
- /// <param name="cacheBase">Cache base</param>
- /// <param name="mediator">Mediator</param>
- public BrandLayoutService(IRepository<BrandLayout> brandLayoutRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _brandLayoutRepository = brandLayoutRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
+ private readonly IRepository<BrandLayout> _brandLayoutRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets all brand layouts
- /// </summary>
- /// <returns>Brand layouts</returns>
- public virtual async Task<IList<BrandLayout>> GetAllBrandLayouts()
- {
- return await _cacheBase.GetAsync(CacheKey.BRAND_LAYOUT_ALL, async () =>
- {
- var query = from pt in _brandLayoutRepository.Table
- orderby pt.DisplayOrder
- select pt;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a brand layout
- /// </summary>
- /// <param name="brandLayoutId">Brand layout</param>
- /// <returns>Brand layout</returns>
- public virtual Task<BrandLayout> GetBrandLayoutById(string brandLayoutId)
- {
- var key = string.Format(CacheKey.BRAND_LAYOUT_BY_ID_KEY, brandLayoutId);
- return _cacheBase.GetAsync(key, () => _brandLayoutRepository.GetByIdAsync(brandLayoutId));
- }
-
- /// <summary>
- /// Inserts brand layout
- /// </summary>
- /// <param name="brandLayout">Brand layout</param>
- public virtual async Task InsertBrandLayout(BrandLayout brandLayout)
+ /// <summary>
+ /// Gets all brand layouts
+ /// </summary>
+ /// <returns>Brand layouts</returns>
+ public virtual async Task<IList<BrandLayout>> GetAllBrandLayouts()
+ {
+ return await _cacheBase.GetAsync(CacheKey.BRAND_LAYOUT_ALL, async () =>
{
- ArgumentNullException.ThrowIfNull(brandLayout);
+ var query = from pt in _brandLayoutRepository.Table
+ orderby pt.DisplayOrder
+ select pt;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _brandLayoutRepository.InsertAsync(brandLayout);
+ /// <summary>
+ /// Gets a brand layout
+ /// </summary>
+ /// <param name="brandLayoutId">Brand layout</param>
+ /// <returns>Brand layout</returns>
+ public virtual Task<BrandLayout> GetBrandLayoutById(string brandLayoutId)
+ {
+ var key = string.Format(CacheKey.BRAND_LAYOUT_BY_ID_KEY, brandLayoutId);
+ return _cacheBase.GetAsync(key, () => _brandLayoutRepository.GetByIdAsync(brandLayoutId));
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Inserts brand layout
+ /// </summary>
+ /// <param name="brandLayout">Brand layout</param>
+ public virtual async Task InsertBrandLayout(BrandLayout brandLayout)
+ {
+ ArgumentNullException.ThrowIfNull(brandLayout);
- //event notification
- await _mediator.EntityInserted(brandLayout);
- }
+ await _brandLayoutRepository.InsertAsync(brandLayout);
- /// <summary>
- /// Updates the brand layout
- /// </summary>
- /// <param name="brandLayout">Brand layout</param>
- public virtual async Task UpdateBrandLayout(BrandLayout brandLayout)
- {
- ArgumentNullException.ThrowIfNull(brandLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
- await _brandLayoutRepository.UpdateAsync(brandLayout);
+ //event notification
+ await _mediator.EntityInserted(brandLayout);
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Updates the brand layout
+ /// </summary>
+ /// <param name="brandLayout">Brand layout</param>
+ public virtual async Task UpdateBrandLayout(BrandLayout brandLayout)
+ {
+ ArgumentNullException.ThrowIfNull(brandLayout);
- //event notification
- await _mediator.EntityUpdated(brandLayout);
- }
+ await _brandLayoutRepository.UpdateAsync(brandLayout);
- /// <summary>
- /// Delete brand layout
- /// </summary>
- /// <param name="brandLayout">Brand layout</param>
- public virtual async Task DeleteBrandLayout(BrandLayout brandLayout)
- {
- ArgumentNullException.ThrowIfNull(brandLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
- await _brandLayoutRepository.DeleteAsync(brandLayout);
+ //event notification
+ await _mediator.EntityUpdated(brandLayout);
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Delete brand layout
+ /// </summary>
+ /// <param name="brandLayout">Brand layout</param>
+ public virtual async Task DeleteBrandLayout(BrandLayout brandLayout)
+ {
+ ArgumentNullException.ThrowIfNull(brandLayout);
- //event notification
- await _mediator.EntityDeleted(brandLayout);
- }
+ await _brandLayoutRepository.DeleteAsync(brandLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRAND_LAYOUT_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(brandLayout);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
index 2b77811fb..e4931620d 100644
--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
@@ -1,8 +1,8 @@
using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
@@ -10,165 +10,164 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Brands
+namespace Grand.Business.Catalog.Services.Brands;
+
+/// <summary>
+/// Brand service
+/// </summary>
+public class BrandService : IBrandService
{
+ #region Ctor
+
/// <summary>
- /// Brand service
+ /// Ctor
/// </summary>
- public class BrandService : IBrandService
+ public BrandService(ICacheBase cacheBase,
+ IRepository<Brand> brandRepository,
+ IWorkContext workContext,
+ IMediator mediator, AccessControlConfig accessControlConfig)
{
- #region Fields
-
- private readonly IRepository<Brand> _brandRepository;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public BrandService(ICacheBase cacheBase,
- IRepository<Brand> brandRepository,
- IWorkContext workContext,
- IMediator mediator, AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _brandRepository = brandRepository;
- _workContext = workContext;
- _mediator = mediator;
- _accessControlConfig = accessControlConfig;
- }
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets all brands
- /// </summary>
- /// <param name="brandName">Brand name</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Brands</returns>
- public virtual async Task<IPagedList<Brand>> GetAllBrands(string brandName = "",
- string storeId = "",
- int pageIndex = 0,
- int pageSize = int.MaxValue,
- bool showHidden = false)
- {
- var query = from m in _brandRepository.Table
- select m;
+ _cacheBase = cacheBase;
+ _brandRepository = brandRepository;
+ _workContext = workContext;
+ _mediator = mediator;
+ _accessControlConfig = accessControlConfig;
+ }
+
+ #endregion
+
+ #region Fields
- if (!showHidden)
- query = query.Where(m => m.Published);
- if (!string.IsNullOrWhiteSpace(brandName))
- query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(brandName.ToLower()));
+ private readonly IRepository<Brand> _brandRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+ private readonly AccessControlConfig _accessControlConfig;
- if (!_accessControlConfig.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets all brands
+ /// </summary>
+ /// <param name="brandName">Brand name</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Brands</returns>
+ public virtual async Task<IPagedList<Brand>> GetAllBrands(string brandName = "",
+ string storeId = "",
+ int pageIndex = 0,
+ int pageSize = int.MaxValue,
+ bool showHidden = false)
+ {
+ var query = from m in _brandRepository.Table
+ select m;
+
+ if (!showHidden)
+ query = query.Where(m => m.Published);
+ if (!string.IsNullOrWhiteSpace(brandName))
+ query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(brandName.ToLower()));
+
+ if (!_accessControlConfig.IgnoreAcl ||
+ (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
+ {
+ if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
- if (!showHidden && !_accessControlConfig.IgnoreAcl)
- {
- //Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
-
- }
- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
- {
- //Limited to stores rules
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
+ //Limited to customer groups rules
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
}
- query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
- return await PagedList<Brand>.Create(query, pageIndex, pageSize);
- }
- /// <summary>
- /// Gets a brand
- /// </summary>
- /// <param name="brandId">Brand id</param>
- /// <returns>Brand</returns>
- public virtual Task<Brand> GetBrandById(string brandId)
- {
- var key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId);
- return _cacheBase.GetAsync(key, () => _brandRepository.GetByIdAsync(brandId));
+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
+ //Limited to stores rules
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
}
- /// <summary>
- /// Inserts a brand
- /// </summary>
- /// <param name="brand">Brand</param>
- public virtual async Task InsertBrand(Brand brand)
- {
- ArgumentNullException.ThrowIfNull(brand);
+ query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
+ return await PagedList<Brand>.Create(query, pageIndex, pageSize);
+ }
- await _brandRepository.InsertAsync(brand);
+ /// <summary>
+ /// Gets a brand
+ /// </summary>
+ /// <param name="brandId">Brand id</param>
+ /// <returns>Brand</returns>
+ public virtual Task<Brand> GetBrandById(string brandId)
+ {
+ var key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId);
+ return _cacheBase.GetAsync(key, () => _brandRepository.GetByIdAsync(brandId));
+ }
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
+ /// <summary>
+ /// Inserts a brand
+ /// </summary>
+ /// <param name="brand">Brand</param>
+ public virtual async Task InsertBrand(Brand brand)
+ {
+ ArgumentNullException.ThrowIfNull(brand);
- //event notification
- await _mediator.EntityInserted(brand);
- }
+ await _brandRepository.InsertAsync(brand);
- /// <summary>
- /// Updates the brand
- /// </summary>
- /// <param name="brand">Brand</param>
- public virtual async Task UpdateBrand(Brand brand)
- {
- ArgumentNullException.ThrowIfNull(brand);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
- await _brandRepository.UpdateAsync(brand);
+ //event notification
+ await _mediator.EntityInserted(brand);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
+ /// <summary>
+ /// Updates the brand
+ /// </summary>
+ /// <param name="brand">Brand</param>
+ public virtual async Task UpdateBrand(Brand brand)
+ {
+ ArgumentNullException.ThrowIfNull(brand);
- //event notification
- await _mediator.EntityUpdated(brand);
- }
- /// <summary>
- /// Deletes a brand
- /// </summary>
- /// <param name="brand">Brand</param>
- public virtual async Task DeleteBrand(Brand brand)
- {
- ArgumentNullException.ThrowIfNull(brand);
+ await _brandRepository.UpdateAsync(brand);
- await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
- await _brandRepository.DeleteAsync(brand);
+ //event notification
+ await _mediator.EntityUpdated(brand);
+ }
- //event notification
- await _mediator.EntityDeleted(brand);
+ /// <summary>
+ /// Deletes a brand
+ /// </summary>
+ /// <param name="brand">Brand</param>
+ public virtual async Task DeleteBrand(Brand brand)
+ {
+ ArgumentNullException.ThrowIfNull(brand);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);
- /// <summary>
- /// Gets a discount brand mapping
- /// </summary>
- /// <param name="discountId">Discount id mapping id</param>
- /// <returns>Product brand mapping</returns>
- public virtual async Task<IList<Brand>> GetAllBrandsByDiscount(string discountId)
- {
- var query = from c in _brandRepository.Table
- where c.AppliedDiscounts.Any(x => x == discountId)
- select c;
+ await _brandRepository.DeleteAsync(brand);
- return await Task.FromResult(query.ToList());
- }
+ //event notification
+ await _mediator.EntityDeleted(brand);
+ }
- #endregion
+ /// <summary>
+ /// Gets a discount brand mapping
+ /// </summary>
+ /// <param name="discountId">Discount id mapping id</param>
+ /// <returns>Product brand mapping</returns>
+ public virtual async Task<IList<Brand>> GetAllBrandsByDiscount(string discountId)
+ {
+ var query = from c in _brandRepository.Table
+ where c.AppliedDiscounts.Any(x => x == discountId)
+ select c;
+ return await Task.FromResult(query.ToList());
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs
index e84707fbc..eaa268e59 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs
@@ -1,124 +1,123 @@
using Grand.Business.Core.Interfaces.Catalog.Categories;
-using Grand.Infrastructure.Extensions;
-using Grand.Domain.Catalog;
using Grand.Data;
-using MediatR;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
+using Grand.Infrastructure.Extensions;
+using MediatR;
+
+namespace Grand.Business.Catalog.Services.Categories;
-namespace Grand.Business.Catalog.Services.Categories
+/// <summary>
+/// Category layout service
+/// </summary>
+public class CategoryLayoutService : ICategoryLayoutService
{
+ #region Ctor
+
/// <summary>
- /// Category layout service
+ /// Ctor
/// </summary>
- public class CategoryLayoutService : ICategoryLayoutService
+ /// <param name="categoryLayoutRepository">Category layout repository</param>
+ /// <param name="cacheBase">cache base</param>
+ /// <param name="mediator">Mediator</param>
+ public CategoryLayoutService(IRepository<CategoryLayout> categoryLayoutRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<CategoryLayout> _categoryLayoutRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _categoryLayoutRepository = categoryLayoutRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="categoryLayoutRepository">Category layout repository</param>
- /// <param name="cacheBase">cache base</param>
- /// <param name="mediator">Mediator</param>
- public CategoryLayoutService(IRepository<CategoryLayout> categoryLayoutRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _categoryLayoutRepository = categoryLayoutRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
+ private readonly IRepository<CategoryLayout> _categoryLayoutRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets all existing category layout
- /// </summary>
- /// <returns>Category layouts</returns>
- public virtual async Task<IList<CategoryLayout>> GetAllCategoryLayouts()
- {
- return await _cacheBase.GetAsync(CacheKey.CATEGORY_LAYOUT_ALL, async () =>
- {
- var query = from pt in _categoryLayoutRepository.Table
- orderby pt.DisplayOrder
- select pt;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a specified category layout
- /// </summary>
- /// <param name="categoryLayoutId">Category layout identifier</param>
- /// <returns>Category layout</returns>
- public virtual Task<CategoryLayout> GetCategoryLayoutById(string categoryLayoutId)
- {
- var key = string.Format(CacheKey.CATEGORY_LAYOUT_BY_ID_KEY, categoryLayoutId);
- return _cacheBase.GetAsync(key, () => _categoryLayoutRepository.GetByIdAsync(categoryLayoutId));
- }
-
- /// <summary>
- /// Insert new category layout
- /// </summary>
- /// <param name="categoryLayout">Category layout</param>
- public virtual async Task InsertCategoryLayout(CategoryLayout categoryLayout)
+ /// <summary>
+ /// Gets all existing category layout
+ /// </summary>
+ /// <returns>Category layouts</returns>
+ public virtual async Task<IList<CategoryLayout>> GetAllCategoryLayouts()
+ {
+ return await _cacheBase.GetAsync(CacheKey.CATEGORY_LAYOUT_ALL, async () =>
{
- ArgumentNullException.ThrowIfNull(categoryLayout);
+ var query = from pt in _categoryLayoutRepository.Table
+ orderby pt.DisplayOrder
+ select pt;
+ return await Task.FromResult(query.ToList());
+ });
+ }
+
+ /// <summary>
+ /// Gets a specified category layout
+ /// </summary>
+ /// <param name="categoryLayoutId">Category layout identifier</param>
+ /// <returns>Category layout</returns>
+ public virtual Task<CategoryLayout> GetCategoryLayoutById(string categoryLayoutId)
+ {
+ var key = string.Format(CacheKey.CATEGORY_LAYOUT_BY_ID_KEY, categoryLayoutId);
+ return _cacheBase.GetAsync(key, () => _categoryLayoutRepository.GetByIdAsync(categoryLayoutId));
+ }
- await _categoryLayoutRepository.InsertAsync(categoryLayout);
+ /// <summary>
+ /// Insert new category layout
+ /// </summary>
+ /// <param name="categoryLayout">Category layout</param>
+ public virtual async Task InsertCategoryLayout(CategoryLayout categoryLayout)
+ {
+ ArgumentNullException.ThrowIfNull(categoryLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
+ await _categoryLayoutRepository.InsertAsync(categoryLayout);
- //event notification
- await _mediator.EntityInserted(categoryLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
- /// <summary>
- /// Updates the category layout
- /// </summary>
- /// <param name="categoryLayout">Category layout</param>
- public virtual async Task UpdateCategoryLayout(CategoryLayout categoryLayout)
- {
- ArgumentNullException.ThrowIfNull(categoryLayout);
+ //event notification
+ await _mediator.EntityInserted(categoryLayout);
+ }
- await _categoryLayoutRepository.UpdateAsync(categoryLayout);
+ /// <summary>
+ /// Updates the category layout
+ /// </summary>
+ /// <param name="categoryLayout">Category layout</param>
+ public virtual async Task UpdateCategoryLayout(CategoryLayout categoryLayout)
+ {
+ ArgumentNullException.ThrowIfNull(categoryLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
+ await _categoryLayoutRepository.UpdateAsync(categoryLayout);
- //event notification
- await _mediator.EntityUpdated(categoryLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
- /// <summary>
- /// Delete category layout
- /// </summary>
- /// <param name="categoryLayout">Category layout</param>
- public virtual async Task DeleteCategoryLayout(CategoryLayout categoryLayout)
- {
- ArgumentNullException.ThrowIfNull(categoryLayout);
+ //event notification
+ await _mediator.EntityUpdated(categoryLayout);
+ }
- await _categoryLayoutRepository.DeleteAsync(categoryLayout);
+ /// <summary>
+ /// Delete category layout
+ /// </summary>
+ /// <param name="categoryLayout">Category layout</param>
+ public virtual async Task DeleteCategoryLayout(CategoryLayout categoryLayout)
+ {
+ ArgumentNullException.ThrowIfNull(categoryLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
+ await _categoryLayoutRepository.DeleteAsync(categoryLayout);
- //event notification
- await _mediator.EntityDeleted(categoryLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORY_LAYOUT_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(categoryLayout);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
index aeb1f53c5..d89616dc6 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
@@ -1,10 +1,10 @@
-using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
@@ -12,460 +12,462 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Categories
+namespace Grand.Business.Catalog.Services.Categories;
+
+/// <summary>
+/// Category service
+/// </summary>
+public class CategoryService : ICategoryService
{
+ #region Ctor
+
/// <summary>
- /// Category service
+ /// Ctor
/// </summary>
- public class CategoryService : ICategoryService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="categoryRepository">Category repository</param>
+ /// <param name="workContext">Work context</param>
+ /// <param name="mediator">Mediator</param>
+ /// <param name="aclService">ACL service</param>
+ /// <param name="accessControlConfig"></param>
+ public CategoryService(ICacheBase cacheBase,
+ IRepository<Category> categoryRepository,
+ IWorkContext workContext,
+ IMediator mediator,
+ IAclService aclService,
+ AccessControlConfig accessControlConfig)
{
- #region Fields
-
- private readonly IRepository<Category> _categoryRepository;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
- private readonly IAclService _aclService;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="categoryRepository">Category repository</param>
- /// <param name="workContext">Work context</param>
- /// <param name="mediator">Mediator</param>
- /// <param name="aclService">ACL service</param>
- /// <param name="accessControlConfig"></param>
- public CategoryService(ICacheBase cacheBase,
- IRepository<Category> categoryRepository,
- IWorkContext workContext,
- IMediator mediator,
- IAclService aclService,
- AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _categoryRepository = categoryRepository;
- _workContext = workContext;
- _mediator = mediator;
- _aclService = aclService;
- _accessControlConfig = accessControlConfig;
- }
+ _cacheBase = cacheBase;
+ _categoryRepository = categoryRepository;
+ _workContext = workContext;
+ _mediator = mediator;
+ _aclService = aclService;
+ _accessControlConfig = accessControlConfig;
+ }
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets all categories
- /// </summary>
- /// <param name="parentId">Parent Id</param>
- /// <param name="categoryName">Category name</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Categories</returns>
- public virtual async Task<IPagedList<Category>> GetAllCategories(string parentId = null, string categoryName = "", string storeId = "",
- int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
- {
- var query = from c in _categoryRepository.Table
- select c;
+ #endregion
- if (!showHidden)
- query = query.Where(c => c.Published);
- if (!string.IsNullOrWhiteSpace(categoryName))
- query = query.Where(m => m.Name.ToLowerInvariant().Contains(categoryName.ToLowerInvariant()));
-
- if (parentId != null)
- query = query.Where(m => m.ParentCategoryId == parentId);
+ #region Fields
- if (!_accessControlConfig.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
- {
- if (!showHidden && !_accessControlConfig.IgnoreAcl)
- {
- //Limited to customer group (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
- {
- //Limited to stores rule
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
- }
+ private readonly IRepository<Category> _categoryRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+ private readonly IAclService _aclService;
+ private readonly AccessControlConfig _accessControlConfig;
- query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Name);
+ #endregion
- //pagination
- return await Task.FromResult(new PagedList<Category>(query, pageIndex, pageSize));
- }
+ #region Methods
- /// <summary>
- /// Gets categories for menu
- /// </summary>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetMenuCategories()
- {
+ /// <summary>
+ /// Gets all categories
+ /// </summary>
+ /// <param name="parentId">Parent Id</param>
+ /// <param name="categoryName">Category name</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Categories</returns>
+ public virtual async Task<IPagedList<Category>> GetAllCategories(string parentId = null, string categoryName = "",
+ string storeId = "",
+ int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ {
+ var query = from c in _categoryRepository.Table
+ select c;
- var query = from c in _categoryRepository.Table
- select c;
+ if (!showHidden)
+ query = query.Where(c => c.Published);
+ if (!string.IsNullOrWhiteSpace(categoryName))
+ query = query.Where(m => m.Name.ToLowerInvariant().Contains(categoryName.ToLowerInvariant()));
- query = query.Where(c => c.Published && c.IncludeInMenu);
+ if (parentId != null)
+ query = query.Where(m => m.ParentCategoryId == parentId);
- switch (_accessControlConfig.IgnoreAcl)
+ if (!_accessControlConfig.IgnoreAcl ||
+ (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
+ {
+ if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
- case true when
- string.IsNullOrEmpty(_workContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
- return await Task.FromResult(query.ToList());
- case false:
- {
- //Limited to customer group (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- break;
- }
+ //Limited to customer group (access control list)
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
}
- if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
- {
+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
//Limited to stores rule
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
select p;
- }
- return await Task.FromResult(query.ToList());
}
- /// <summary>
- /// Gets all categories filtered by parent category identifier
- /// </summary>
- /// <param name="parentCategoryId">Parent category identifier</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <param name="includeAllLevels">A value that indicates if we should load all child levels</param>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryId(string parentCategoryId = "",
- bool showHidden = false, bool includeAllLevels = false)
- {
- var storeId = _workContext.CurrentStore.Id;
- var customer = _workContext.CurrentCustomer;
- var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden, customer.Id, storeId, includeAllLevels);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = _categoryRepository.Table.Where(c => c.ParentCategoryId == parentCategoryId);
- if (!showHidden)
- query = query.Where(c => c.Published);
+ query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Name);
- if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
- {
- if (!_accessControlConfig.IgnoreAcl)
- {
- //Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
- if (!_accessControlConfig.IgnoreStoreLimitations)
- {
- //Limited to stores rules
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
+ //pagination
+ return await Task.FromResult(new PagedList<Category>(query, pageIndex, pageSize));
+ }
- }
- var categories = query.OrderBy(x => x.DisplayOrder).ToList();
- if (!includeAllLevels) return categories;
- var childCategories = new List<Category>();
- //add child levels
- foreach (var category in categories)
- {
- childCategories.AddRange(await GetAllCategoriesByParentCategoryId(category.Id, showHidden, true));
- }
- categories.AddRange(childCategories);
- return categories;
- });
- }
+ /// <summary>
+ /// Gets categories for menu
+ /// </summary>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetMenuCategories()
+ {
+ var query = from c in _categoryRepository.Table
+ select c;
+
+ query = query.Where(c => c.Published && c.IncludeInMenu);
- /// <summary>
- /// Gets all categories that should be displayed on the home page
- /// </summary>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetAllCategoriesDisplayedOnHomePage(bool showHidden = false)
+ switch (_accessControlConfig.IgnoreAcl)
{
- var query = _categoryRepository.Table
- .Where(x => x.Published && x.ShowOnHomePage)
- .OrderBy(x => x.DisplayOrder);
- var categories = await Task.FromResult(query.ToList());
- if (!showHidden)
+ case true when
+ string.IsNullOrEmpty(_workContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
+ return await Task.FromResult(query.ToList());
+ case false:
{
- categories = categories
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) && _aclService.Authorize(c, _workContext.CurrentStore.Id))
- .ToList();
+ //Limited to customer group (access control list)
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
+ break;
}
-
- return categories;
}
- /// <summary>
- /// Gets all featured products from categories that should be displayed on the home page
- /// </summary>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetAllCategoriesFeaturedProductsOnHomePage(bool showHidden = false)
- {
- var query = _categoryRepository.Table
- .Where(x => x.Published && x.FeaturedProductsOnHomePage)
- .OrderBy(x => x.DisplayOrder);
+ if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
+ //Limited to stores rule
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ select p;
+ return await Task.FromResult(query.ToList());
+ }
- var categories = await Task.FromResult(query.ToList());
+ /// <summary>
+ /// Gets all categories filtered by parent category identifier
+ /// </summary>
+ /// <param name="parentCategoryId">Parent category identifier</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <param name="includeAllLevels">A value that indicates if we should load all child levels</param>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryId(string parentCategoryId = "",
+ bool showHidden = false, bool includeAllLevels = false)
+ {
+ var storeId = _workContext.CurrentStore.Id;
+ var customer = _workContext.CurrentCustomer;
+ var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden,
+ customer.Id, storeId, includeAllLevels);
+ return await _cacheBase.GetAsync(key, async () =>
+ {
+ var query = _categoryRepository.Table.Where(c => c.ParentCategoryId == parentCategoryId);
if (!showHidden)
+ query = query.Where(c => c.Published);
+
+ if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
{
- categories = categories
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) && _aclService.Authorize(c, _workContext.CurrentStore.Id))
- .ToList();
+ if (!_accessControlConfig.IgnoreAcl)
+ {
+ //Limited to customer groups rules
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
+ }
+
+ if (!_accessControlConfig.IgnoreStoreLimitations)
+ //Limited to stores rules
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
}
- return categories;
- }
- /// <summary>
- /// Gets all categories displayed in the search box
- /// </summary>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetAllCategoriesSearchBox()
- {
- var query = _categoryRepository.Table
- .Where(x => x.Published && x.ShowOnSearchBox)
- .OrderBy(x => x.SearchBoxDisplayOrder);
+ var categories = query.OrderBy(x => x.DisplayOrder).ToList();
+ if (!includeAllLevels) return categories;
+ var childCategories = new List<Category>();
+ //add child levels
+ foreach (var category in categories)
+ childCategories.AddRange(await GetAllCategoriesByParentCategoryId(category.Id, showHidden, true));
+ categories.AddRange(childCategories);
+ return categories;
+ });
+ }
- var categories = (await Task.FromResult(query.ToList()))
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) && _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ /// <summary>
+ /// Gets all categories that should be displayed on the home page
+ /// </summary>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetAllCategoriesDisplayedOnHomePage(bool showHidden = false)
+ {
+ var query = _categoryRepository.Table
+ .Where(x => x.Published && x.ShowOnHomePage)
+ .OrderBy(x => x.DisplayOrder);
+ var categories = await Task.FromResult(query.ToList());
+ if (!showHidden)
+ categories = categories
+ .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContext.CurrentStore.Id))
.ToList();
- return categories;
- }
+ return categories;
+ }
- /// <summary>
- /// Get category breadcrumb
- /// </summary>
- /// <param name="category">Category</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Category breadcrumb </returns>
- public virtual async Task<IList<Category>> GetCategoryBreadCrumb(Category category, bool showHidden = false)
- {
- var result = new List<Category>();
+ /// <summary>
+ /// Gets all featured products from categories that should be displayed on the home page
+ /// </summary>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetAllCategoriesFeaturedProductsOnHomePage(bool showHidden = false)
+ {
+ var query = _categoryRepository.Table
+ .Where(x => x.Published && x.FeaturedProductsOnHomePage)
+ .OrderBy(x => x.DisplayOrder);
+
+ var categories = await Task.FromResult(query.ToList());
+ if (!showHidden)
+ categories = categories
+ .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .ToList();
+ return categories;
+ }
- //used to avoid circular references
- var alreadyProcessedCategoryIds = new List<string>();
+ /// <summary>
+ /// Gets all categories displayed in the search box
+ /// </summary>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetAllCategoriesSearchBox()
+ {
+ var query = _categoryRepository.Table
+ .Where(x => x.Published && x.ShowOnSearchBox)
+ .OrderBy(x => x.SearchBoxDisplayOrder);
- while (category != null && //not null
- (showHidden || category.Published) && //published
- (showHidden || _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
- (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
- !alreadyProcessedCategoryIds.Contains(category.Id))
- {
- result.Add(category);
+ var categories = (await Task.FromResult(query.ToList()))
+ .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .ToList();
- alreadyProcessedCategoryIds.Add(category.Id);
+ return categories;
+ }
- category = await GetCategoryById(category.ParentCategoryId);
- }
- result.Reverse();
- return result;
- }
+ /// <summary>
+ /// Get category breadcrumb
+ /// </summary>
+ /// <param name="category">Category</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Category breadcrumb </returns>
+ public virtual async Task<IList<Category>> GetCategoryBreadCrumb(Category category, bool showHidden = false)
+ {
+ var result = new List<Category>();
- /// <summary>
- /// Get category breadcrumb
- /// </summary>
- /// <param name="category">Category</param>
- /// <param name="allCategories">All categories</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Category breadcrumb </returns>
- public virtual IList<Category> GetCategoryBreadCrumb(Category category, IList<Category> allCategories, bool showHidden = false)
+ //used to avoid circular references
+ var alreadyProcessedCategoryIds = new List<string>();
+
+ while (category != null && //not null
+ (showHidden || category.Published) && //published
+ (showHidden ||
+ _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
+ (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
+ !alreadyProcessedCategoryIds.Contains(category.Id))
{
- var result = new List<Category>();
+ result.Add(category);
- //used to avoid circular references
- var alreadyProcessedCategoryIds = new List<string>();
+ alreadyProcessedCategoryIds.Add(category.Id);
- while (category != null && //not null
- (showHidden || category.Published) && //published
- (showHidden || _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
- (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
- !alreadyProcessedCategoryIds.Contains(category.Id)) //avoid circular references
- {
- result.Add(category);
+ category = await GetCategoryById(category.ParentCategoryId);
+ }
- alreadyProcessedCategoryIds.Add(category.Id);
+ result.Reverse();
+ return result;
+ }
- category = (from c in allCategories
- where c.Id == category.ParentCategoryId
- select c).FirstOrDefault();
- }
- result.Reverse();
- return result;
- }
+ /// <summary>
+ /// Get category breadcrumb
+ /// </summary>
+ /// <param name="category">Category</param>
+ /// <param name="allCategories">All categories</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Category breadcrumb </returns>
+ public virtual IList<Category> GetCategoryBreadCrumb(Category category, IList<Category> allCategories,
+ bool showHidden = false)
+ {
+ var result = new List<Category>();
+
+ //used to avoid circular references
+ var alreadyProcessedCategoryIds = new List<string>();
- /// <summary>
- /// Get formatted category breadcrumb
- /// Note: ACL and store acl are ignored
- /// </summary>
- /// <param name="category">Category</param>
- /// <param name="separator">Separator</param>
- /// <param name="languageId">Language ID</param>
- /// <returns>Formatted breadcrumb</returns>
- public virtual async Task<string> GetFormattedBreadCrumb(Category category, string separator = ">>", string languageId = "")
+ while (category != null && //not null
+ (showHidden || category.Published) && //published
+ (showHidden ||
+ _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
+ (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
+ !alreadyProcessedCategoryIds.Contains(category.Id)) //avoid circular references
{
- var result = string.Empty;
+ result.Add(category);
- var breadcrumb = await GetCategoryBreadCrumb(category, true);
- for (var i = 0; i <= breadcrumb.Count - 1; i++)
- {
- var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);
- result = string.IsNullOrEmpty(result)
- ? categoryName
- : $"{result} {separator} {categoryName}";
- }
+ alreadyProcessedCategoryIds.Add(category.Id);
- return result;
+ category = (from c in allCategories
+ where c.Id == category.ParentCategoryId
+ select c).FirstOrDefault();
}
- /// <summary>
- /// Get formatted category breadcrumb
- /// Note: ACL and store acl are ignored
- /// </summary>
- /// <param name="category">Category</param>
- /// <param name="allCategories">All categories</param>
- /// <param name="separator">Separator</param>
- /// <param name="languageId">Language ID</param>
- /// <returns>Formatted breadcrumb</returns>
- public virtual string GetFormattedBreadCrumb(Category category,
- IList<Category> allCategories, string separator = ">>", string languageId = "")
- {
- var result = string.Empty;
- var breadcrumb = GetCategoryBreadCrumb(category, allCategories, true);
- for (var i = 0; i <= breadcrumb.Count - 1; i++)
- {
- var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);
- result = string.IsNullOrEmpty(result)
- ? categoryName
- : $"{result} {separator} {categoryName}";
- }
+ result.Reverse();
+ return result;
+ }
- return result;
- }
+ /// <summary>
+ /// Get formatted category breadcrumb
+ /// Note: ACL and store acl are ignored
+ /// </summary>
+ /// <param name="category">Category</param>
+ /// <param name="separator">Separator</param>
+ /// <param name="languageId">Language ID</param>
+ /// <returns>Formatted breadcrumb</returns>
+ public virtual async Task<string> GetFormattedBreadCrumb(Category category, string separator = ">>",
+ string languageId = "")
+ {
+ var result = string.Empty;
- /// <summary>
- /// Gets all categories by discount id
- /// </summary>
- /// <returns>Categories</returns>
- public virtual async Task<IList<Category>> GetAllCategoriesByDiscount(string discountId)
+ var breadcrumb = await GetCategoryBreadCrumb(category, true);
+ for (var i = 0; i <= breadcrumb.Count - 1; i++)
{
- var query = from c in _categoryRepository.Table
- where c.AppliedDiscounts.Any(x => x == discountId)
- select c;
-
- return await Task.FromResult(query.ToList());
+ var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);
+ result = string.IsNullOrEmpty(result)
+ ? categoryName
+ : $"{result} {separator} {categoryName}";
}
- /// <summary>
- /// Gets a category
- /// </summary>
- /// <param name="categoryId">Category identifier</param>
- /// <returns>Category</returns>
- public virtual async Task<Category> GetCategoryById(string categoryId)
+ return result;
+ }
+
+ /// <summary>
+ /// Get formatted category breadcrumb
+ /// Note: ACL and store acl are ignored
+ /// </summary>
+ /// <param name="category">Category</param>
+ /// <param name="allCategories">All categories</param>
+ /// <param name="separator">Separator</param>
+ /// <param name="languageId">Language ID</param>
+ /// <returns>Formatted breadcrumb</returns>
+ public virtual string GetFormattedBreadCrumb(Category category,
+ IList<Category> allCategories, string separator = ">>", string languageId = "")
+ {
+ var result = string.Empty;
+
+ var breadcrumb = GetCategoryBreadCrumb(category, allCategories, true);
+ for (var i = 0; i <= breadcrumb.Count - 1; i++)
{
- var key = string.Format(CacheKey.CATEGORIES_BY_ID_KEY, categoryId);
- return await _cacheBase.GetAsync(key, () => _categoryRepository.GetByIdAsync(categoryId));
+ var categoryName = breadcrumb[i].GetTranslation(x => x.Name, languageId);
+ result = string.IsNullOrEmpty(result)
+ ? categoryName
+ : $"{result} {separator} {categoryName}";
}
- /// <summary>
- /// Inserts category
- /// </summary>
- /// <param name="category">Category</param>
- public virtual async Task InsertCategory(Category category)
- {
- ArgumentNullException.ThrowIfNull(category);
+ return result;
+ }
- await _categoryRepository.InsertAsync(category);
+ /// <summary>
+ /// Gets all categories by discount id
+ /// </summary>
+ /// <returns>Categories</returns>
+ public virtual async Task<IList<Category>> GetAllCategoriesByDiscount(string discountId)
+ {
+ var query = from c in _categoryRepository.Table
+ where c.AppliedDiscounts.Any(x => x == discountId)
+ select c;
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ return await Task.FromResult(query.ToList());
+ }
- //event notification
- await _mediator.EntityInserted(category);
- }
+ /// <summary>
+ /// Gets a category
+ /// </summary>
+ /// <param name="categoryId">Category identifier</param>
+ /// <returns>Category</returns>
+ public virtual async Task<Category> GetCategoryById(string categoryId)
+ {
+ var key = string.Format(CacheKey.CATEGORIES_BY_ID_KEY, categoryId);
+ return await _cacheBase.GetAsync(key, () => _categoryRepository.GetByIdAsync(categoryId));
+ }
- /// <summary>
- /// Updates the category
- /// </summary>
- /// <param name="category">Category</param>
- public virtual async Task UpdateCategory(Category category)
- {
- ArgumentNullException.ThrowIfNull(category);
- if (string.IsNullOrEmpty(category.ParentCategoryId))
- category.ParentCategoryId = "";
+ /// <summary>
+ /// Inserts category
+ /// </summary>
+ /// <param name="category">Category</param>
+ public virtual async Task InsertCategory(Category category)
+ {
+ ArgumentNullException.ThrowIfNull(category);
- //validate category hierarchy
- var parentCategory = await GetCategoryById(category.ParentCategoryId);
- while (parentCategory != null)
- {
- if (category.Id == parentCategory.Id)
- {
- category.ParentCategoryId = "";
- break;
- }
- parentCategory = await GetCategoryById(parentCategory.ParentCategoryId);
- }
+ await _categoryRepository.InsertAsync(category);
- await _categoryRepository.UpdateAsync(category);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityInserted(category);
+ }
- //event notification
- await _mediator.EntityUpdated(category);
- }
- /// <summary>
- /// Delete category
- /// </summary>
- /// <param name="category">Category</param>
- public virtual async Task DeleteCategory(Category category)
- {
- ArgumentNullException.ThrowIfNull(category);
+ /// <summary>
+ /// Updates the category
+ /// </summary>
+ /// <param name="category">Category</param>
+ public virtual async Task UpdateCategory(Category category)
+ {
+ ArgumentNullException.ThrowIfNull(category);
+ if (string.IsNullOrEmpty(category.ParentCategoryId))
+ category.ParentCategoryId = "";
- //reset a "Parent category" property of all child subcategories
- var subcategories = await GetAllCategoriesByParentCategoryId(category.Id, true);
- foreach (var subcategory in subcategories)
+ //validate category hierarchy
+ var parentCategory = await GetCategoryById(category.ParentCategoryId);
+ while (parentCategory != null)
+ {
+ if (category.Id == parentCategory.Id)
{
- subcategory.ParentCategoryId = "";
- await UpdateCategory(subcategory);
+ category.ParentCategoryId = "";
+ break;
}
- await _categoryRepository.DeleteAsync(category);
+ parentCategory = await GetCategoryById(parentCategory.ParentCategoryId);
+ }
+
+ await _categoryRepository.UpdateAsync(category);
+
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityUpdated(category);
+ }
+
+ /// <summary>
+ /// Delete category
+ /// </summary>
+ /// <param name="category">Category</param>
+ public virtual async Task DeleteCategory(Category category)
+ {
+ ArgumentNullException.ThrowIfNull(category);
- //event notification
- await _mediator.EntityDeleted(category);
+ //reset a "Parent category" property of all child subcategories
+ var subcategories = await GetAllCategoriesByParentCategoryId(category.Id, true);
+ foreach (var subcategory in subcategories)
+ {
+ subcategory.ParentCategoryId = "";
+ await UpdateCategory(subcategory);
}
- #endregion
+ await _categoryRepository.DeleteAsync(category);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);
+
+ //event notification
+ await _mediator.EntityDeleted(category);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
index e4c90c998..d0b7571e8 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
@@ -1,9 +1,9 @@
using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
@@ -11,147 +11,145 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Categories
+namespace Grand.Business.Catalog.Services.Categories;
+
+public class ProductCategoryService : IProductCategoryService
{
- public class ProductCategoryService : IProductCategoryService
+ private readonly AccessControlConfig _accessControlConfig;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
+ private readonly IRepository<Product> _productRepository;
+ private readonly IWorkContext _workContext;
+
+ public ProductCategoryService(
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase,
+ IWorkContext workContext,
+ IMediator mediator, AccessControlConfig accessControlConfig)
{
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
- private readonly AccessControlConfig _accessControlConfig;
-
- public ProductCategoryService(
- IRepository<Product> productRepository,
- ICacheBase cacheBase,
- IWorkContext workContext,
- IMediator mediator, AccessControlConfig accessControlConfig)
- {
- _productRepository = productRepository;
- _cacheBase = cacheBase;
- _workContext = workContext;
- _mediator = mediator;
- _accessControlConfig = accessControlConfig;
- }
-
- /// <summary>
- /// Gets product category mapping collection
- /// </summary>
- /// <param name="categoryId">Category identifier</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Product a category mapping collection</returns>
- public virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCategoryId(string categoryId,
- int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ _productRepository = productRepository;
+ _cacheBase = cacheBase;
+ _workContext = workContext;
+ _mediator = mediator;
+ _accessControlConfig = accessControlConfig;
+ }
+
+ /// <summary>
+ /// Gets product category mapping collection
+ /// </summary>
+ /// <param name="categoryId">Category identifier</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Product a category mapping collection</returns>
+ public virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCategoryId(string categoryId,
+ int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ {
+ if (string.IsNullOrEmpty(categoryId))
+ return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);
+
+ var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex,
+ pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);
+ return await _cacheBase.GetAsync(key, () =>
{
- if (string.IsNullOrEmpty(categoryId))
- return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);
+ var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));
- var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);
- return await _cacheBase.GetAsync(key, () =>
+ if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
{
- var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));
+ if (!_accessControlConfig.IgnoreAcl)
+ {
+ //Limited to customer groups
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
+ }
- if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
+ if (!_accessControlConfig.IgnoreStoreLimitations)
{
- if (!_accessControlConfig.IgnoreAcl)
- {
- //Limited to customer groups
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
- if (!_accessControlConfig.IgnoreStoreLimitations)
- {
- //Limited to stores
- var currentStoreId = _workContext.CurrentStore.Id;
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(currentStoreId)
- select p;
-
- }
+ //Limited to stores
+ var currentStoreId = _workContext.CurrentStore.Id;
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(currentStoreId)
+ select p;
+ }
+ }
+
+ var queryProductCategories = from prod in query
+ from pc in prod.ProductCategories
+ select new ProductsCategory {
+ CategoryId = pc.CategoryId,
+ DisplayOrder = pc.DisplayOrder,
+ Id = pc.Id,
+ ProductId = prod.Id,
+ IsFeaturedProduct = pc.IsFeaturedProduct
+ };
+
+ queryProductCategories = from pm in queryProductCategories
+ where pm.CategoryId == categoryId
+ orderby pm.DisplayOrder
+ select pm;
+
+ return Task.FromResult(new PagedList<ProductsCategory>(queryProductCategories, pageIndex, pageSize));
+ });
+ }
- }
- var queryProductCategories = from prod in query
- from pc in prod.ProductCategories
- select new ProductsCategory
- {
- CategoryId = pc.CategoryId,
- DisplayOrder = pc.DisplayOrder,
- Id = pc.Id,
- ProductId = prod.Id,
- IsFeaturedProduct = pc.IsFeaturedProduct
- };
-
- queryProductCategories = from pm in queryProductCategories
- where pm.CategoryId == categoryId
- orderby pm.DisplayOrder
- select pm;
-
- return Task.FromResult(new PagedList<ProductsCategory>(queryProductCategories, pageIndex, pageSize));
- });
- }
-
-
- /// <summary>
- /// Inserts a product category
- /// </summary>
- /// <param name="productCategory">>Product category mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductCategory(ProductCategory productCategory, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCategory);
+ /// <summary>
+ /// Inserts a product category
+ /// </summary>
+ /// <param name="productCategory">>Product category mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductCategory(ProductCategory productCategory, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCategory);
- await _productRepository.AddToSet(productId, x => x.ProductCategories, productCategory);
+ await _productRepository.AddToSet(productId, x => x.ProductCategories, productCategory);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityInserted(productCategory);
- }
+ //event notification
+ await _mediator.EntityInserted(productCategory);
+ }
- /// <summary>
- /// Updates the associated product category
- /// </summary>
- /// <param name="productCategory">>Product category mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateProductCategory(ProductCategory productCategory, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCategory);
-
- await _productRepository.UpdateToSet(productId, x => x.ProductCategories, z => z.Id, productCategory.Id, productCategory);
-
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
-
- //event notification
- await _mediator.EntityUpdated(productCategory);
- }
- /// <summary>
- /// Deletes a associated product category
- /// </summary>
- /// <param name="productCategory">Product category</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductCategory(ProductCategory productCategory, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCategory);
+ /// <summary>
+ /// Updates the associated product category
+ /// </summary>
+ /// <param name="productCategory">>Product category mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateProductCategory(ProductCategory productCategory, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCategory);
+
+ await _productRepository.UpdateToSet(productId, x => x.ProductCategories, z => z.Id, productCategory.Id,
+ productCategory);
- await _productRepository.PullFilter(productId, x => x.ProductCategories, z => z.Id, productCategory.Id);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityUpdated(productCategory);
+ }
+
+ /// <summary>
+ /// Deletes a associated product category
+ /// </summary>
+ /// <param name="productCategory">Product category</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductCategory(ProductCategory productCategory, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCategory);
- //event notification
- await _mediator.EntityDeleted(productCategory);
+ await _productRepository.PullFilter(productId, x => x.ProductCategories, z => z.Id, productCategory.Id);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCATEGORIES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityDeleted(productCategory);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs
index 5a35286a7..5a03a2391 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs
@@ -1,125 +1,123 @@
using Grand.Business.Core.Interfaces.Catalog.Collections;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Collections
+namespace Grand.Business.Catalog.Services.Collections;
+
+/// <summary>
+/// Collection layout service
+/// </summary>
+public class CollectionLayoutService : ICollectionLayoutService
{
+ #region Ctor
+
/// <summary>
- /// Collection layout service
+ /// Ctor
/// </summary>
- public class CollectionLayoutService : ICollectionLayoutService
+ /// <param name="collectionLayoutRepository">Collection layout repository</param>
+ /// <param name="cacheBase">Cache base</param>
+ /// <param name="mediator">Mediator</param>
+ public CollectionLayoutService(IRepository<CollectionLayout> collectionLayoutRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<CollectionLayout> _collectionLayoutRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _collectionLayoutRepository = collectionLayoutRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="collectionLayoutRepository">Collection layout repository</param>
- /// <param name="cacheBase">Cache base</param>
- /// <param name="mediator">Mediator</param>
- public CollectionLayoutService(IRepository<CollectionLayout> collectionLayoutRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _collectionLayoutRepository = collectionLayoutRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
+ private readonly IRepository<CollectionLayout> _collectionLayoutRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets all collection layouts
- /// </summary>
- /// <returns>Collection layouts</returns>
- public virtual async Task<IList<CollectionLayout>> GetAllCollectionLayouts()
- {
- return await _cacheBase.GetAsync(CacheKey.COLLECTION_LAYOUT_ALL, async () =>
- {
- var query = from pt in _collectionLayoutRepository.Table
- orderby pt.DisplayOrder
- select pt;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a collection layout
- /// </summary>
- /// <param name="collectionLayoutId">Collection layout id</param>
- /// <returns>Collection layout</returns>
- public virtual Task<CollectionLayout> GetCollectionLayoutById(string collectionLayoutId)
- {
- var key = string.Format(CacheKey.COLLECTION_LAYOUT_BY_ID_KEY, collectionLayoutId);
- return _cacheBase.GetAsync(key, () => _collectionLayoutRepository.GetByIdAsync(collectionLayoutId));
- }
-
- /// <summary>
- /// Inserts collection layout
- /// </summary>
- /// <param name="collectionLayout">Collection layout</param>
- public virtual async Task InsertCollectionLayout(CollectionLayout collectionLayout)
+ /// <summary>
+ /// Gets all collection layouts
+ /// </summary>
+ /// <returns>Collection layouts</returns>
+ public virtual async Task<IList<CollectionLayout>> GetAllCollectionLayouts()
+ {
+ return await _cacheBase.GetAsync(CacheKey.COLLECTION_LAYOUT_ALL, async () =>
{
- ArgumentNullException.ThrowIfNull(collectionLayout);
+ var query = from pt in _collectionLayoutRepository.Table
+ orderby pt.DisplayOrder
+ select pt;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _collectionLayoutRepository.InsertAsync(collectionLayout);
+ /// <summary>
+ /// Gets a collection layout
+ /// </summary>
+ /// <param name="collectionLayoutId">Collection layout id</param>
+ /// <returns>Collection layout</returns>
+ public virtual Task<CollectionLayout> GetCollectionLayoutById(string collectionLayoutId)
+ {
+ var key = string.Format(CacheKey.COLLECTION_LAYOUT_BY_ID_KEY, collectionLayoutId);
+ return _cacheBase.GetAsync(key, () => _collectionLayoutRepository.GetByIdAsync(collectionLayoutId));
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Inserts collection layout
+ /// </summary>
+ /// <param name="collectionLayout">Collection layout</param>
+ public virtual async Task InsertCollectionLayout(CollectionLayout collectionLayout)
+ {
+ ArgumentNullException.ThrowIfNull(collectionLayout);
- //event notification
- await _mediator.EntityInserted(collectionLayout);
- }
+ await _collectionLayoutRepository.InsertAsync(collectionLayout);
- /// <summary>
- /// Updates the collection layout
- /// </summary>
- /// <param name="collectionLayout">Collection layout</param>
- public virtual async Task UpdateCollectionLayout(CollectionLayout collectionLayout)
- {
- ArgumentNullException.ThrowIfNull(collectionLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
- await _collectionLayoutRepository.UpdateAsync(collectionLayout);
+ //event notification
+ await _mediator.EntityInserted(collectionLayout);
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Updates the collection layout
+ /// </summary>
+ /// <param name="collectionLayout">Collection layout</param>
+ public virtual async Task UpdateCollectionLayout(CollectionLayout collectionLayout)
+ {
+ ArgumentNullException.ThrowIfNull(collectionLayout);
- //event notification
- await _mediator.EntityUpdated(collectionLayout);
- }
+ await _collectionLayoutRepository.UpdateAsync(collectionLayout);
- /// <summary>
- /// Delete collection layout
- /// </summary>
- /// <param name="collectionLayout">Collection layout</param>
- public virtual async Task DeleteCollectionLayout(CollectionLayout collectionLayout)
- {
- ArgumentNullException.ThrowIfNull(collectionLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
- await _collectionLayoutRepository.DeleteAsync(collectionLayout);
+ //event notification
+ await _mediator.EntityUpdated(collectionLayout);
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
+ /// <summary>
+ /// Delete collection layout
+ /// </summary>
+ /// <param name="collectionLayout">Collection layout</param>
+ public virtual async Task DeleteCollectionLayout(CollectionLayout collectionLayout)
+ {
+ ArgumentNullException.ThrowIfNull(collectionLayout);
- //event notification
- await _mediator.EntityDeleted(collectionLayout);
- }
+ await _collectionLayoutRepository.DeleteAsync(collectionLayout);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTION_LAYOUT_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(collectionLayout);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
index 542c5707a..bda6e8f51 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
@@ -1,9 +1,9 @@
using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
@@ -11,192 +11,190 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Collections
+namespace Grand.Business.Catalog.Services.Collections;
+
+/// <summary>
+/// Collection service
+/// </summary>
+public class CollectionService : ICollectionService
{
+ #region Ctor
+
/// <summary>
- /// Collection service
+ /// Ctor
/// </summary>
- public class CollectionService : ICollectionService
+ public CollectionService(ICacheBase cacheBase,
+ IRepository<Collection> collectionRepository,
+ IWorkContext workContext,
+ IMediator mediator,
+ IAclService aclService, AccessControlConfig accessControlConfig)
{
- #region Fields
-
- private readonly IRepository<Collection> _collectionRepository;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
- private readonly IAclService _aclService;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public CollectionService(ICacheBase cacheBase,
- IRepository<Collection> collectionRepository,
- IWorkContext workContext,
- IMediator mediator,
- IAclService aclService, AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _collectionRepository = collectionRepository;
- _workContext = workContext;
- _mediator = mediator;
- _aclService = aclService;
- _accessControlConfig = accessControlConfig;
- }
+ _cacheBase = cacheBase;
+ _collectionRepository = collectionRepository;
+ _workContext = workContext;
+ _mediator = mediator;
+ _aclService = aclService;
+ _accessControlConfig = accessControlConfig;
+ }
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets all collections
- /// </summary>
- /// <param name="collectionName">Collection name</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Collections</returns>
- public virtual async Task<IPagedList<Collection>> GetAllCollections(string collectionName = "",
- string storeId = "",
- int pageIndex = 0,
- int pageSize = int.MaxValue,
- bool showHidden = false)
- {
- var query = from m in _collectionRepository.Table
- select m;
+ #endregion
- if (!showHidden)
- query = query.Where(m => m.Published);
- if (!string.IsNullOrWhiteSpace(collectionName))
- query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(collectionName.ToLower()));
+ #region Fields
- if (!_accessControlConfig.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
- {
- if (!showHidden && !_accessControlConfig.IgnoreAcl)
- {
- //Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
-
- }
- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
- {
- //Limited to stores rules
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
- }
- query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
- return await PagedList<Collection>.Create(query, pageIndex, pageSize);
- }
+ private readonly IRepository<Collection> _collectionRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+ private readonly IAclService _aclService;
+ private readonly AccessControlConfig _accessControlConfig;
+ #endregion
- /// <summary>
- /// Gets all featured products for collections displayed on the home page
- /// </summary>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Collections</returns>
- public virtual async Task<IList<Collection>> GetAllCollectionFeaturedProductsOnHomePage(bool showHidden = false)
- {
- var query = _collectionRepository.Table.Where(x=>x.Published && x.FeaturedProductsOnHomePage).OrderBy(x => x.DisplayOrder);
+ #region Methods
+
+ /// <summary>
+ /// Gets all collections
+ /// </summary>
+ /// <param name="collectionName">Collection name</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Collections</returns>
+ public virtual async Task<IPagedList<Collection>> GetAllCollections(string collectionName = "",
+ string storeId = "",
+ int pageIndex = 0,
+ int pageSize = int.MaxValue,
+ bool showHidden = false)
+ {
+ var query = from m in _collectionRepository.Table
+ select m;
- var collections = await Task.FromResult(query.ToList());
- if (!showHidden)
+ if (!showHidden)
+ query = query.Where(m => m.Published);
+ if (!string.IsNullOrWhiteSpace(collectionName))
+ query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(collectionName.ToLower()));
+
+ if (!_accessControlConfig.IgnoreAcl ||
+ (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))
+ {
+ if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
- collections = collections
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) && _aclService.Authorize(c, _workContext.CurrentStore.Id))
- .ToList();
+ //Limited to customer groups rules
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
}
- return collections;
+
+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
+ //Limited to stores rules
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
}
+ query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
+ return await PagedList<Collection>.Create(query, pageIndex, pageSize);
+ }
- /// <summary>
- /// Gets a collection
- /// </summary>
- /// <param name="collectionId">Collection id</param>
- /// <returns>Collection</returns>
- public virtual Task<Collection> GetCollectionById(string collectionId)
- {
- var key = string.Format(CacheKey.COLLECTIONS_BY_ID_KEY, collectionId);
- return _cacheBase.GetAsync(key, () => _collectionRepository.GetByIdAsync(collectionId));
- }
- /// <summary>
- /// Inserts a collection
- /// </summary>
- /// <param name="collection">Collection</param>
- public virtual async Task InsertCollection(Collection collection)
- {
- ArgumentNullException.ThrowIfNull(collection);
+ /// <summary>
+ /// Gets all featured products for collections displayed on the home page
+ /// </summary>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Collections</returns>
+ public virtual async Task<IList<Collection>> GetAllCollectionFeaturedProductsOnHomePage(bool showHidden = false)
+ {
+ var query = _collectionRepository.Table.Where(x => x.Published && x.FeaturedProductsOnHomePage)
+ .OrderBy(x => x.DisplayOrder);
+
+ var collections = await Task.FromResult(query.ToList());
+ if (!showHidden)
+ collections = collections
+ .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .ToList();
+ return collections;
+ }
- await _collectionRepository.InsertAsync(collection);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
+ /// <summary>
+ /// Gets a collection
+ /// </summary>
+ /// <param name="collectionId">Collection id</param>
+ /// <returns>Collection</returns>
+ public virtual Task<Collection> GetCollectionById(string collectionId)
+ {
+ var key = string.Format(CacheKey.COLLECTIONS_BY_ID_KEY, collectionId);
+ return _cacheBase.GetAsync(key, () => _collectionRepository.GetByIdAsync(collectionId));
+ }
- //event notification
- await _mediator.EntityInserted(collection);
- }
+ /// <summary>
+ /// Inserts a collection
+ /// </summary>
+ /// <param name="collection">Collection</param>
+ public virtual async Task InsertCollection(Collection collection)
+ {
+ ArgumentNullException.ThrowIfNull(collection);
- /// <summary>
- /// Updates the collection
- /// </summary>
- /// <param name="collection">Collection</param>
- public virtual async Task UpdateCollection(Collection collection)
- {
- ArgumentNullException.ThrowIfNull(collection);
+ await _collectionRepository.InsertAsync(collection);
- await _collectionRepository.UpdateAsync(collection);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityInserted(collection);
+ }
- //event notification
- await _mediator.EntityUpdated(collection);
- }
- /// <summary>
- /// Deletes a collection
- /// </summary>
- /// <param name="collection">Collection</param>
- public virtual async Task DeleteCollection(Collection collection)
- {
- ArgumentNullException.ThrowIfNull(collection);
+ /// <summary>
+ /// Updates the collection
+ /// </summary>
+ /// <param name="collection">Collection</param>
+ public virtual async Task UpdateCollection(Collection collection)
+ {
+ ArgumentNullException.ThrowIfNull(collection);
- await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
+ await _collectionRepository.UpdateAsync(collection);
- await _collectionRepository.DeleteAsync(collection);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(collection);
+ //event notification
+ await _mediator.EntityUpdated(collection);
+ }
- }
+ /// <summary>
+ /// Deletes a collection
+ /// </summary>
+ /// <param name="collection">Collection</param>
+ public virtual async Task DeleteCollection(Collection collection)
+ {
+ ArgumentNullException.ThrowIfNull(collection);
- /// <summary>
- /// Gets a discount collection mapping
- /// </summary>
- /// <param name="discountId">Discount id mapping id</param>
- /// <returns>Product collection mapping</returns>
- public virtual async Task<IList<Collection>> GetAllCollectionsByDiscount(string discountId)
- {
- var query = from c in _collectionRepository.Table
- where c.AppliedDiscounts.Any(x => x == discountId)
- select c;
+ await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);
- return await Task.FromResult(query.ToList());
- }
+ await _collectionRepository.DeleteAsync(collection);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(collection);
+ }
+
+ /// <summary>
+ /// Gets a discount collection mapping
+ /// </summary>
+ /// <param name="discountId">Discount id mapping id</param>
+ /// <returns>Product collection mapping</returns>
+ public virtual async Task<IList<Collection>> GetAllCollectionsByDiscount(string discountId)
+ {
+ var query = from c in _collectionRepository.Table
+ where c.AppliedDiscounts.Any(x => x == discountId)
+ select c;
+ return await Task.FromResult(query.ToList());
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
index e81c8fcdf..21659c113 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
@@ -1,9 +1,9 @@
using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
@@ -11,148 +11,148 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Collections
+namespace Grand.Business.Catalog.Services.Collections;
+
+public class ProductCollectionService : IProductCollectionService
{
- public class ProductCollectionService : IProductCollectionService
+ #region Ctor
+
+ public ProductCollectionService(ICacheBase cacheBase,
+ IRepository<Product> productRepository,
+ IWorkContext workContext,
+ IMediator mediator, AccessControlConfig accessControlConfig)
{
- #region Fields
-
- private readonly IRepository<Product> _productRepository;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- public ProductCollectionService(ICacheBase cacheBase,
- IRepository<Product> productRepository,
- IWorkContext workContext,
- IMediator mediator, AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _productRepository = productRepository;
- _workContext = workContext;
- _mediator = mediator;
- _accessControlConfig = accessControlConfig;
- }
- #endregion
-
- /// <summary>
- /// Gets product collection by collection id
- /// </summary>
- /// <param name="collectionId">Collection id</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Product collection collection</returns>
- public virtual async Task<IPagedList<ProductsCollection>> GetProductCollectionsByCollectionId(string collectionId, string storeId,
- int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ _cacheBase = cacheBase;
+ _productRepository = productRepository;
+ _workContext = workContext;
+ _mediator = mediator;
+ _accessControlConfig = accessControlConfig;
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets product collection by collection id
+ /// </summary>
+ /// <param name="collectionId">Collection id</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Product collection collection</returns>
+ public virtual async Task<IPagedList<ProductsCollection>> GetProductCollectionsByCollectionId(string collectionId,
+ string storeId,
+ int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ {
+ var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex,
+ pageSize, _workContext.CurrentCustomer.Id, storeId);
+ return await _cacheBase.GetAsync(key, () =>
{
- var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, storeId);
- return await _cacheBase.GetAsync(key, () =>
- {
- var query = _productRepository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == collectionId));
+ var query = _productRepository.Table.Where(x =>
+ x.ProductCollections.Any(y => y.CollectionId == collectionId));
- if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
+ if (!showHidden && (!_accessControlConfig.IgnoreAcl || !_accessControlConfig.IgnoreStoreLimitations))
+ {
+ if (!_accessControlConfig.IgnoreAcl)
{
- if (!_accessControlConfig.IgnoreAcl)
- {
- //ACL (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
- if (!_accessControlConfig.IgnoreStoreLimitations && !string.IsNullOrEmpty(storeId))
- {
- //Store acl
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
-
- }
-
+ //ACL (access control list)
+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
}
- var queryProductCollection = from prod in query
- from pm in prod.ProductCollections
- select new ProductsCollection {
- Id = pm.Id,
- ProductId = prod.Id,
- DisplayOrder = pm.DisplayOrder,
- IsFeaturedProduct = pm.IsFeaturedProduct,
- CollectionId = pm.CollectionId
- };
-
- queryProductCollection = from pm in queryProductCollection
- where pm.CollectionId == collectionId
- orderby pm.DisplayOrder
- select pm;
-
- return Task.FromResult(new PagedList<ProductsCollection>(queryProductCollection, pageIndex, pageSize));
- });
- }
-
- /// <summary>
- /// Inserts a product collection mapping
- /// </summary>
- /// <param name="productCollection">Product collection mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductCollection(ProductCollection productCollection, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCollection);
+ if (!_accessControlConfig.IgnoreStoreLimitations && !string.IsNullOrEmpty(storeId))
+ //Store acl
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
+ }
+
+ var queryProductCollection = from prod in query
+ from pm in prod.ProductCollections
+ select new ProductsCollection {
+ Id = pm.Id,
+ ProductId = prod.Id,
+ DisplayOrder = pm.DisplayOrder,
+ IsFeaturedProduct = pm.IsFeaturedProduct,
+ CollectionId = pm.CollectionId
+ };
+
+ queryProductCollection = from pm in queryProductCollection
+ where pm.CollectionId == collectionId
+ orderby pm.DisplayOrder
+ select pm;
+
+ return Task.FromResult(new PagedList<ProductsCollection>(queryProductCollection, pageIndex, pageSize));
+ });
+ }
- await _productRepository.AddToSet(productId, x => x.ProductCollections, productCollection);
+ /// <summary>
+ /// Inserts a product collection mapping
+ /// </summary>
+ /// <param name="productCollection">Product collection mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductCollection(ProductCollection productCollection, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCollection);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _productRepository.AddToSet(productId, x => x.ProductCollections, productCollection);
- //event notification
- await _mediator.EntityInserted(productCollection);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- /// <summary>
- /// Updates the product collection mapping
- /// </summary>
- /// <param name="productCollection">Product collection mapping</param>
- /// <param name="productId">Product id</param>
- public virtual async Task UpdateProductCollection(ProductCollection productCollection, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCollection);
+ //event notification
+ await _mediator.EntityInserted(productCollection);
+ }
- await _productRepository.UpdateToSet(productId, x => x.ProductCollections, z => z.Id, productCollection.Id, productCollection);
+ /// <summary>
+ /// Updates the product collection mapping
+ /// </summary>
+ /// <param name="productCollection">Product collection mapping</param>
+ /// <param name="productId">Product id</param>
+ public virtual async Task UpdateProductCollection(ProductCollection productCollection, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCollection);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _productRepository.UpdateToSet(productId, x => x.ProductCollections, z => z.Id, productCollection.Id,
+ productCollection);
- //event notification
- await _mediator.EntityUpdated(productCollection);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- /// <summary>
- /// Deletes a product collection mapping
- /// </summary>
- /// <param name="productCollection">Product collection mapping</param>
- /// <param name="productId">Product id</param>
- public virtual async Task DeleteProductCollection(ProductCollection productCollection, string productId)
- {
- ArgumentNullException.ThrowIfNull(productCollection);
+ //event notification
+ await _mediator.EntityUpdated(productCollection);
+ }
- await _productRepository.PullFilter(productId, x => x.ProductCollections, z => z.Id, productCollection.Id);
+ /// <summary>
+ /// Deletes a product collection mapping
+ /// </summary>
+ /// <param name="productCollection">Product collection mapping</param>
+ /// <param name="productId">Product id</param>
+ public virtual async Task DeleteProductCollection(ProductCollection productCollection, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productCollection);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _productRepository.PullFilter(productId, x => x.ProductCollections, z => z.Id, productCollection.Id);
- //event notification
- await _mediator.EntityDeleted(productCollection);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTCOLLECTIONS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityDeleted(productCollection);
}
-}
+
+ #region Fields
+
+ private readonly IRepository<Product> _productRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+ private readonly AccessControlConfig _accessControlConfig;
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
index 547025679..e7e788452 100644
--- a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
@@ -1,4 +1,5 @@
//This product contains GeoLite2 data created by MaxMind, from http://www.maxmind.com
+
using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.SharedKernel.Extensions;
using MaxMind.GeoIP2;
@@ -6,81 +7,81 @@ using MaxMind.GeoIP2.Exceptions;
using MaxMind.GeoIP2.Responses;
using Microsoft.Extensions.Logging;
-namespace Grand.Business.Catalog.Services.Directory
+namespace Grand.Business.Catalog.Services.Directory;
+
+/// <summary>
+/// GEO lookup service
+/// </summary>
+public class GeoLookupService : IGeoLookupService
{
- /// <summary>
- /// GEO lookup service
- /// </summary>
- public class GeoLookupService : IGeoLookupService
- {
- #region Fields
+ #region Fields
- private readonly ILogger<GeoLookupService> _logger;
+ private readonly ILogger<GeoLookupService> _logger;
- #endregion
+ #endregion
- #region Ctor
+ #region Ctor
- public GeoLookupService(ILogger<GeoLookupService> logger)
- {
- _logger = logger;
- }
+ public GeoLookupService(ILogger<GeoLookupService> logger)
+ {
+ _logger = logger;
+ }
+
+ #endregion
- #endregion
+ #region Utilities
- #region Utilities
+ protected virtual CountryResponse GetInformation(string ipAddress)
+ {
+ if (string.IsNullOrEmpty(ipAddress))
+ return null;
- protected virtual CountryResponse GetInformation(string ipAddress)
+ try
{
- if (string.IsNullOrEmpty(ipAddress))
- return null;
-
- try
- {
- //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
- var databasePath = CommonPath.MapPath("App_Data/GeoLite2-Country.mmdb");
- var reader = new DatabaseReader(databasePath);
- var response = reader.Country(ipAddress);
- return response;
- //more info: http://maxmind.github.io/GeoIP2-dotnet/
- //more info: https://github.com/maxmind/GeoIP2-dotnet
- }
- catch (GeoIP2Exception)
- {
- return null;
- }
- catch (Exception exc)
- {
- _logger.LogError(exc, "Cannot load MaxMind record");
- return null;
- }
+ //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
+ var databasePath = CommonPath.MapPath("App_Data/GeoLite2-Country.mmdb");
+ var reader = new DatabaseReader(databasePath);
+ var response = reader.Country(ipAddress);
+ return response;
+ //more info: http://maxmind.github.io/GeoIP2-dotnet/
+ //more info: https://github.com/maxmind/GeoIP2-dotnet
}
-
- #endregion
-
- #region Methods
- /// <summary>
- /// Get country name
- /// </summary>
- /// <param name="ipAddress">IP address</param>
- /// <returns>Country name</returns>
- public virtual string CountryIsoCode(string ipAddress)
+ catch (GeoIP2Exception)
{
- var response = GetInformation(ipAddress);
- return response is { } ? response.Country.IsoCode : "";
+ return null;
}
-
- /// <summary>
- /// Get country name
- /// </summary>
- /// <param name="ipAddress">IP address</param>
- /// <returns>Country name</returns>
- public virtual string CountryName(string ipAddress)
+ catch (Exception exc)
{
- var response = GetInformation(ipAddress);
- return response is { } ? response.Country.Name : "";
+ _logger.LogError(exc, "Cannot load MaxMind record");
+ return null;
}
+ }
+
+ #endregion
+
+ #region Methods
- #endregion
+ /// <summary>
+ /// Get country name
+ /// </summary>
+ /// <param name="ipAddress">IP address</param>
+ /// <returns>Country name</returns>
+ public virtual string CountryIsoCode(string ipAddress)
+ {
+ var response = GetInformation(ipAddress);
+ return response is not null ? response.Country.IsoCode : "";
}
+
+ /// <summary>
+ /// Get country name
+ /// </summary>
+ /// <param name="ipAddress">IP address</param>
+ /// <returns>Country name</returns>
+ public virtual string CountryName(string ipAddress)
+ {
+ var response = GetInformation(ipAddress);
+ return response is not null ? response.Country.Name : "";
+ }
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs
index 702a0cdf8..e909c5d1a 100644
--- a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs
@@ -1,463 +1,465 @@
+using Grand.Business.Core.Interfaces.Catalog.Directory;
+using Grand.Data;
+using Grand.Domain.Directory;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Data;
-using Grand.Domain.Directory;
using Grand.SharedKernel;
using MediatR;
-using Grand.Business.Core.Interfaces.Catalog.Directory;
-namespace Grand.Business.Catalog.Services.Directory
+namespace Grand.Business.Catalog.Services.Directory;
+
+/// <summary>
+/// Measure dimension service
+/// </summary>
+public class MeasureService : IMeasureService
{
+ #region Ctor
+
/// <summary>
- /// Measure dimension service
+ /// Ctor
/// </summary>
- public class MeasureService : IMeasureService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="measureDimensionRepository">Dimension repository</param>
+ /// <param name="measureWeightRepository">Weight repository</param>
+ /// <param name="measureUnitRepository">Unit repository</param>
+ /// <param name="measureSettings">Measure settings</param>
+ /// <param name="mediator">Mediator</param>
+ public MeasureService(ICacheBase cacheBase,
+ IRepository<MeasureDimension> measureDimensionRepository,
+ IRepository<MeasureWeight> measureWeightRepository,
+ IRepository<MeasureUnit> measureUnitRepository,
+ MeasureSettings measureSettings,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<MeasureDimension> _measureDimensionRepository;
- private readonly IRepository<MeasureWeight> _measureWeightRepository;
- private readonly IRepository<MeasureUnit> _measureUnitRepository;
- private readonly ICacheBase _cacheBase;
- private readonly MeasureSettings _measureSettings;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="measureDimensionRepository">Dimension repository</param>
- /// <param name="measureWeightRepository">Weight repository</param>
- /// <param name="measureUnitRepository">Unit repository</param>
- /// <param name="measureSettings">Measure settings</param>
- /// <param name="mediator">Mediator</param>
- public MeasureService(ICacheBase cacheBase,
- IRepository<MeasureDimension> measureDimensionRepository,
- IRepository<MeasureWeight> measureWeightRepository,
- IRepository<MeasureUnit> measureUnitRepository,
- MeasureSettings measureSettings,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _measureDimensionRepository = measureDimensionRepository;
- _measureWeightRepository = measureWeightRepository;
- _measureUnitRepository = measureUnitRepository;
- _measureSettings = measureSettings;
- _mediator = mediator;
- }
+ _cacheBase = cacheBase;
+ _measureDimensionRepository = measureDimensionRepository;
+ _measureWeightRepository = measureWeightRepository;
+ _measureUnitRepository = measureUnitRepository;
+ _measureSettings = measureSettings;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Methods
+ #region Fields
- #region Dimensions
+ private readonly IRepository<MeasureDimension> _measureDimensionRepository;
+ private readonly IRepository<MeasureWeight> _measureWeightRepository;
+ private readonly IRepository<MeasureUnit> _measureUnitRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly MeasureSettings _measureSettings;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Gets a measure dimension by identifier
- /// </summary>
- /// <param name="measureDimensionId">Measure dimension identifier</param>
- /// <returns>Measure dimension</returns>
- public virtual Task<MeasureDimension> GetMeasureDimensionById(string measureDimensionId)
- {
- var key = string.Format(CacheKey.MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId);
- return _cacheBase.GetAsync(key, () => _measureDimensionRepository.GetByIdAsync(measureDimensionId));
- }
+ #endregion
- /// <summary>
- /// Gets a measure dimension by system keyword
- /// </summary>
- /// <param name="systemKeyword">The system keyword</param>
- /// <returns>Measure dimension</returns>
- public virtual async Task<MeasureDimension> GetMeasureDimensionBySystemKeyword(string systemKeyword)
- {
- if (string.IsNullOrEmpty(systemKeyword))
- return null;
+ #region Methods
- var measureDimensions = await GetAllMeasureDimensions();
- return measureDimensions.FirstOrDefault(measureDimension => string.Equals(measureDimension.SystemKeyword, systemKeyword, StringComparison.InvariantCultureIgnoreCase));
- }
+ #region Dimensions
- /// <summary>
- /// Gets all measure dimensions
- /// </summary>
- /// <returns>Measure dimensions</returns>
- public virtual async Task<IList<MeasureDimension>> GetAllMeasureDimensions()
- {
- var key = CacheKey.MEASUREDIMENSIONS_ALL_KEY;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from md in _measureDimensionRepository.Table
- orderby md.DisplayOrder
- select md;
- return await Task.FromResult(query.ToList());
- });
- }
+ /// <summary>
+ /// Gets a measure dimension by identifier
+ /// </summary>
+ /// <param name="measureDimensionId">Measure dimension identifier</param>
+ /// <returns>Measure dimension</returns>
+ public virtual Task<MeasureDimension> GetMeasureDimensionById(string measureDimensionId)
+ {
+ var key = string.Format(CacheKey.MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId);
+ return _cacheBase.GetAsync(key, () => _measureDimensionRepository.GetByIdAsync(measureDimensionId));
+ }
+
+ /// <summary>
+ /// Gets a measure dimension by system keyword
+ /// </summary>
+ /// <param name="systemKeyword">The system keyword</param>
+ /// <returns>Measure dimension</returns>
+ public virtual async Task<MeasureDimension> GetMeasureDimensionBySystemKeyword(string systemKeyword)
+ {
+ if (string.IsNullOrEmpty(systemKeyword))
+ return null;
+
+ var measureDimensions = await GetAllMeasureDimensions();
+ return measureDimensions.FirstOrDefault(measureDimension => string.Equals(measureDimension.SystemKeyword,
+ systemKeyword, StringComparison.InvariantCultureIgnoreCase));
+ }
- /// <summary>
- /// Inserts a measure dimension
- /// </summary>
- /// <param name="measure">Measure dimension</param>
- public virtual async Task InsertMeasureDimension(MeasureDimension measure)
+ /// <summary>
+ /// Gets all measure dimensions
+ /// </summary>
+ /// <returns>Measure dimensions</returns>
+ public virtual async Task<IList<MeasureDimension>> GetAllMeasureDimensions()
+ {
+ var key = CacheKey.MEASUREDIMENSIONS_ALL_KEY;
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(measure);
+ var query = from md in _measureDimensionRepository.Table
+ orderby md.DisplayOrder
+ select md;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _measureDimensionRepository.InsertAsync(measure);
+ /// <summary>
+ /// Inserts a measure dimension
+ /// </summary>
+ /// <param name="measure">Measure dimension</param>
+ public virtual async Task InsertMeasureDimension(MeasureDimension measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
+ await _measureDimensionRepository.InsertAsync(measure);
- //event notification
- await _mediator.EntityInserted(measure);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
- /// <summary>
- /// Updates the measure dimension
- /// </summary>
- /// <param name="measure">Measure dimension</param>
- public virtual async Task UpdateMeasureDimension(MeasureDimension measure)
- {
- ArgumentNullException.ThrowIfNull(measure);
+ //event notification
+ await _mediator.EntityInserted(measure);
+ }
- await _measureDimensionRepository.UpdateAsync(measure);
+ /// <summary>
+ /// Updates the measure dimension
+ /// </summary>
+ /// <param name="measure">Measure dimension</param>
+ public virtual async Task UpdateMeasureDimension(MeasureDimension measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
+ await _measureDimensionRepository.UpdateAsync(measure);
- //event notification
- await _mediator.EntityUpdated(measure);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
- /// <summary>
- /// Deletes measure dimension
- /// </summary>
- /// <param name="measureDimension">Measure dimension</param>
- public virtual async Task DeleteMeasureDimension(MeasureDimension measureDimension)
- {
- ArgumentNullException.ThrowIfNull(measureDimension);
+ //event notification
+ await _mediator.EntityUpdated(measure);
+ }
- await _measureDimensionRepository.DeleteAsync(measureDimension);
+ /// <summary>
+ /// Deletes measure dimension
+ /// </summary>
+ /// <param name="measureDimension">Measure dimension</param>
+ public virtual async Task DeleteMeasureDimension(MeasureDimension measureDimension)
+ {
+ ArgumentNullException.ThrowIfNull(measureDimension);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
+ await _measureDimensionRepository.DeleteAsync(measureDimension);
- //event notification
- await _mediator.EntityDeleted(measureDimension);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREDIMENSIONS_PATTERN_KEY);
- /// <summary>
- /// Converts dimension
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="sourceMeasureDimension">Source dimension</param>
- /// <param name="targetMeasureDimension">Target dimension</param>
- /// <param name="round">A value indicating whether a result should be rounded</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertDimension(double value,
- MeasureDimension sourceMeasureDimension, MeasureDimension targetMeasureDimension, bool round = true)
- {
- ArgumentNullException.ThrowIfNull(sourceMeasureDimension);
- ArgumentNullException.ThrowIfNull(targetMeasureDimension);
-
- var result = value;
- if (result != 0 && sourceMeasureDimension.Id != targetMeasureDimension.Id)
- {
- result = await ConvertToPrimaryMeasureDimension(result, sourceMeasureDimension);
- result = await ConvertFromPrimaryMeasureDimension(result, targetMeasureDimension);
- }
- if (round)
- result = Math.Round(result, 2);
- return result;
- }
+ //event notification
+ await _mediator.EntityDeleted(measureDimension);
+ }
- /// <summary>
- /// Converts to primary measure dimension
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="sourceMeasureDimension">Source dimension</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertToPrimaryMeasureDimension(double value,
- MeasureDimension sourceMeasureDimension)
- {
- ArgumentNullException.ThrowIfNull(sourceMeasureDimension);
-
- var result = value;
- var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);
- if (result == 0 || sourceMeasureDimension.Id == baseDimensionIn.Id) return result;
- var exchangeRatio = sourceMeasureDimension.Ratio;
- if (exchangeRatio == 0)
- throw new GrandException($"Exchange ratio not set for dimension [{sourceMeasureDimension.Name}]");
- result /= exchangeRatio;
- return result;
- }
+ /// <summary>
+ /// Converts dimension
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="sourceMeasureDimension">Source dimension</param>
+ /// <param name="targetMeasureDimension">Target dimension</param>
+ /// <param name="round">A value indicating whether a result should be rounded</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertDimension(double value,
+ MeasureDimension sourceMeasureDimension, MeasureDimension targetMeasureDimension, bool round = true)
+ {
+ ArgumentNullException.ThrowIfNull(sourceMeasureDimension);
+ ArgumentNullException.ThrowIfNull(targetMeasureDimension);
- /// <summary>
- /// Converts from primary dimension
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="targetMeasureDimension">Target dimension</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertFromPrimaryMeasureDimension(double value,
- MeasureDimension targetMeasureDimension)
+ var result = value;
+ if (result != 0 && sourceMeasureDimension.Id != targetMeasureDimension.Id)
{
- ArgumentNullException.ThrowIfNull(targetMeasureDimension);
-
- var result = value;
- var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);
- if (result == 0 || targetMeasureDimension.Id == baseDimensionIn.Id) return result;
- var exchangeRatio = targetMeasureDimension.Ratio;
- if (exchangeRatio == 0)
- throw new GrandException($"Exchange ratio not set for dimension [{targetMeasureDimension.Name}]");
- result *= exchangeRatio;
- return result;
+ result = await ConvertToPrimaryMeasureDimension(result, sourceMeasureDimension);
+ result = await ConvertFromPrimaryMeasureDimension(result, targetMeasureDimension);
}
- #endregion
+ if (round)
+ result = Math.Round(result, 2);
+ return result;
+ }
- #region Weights
+ /// <summary>
+ /// Converts to primary measure dimension
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="sourceMeasureDimension">Source dimension</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertToPrimaryMeasureDimension(double value,
+ MeasureDimension sourceMeasureDimension)
+ {
+ ArgumentNullException.ThrowIfNull(sourceMeasureDimension);
+
+ var result = value;
+ var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);
+ if (result == 0 || sourceMeasureDimension.Id == baseDimensionIn.Id) return result;
+ var exchangeRatio = sourceMeasureDimension.Ratio;
+ if (exchangeRatio == 0)
+ throw new GrandException($"Exchange ratio not set for dimension [{sourceMeasureDimension.Name}]");
+ result /= exchangeRatio;
+ return result;
+ }
- /// <summary>
- /// Gets a measure weight by identifier
- /// </summary>
- /// <param name="measureWeightId">Measure weight identifier</param>
- /// <returns>Measure weight</returns>
- public virtual Task<MeasureWeight> GetMeasureWeightById(string measureWeightId)
- {
- var key = string.Format(CacheKey.MEASUREWEIGHTS_BY_ID_KEY, measureWeightId);
- return _cacheBase.GetAsync(key, () => _measureWeightRepository.GetByIdAsync(measureWeightId));
- }
+ /// <summary>
+ /// Converts from primary dimension
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="targetMeasureDimension">Target dimension</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertFromPrimaryMeasureDimension(double value,
+ MeasureDimension targetMeasureDimension)
+ {
+ ArgumentNullException.ThrowIfNull(targetMeasureDimension);
+
+ var result = value;
+ var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);
+ if (result == 0 || targetMeasureDimension.Id == baseDimensionIn.Id) return result;
+ var exchangeRatio = targetMeasureDimension.Ratio;
+ if (exchangeRatio == 0)
+ throw new GrandException($"Exchange ratio not set for dimension [{targetMeasureDimension.Name}]");
+ result *= exchangeRatio;
+ return result;
+ }
- /// <summary>
- /// Gets a measure weight by system keyword
- /// </summary>
- /// <param name="systemKeyword">The system keyword</param>
- /// <returns>Measure weight</returns>
- public virtual async Task<MeasureWeight> GetMeasureWeightBySystemKeyword(string systemKeyword)
- {
- if (string.IsNullOrEmpty(systemKeyword))
- return null;
+ #endregion
- var measureWeights = await GetAllMeasureWeights();
- return measureWeights.FirstOrDefault(measureWeight => string.Equals(measureWeight.SystemKeyword, systemKeyword, StringComparison.InvariantCultureIgnoreCase));
- }
+ #region Weights
- /// <summary>
- /// Gets all measure weights
- /// </summary>
- /// <returns>Measure weights</returns>
- public virtual async Task<IList<MeasureWeight>> GetAllMeasureWeights()
- {
- var key = CacheKey.MEASUREWEIGHTS_ALL_KEY;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from mw in _measureWeightRepository.Table
- orderby mw.DisplayOrder
- select mw;
- return await Task.FromResult(query.ToList());
- });
- }
+ /// <summary>
+ /// Gets a measure weight by identifier
+ /// </summary>
+ /// <param name="measureWeightId">Measure weight identifier</param>
+ /// <returns>Measure weight</returns>
+ public virtual Task<MeasureWeight> GetMeasureWeightById(string measureWeightId)
+ {
+ var key = string.Format(CacheKey.MEASUREWEIGHTS_BY_ID_KEY, measureWeightId);
+ return _cacheBase.GetAsync(key, () => _measureWeightRepository.GetByIdAsync(measureWeightId));
+ }
- /// <summary>
- /// Inserts a measure weight
- /// </summary>
- /// <param name="measure">Measure weight</param>
- public virtual async Task InsertMeasureWeight(MeasureWeight measure)
+ /// <summary>
+ /// Gets a measure weight by system keyword
+ /// </summary>
+ /// <param name="systemKeyword">The system keyword</param>
+ /// <returns>Measure weight</returns>
+ public virtual async Task<MeasureWeight> GetMeasureWeightBySystemKeyword(string systemKeyword)
+ {
+ if (string.IsNullOrEmpty(systemKeyword))
+ return null;
+
+ var measureWeights = await GetAllMeasureWeights();
+ return measureWeights.FirstOrDefault(measureWeight => string.Equals(measureWeight.SystemKeyword, systemKeyword,
+ StringComparison.InvariantCultureIgnoreCase));
+ }
+
+ /// <summary>
+ /// Gets all measure weights
+ /// </summary>
+ /// <returns>Measure weights</returns>
+ public virtual async Task<IList<MeasureWeight>> GetAllMeasureWeights()
+ {
+ var key = CacheKey.MEASUREWEIGHTS_ALL_KEY;
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(measure);
+ var query = from mw in _measureWeightRepository.Table
+ orderby mw.DisplayOrder
+ select mw;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _measureWeightRepository.InsertAsync(measure);
+ /// <summary>
+ /// Inserts a measure weight
+ /// </summary>
+ /// <param name="measure">Measure weight</param>
+ public virtual async Task InsertMeasureWeight(MeasureWeight measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
+ await _measureWeightRepository.InsertAsync(measure);
- //event notification
- await _mediator.EntityInserted(measure);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
- /// <summary>
- /// Updates the measure weight
- /// </summary>
- /// <param name="measure">Measure weight</param>
- public virtual async Task UpdateMeasureWeight(MeasureWeight measure)
- {
- ArgumentNullException.ThrowIfNull(measure);
+ //event notification
+ await _mediator.EntityInserted(measure);
+ }
- await _measureWeightRepository.UpdateAsync(measure);
+ /// <summary>
+ /// Updates the measure weight
+ /// </summary>
+ /// <param name="measure">Measure weight</param>
+ public virtual async Task UpdateMeasureWeight(MeasureWeight measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
+ await _measureWeightRepository.UpdateAsync(measure);
- //event notification
- await _mediator.EntityUpdated(measure);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
- /// <summary>
- /// Deletes measure weight
- /// </summary>
- /// <param name="measureWeight">Measure weight</param>
- public virtual async Task DeleteMeasureWeight(MeasureWeight measureWeight)
- {
- ArgumentNullException.ThrowIfNull(measureWeight);
+ //event notification
+ await _mediator.EntityUpdated(measure);
+ }
- await _measureWeightRepository.DeleteAsync(measureWeight);
+ /// <summary>
+ /// Deletes measure weight
+ /// </summary>
+ /// <param name="measureWeight">Measure weight</param>
+ public virtual async Task DeleteMeasureWeight(MeasureWeight measureWeight)
+ {
+ ArgumentNullException.ThrowIfNull(measureWeight);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
+ await _measureWeightRepository.DeleteAsync(measureWeight);
- //event notification
- await _mediator.EntityDeleted(measureWeight);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREWEIGHTS_PATTERN_KEY);
- /// <summary>
- /// Converts weight
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="sourceMeasureWeight">Source weight</param>
- /// <param name="targetMeasureWeight">Target weight</param>
- /// <param name="round">A value indicating whether a result should be rounded</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertWeight(double value,
- MeasureWeight sourceMeasureWeight, MeasureWeight targetMeasureWeight, bool round = true)
- {
- ArgumentNullException.ThrowIfNull(sourceMeasureWeight);
- ArgumentNullException.ThrowIfNull(targetMeasureWeight);
-
- var result = value;
- if (result != 0 && sourceMeasureWeight.Id != targetMeasureWeight.Id)
- {
- result = await ConvertToPrimaryMeasureWeight(result, sourceMeasureWeight);
- result = await ConvertFromPrimaryMeasureWeight(result, targetMeasureWeight);
- }
- if (round)
- result = Math.Round(result, 2);
- return result;
- }
+ //event notification
+ await _mediator.EntityDeleted(measureWeight);
+ }
- /// <summary>
- /// Converts to primary measure weight
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="sourceMeasureWeight">Source weight</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertToPrimaryMeasureWeight(double value, MeasureWeight sourceMeasureWeight)
- {
- ArgumentNullException.ThrowIfNull(sourceMeasureWeight);
-
- var result = value;
- var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);
- if (result == 0 || sourceMeasureWeight.Id == baseWeightIn.Id) return result;
- var exchangeRatio = sourceMeasureWeight.Ratio;
- if (exchangeRatio == 0)
- throw new GrandException($"Exchange ratio not set for weight [{sourceMeasureWeight.Name}]");
- result /= exchangeRatio;
- return result;
- }
+ /// <summary>
+ /// Converts weight
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="sourceMeasureWeight">Source weight</param>
+ /// <param name="targetMeasureWeight">Target weight</param>
+ /// <param name="round">A value indicating whether a result should be rounded</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertWeight(double value,
+ MeasureWeight sourceMeasureWeight, MeasureWeight targetMeasureWeight, bool round = true)
+ {
+ ArgumentNullException.ThrowIfNull(sourceMeasureWeight);
+ ArgumentNullException.ThrowIfNull(targetMeasureWeight);
- /// <summary>
- /// Converts from primary weight
- /// </summary>
- /// <param name="value">Value to convert</param>
- /// <param name="targetMeasureWeight">Target weight</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertFromPrimaryMeasureWeight(double value,
- MeasureWeight targetMeasureWeight)
+ var result = value;
+ if (result != 0 && sourceMeasureWeight.Id != targetMeasureWeight.Id)
{
- ArgumentNullException.ThrowIfNull(targetMeasureWeight);
-
- var result = value;
- var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);
- if (result == 0 || targetMeasureWeight.Id == baseWeightIn.Id) return result;
- var exchangeRatio = targetMeasureWeight.Ratio;
- if (exchangeRatio == 0)
- throw new GrandException($"Exchange ratio not set for weight [{targetMeasureWeight.Name}]");
- result *= exchangeRatio;
- return result;
+ result = await ConvertToPrimaryMeasureWeight(result, sourceMeasureWeight);
+ result = await ConvertFromPrimaryMeasureWeight(result, targetMeasureWeight);
}
- #endregion
+ if (round)
+ result = Math.Round(result, 2);
+ return result;
+ }
+
+ /// <summary>
+ /// Converts to primary measure weight
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="sourceMeasureWeight">Source weight</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertToPrimaryMeasureWeight(double value, MeasureWeight sourceMeasureWeight)
+ {
+ ArgumentNullException.ThrowIfNull(sourceMeasureWeight);
+
+ var result = value;
+ var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);
+ if (result == 0 || sourceMeasureWeight.Id == baseWeightIn.Id) return result;
+ var exchangeRatio = sourceMeasureWeight.Ratio;
+ if (exchangeRatio == 0)
+ throw new GrandException($"Exchange ratio not set for weight [{sourceMeasureWeight.Name}]");
+ result /= exchangeRatio;
+ return result;
+ }
+
+ /// <summary>
+ /// Converts from primary weight
+ /// </summary>
+ /// <param name="value">Value to convert</param>
+ /// <param name="targetMeasureWeight">Target weight</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertFromPrimaryMeasureWeight(double value,
+ MeasureWeight targetMeasureWeight)
+ {
+ ArgumentNullException.ThrowIfNull(targetMeasureWeight);
+
+ var result = value;
+ var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);
+ if (result == 0 || targetMeasureWeight.Id == baseWeightIn.Id) return result;
+ var exchangeRatio = targetMeasureWeight.Ratio;
+ if (exchangeRatio == 0)
+ throw new GrandException($"Exchange ratio not set for weight [{targetMeasureWeight.Name}]");
+ result *= exchangeRatio;
+ return result;
+ }
- #region MeasureUnit
+ #endregion
+ #region MeasureUnit
- /// <summary>
- /// Gets a measure unit by identifier
- /// </summary>
- /// <param name="measureUnitId">Measure unit identifier</param>
- /// <returns>Measure dimension</returns>
- public virtual Task<MeasureUnit> GetMeasureUnitById(string measureUnitId)
- {
- var key = string.Format(CacheKey.MEASUREUNITS_BY_ID_KEY, measureUnitId);
- return _cacheBase.GetAsync(key, () => _measureUnitRepository.GetByIdAsync(measureUnitId));
- }
+ /// <summary>
+ /// Gets a measure unit by identifier
+ /// </summary>
+ /// <param name="measureUnitId">Measure unit identifier</param>
+ /// <returns>Measure dimension</returns>
+ public virtual Task<MeasureUnit> GetMeasureUnitById(string measureUnitId)
+ {
+ var key = string.Format(CacheKey.MEASUREUNITS_BY_ID_KEY, measureUnitId);
+ return _cacheBase.GetAsync(key, () => _measureUnitRepository.GetByIdAsync(measureUnitId));
+ }
- /// <summary>
- /// Gets all measure units
- /// </summary>
- /// <returns>Measure unit</returns>
- public virtual async Task<IList<MeasureUnit>> GetAllMeasureUnits()
+ /// <summary>
+ /// Gets all measure units
+ /// </summary>
+ /// <returns>Measure unit</returns>
+ public virtual async Task<IList<MeasureUnit>> GetAllMeasureUnits()
+ {
+ var key = CacheKey.MEASUREUNITS_ALL_KEY;
+ return await _cacheBase.GetAsync(key, async () =>
{
- var key = CacheKey.MEASUREUNITS_ALL_KEY;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from md in _measureUnitRepository.Table
- orderby md.DisplayOrder
- select md;
- return await Task.FromResult(query.ToList());
- });
- }
+ var query = from md in _measureUnitRepository.Table
+ orderby md.DisplayOrder
+ select md;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- /// <summary>
- /// Inserts a measure unit
- /// </summary>
- /// <param name="measure">Measure unit</param>
- public virtual async Task InsertMeasureUnit(MeasureUnit measure)
- {
- ArgumentNullException.ThrowIfNull(measure);
+ /// <summary>
+ /// Inserts a measure unit
+ /// </summary>
+ /// <param name="measure">Measure unit</param>
+ public virtual async Task InsertMeasureUnit(MeasureUnit measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _measureUnitRepository.InsertAsync(measure);
+ await _measureUnitRepository.InsertAsync(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
- //event notification
- await _mediator.EntityInserted(measure);
- }
+ //event notification
+ await _mediator.EntityInserted(measure);
+ }
- /// <summary>
- /// Updates the measure unit
- /// </summary>
- /// <param name="measure">Measure unit</param>
- public virtual async Task UpdateMeasureUnit(MeasureUnit measure)
- {
- ArgumentNullException.ThrowIfNull(measure);
+ /// <summary>
+ /// Updates the measure unit
+ /// </summary>
+ /// <param name="measure">Measure unit</param>
+ public virtual async Task UpdateMeasureUnit(MeasureUnit measure)
+ {
+ ArgumentNullException.ThrowIfNull(measure);
- await _measureUnitRepository.UpdateAsync(measure);
+ await _measureUnitRepository.UpdateAsync(measure);
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
- //event notification
- await _mediator.EntityUpdated(measure);
- }
+ //event notification
+ await _mediator.EntityUpdated(measure);
+ }
- /// <summary>
- /// Deletes measure unit
- /// </summary>
- /// <param name="measureUnit">Measure unit</param>
- public virtual async Task DeleteMeasureUnit(MeasureUnit measureUnit)
- {
- ArgumentNullException.ThrowIfNull(measureUnit);
+ /// <summary>
+ /// Deletes measure unit
+ /// </summary>
+ /// <param name="measureUnit">Measure unit</param>
+ public virtual async Task DeleteMeasureUnit(MeasureUnit measureUnit)
+ {
+ ArgumentNullException.ThrowIfNull(measureUnit);
- //delete
- await _measureUnitRepository.DeleteAsync(measureUnit);
+ //delete
+ await _measureUnitRepository.DeleteAsync(measureUnit);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.MEASUREUNITS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(measureUnit);
- }
+ //event notification
+ await _mediator.EntityDeleted(measureUnit);
+ }
- #endregion
+ #endregion
- #endregion
- }
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs
index bab95e591..ae832ed4e 100644
--- a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs
@@ -1,130 +1,129 @@
using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Common;
-using Grand.Data;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Directory
+namespace Grand.Business.Catalog.Services.Directory;
+
+/// <summary>
+/// Search term service
+/// </summary>
+public class SearchTermService : ISearchTermService
{
+ #region Ctor
+
+ public SearchTermService(IRepository<SearchTerm> searchTermRepository,
+ IMediator mediator)
+ {
+ _searchTermRepository = searchTermRepository;
+ _mediator = mediator;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IRepository<SearchTerm> _searchTermRepository;
+ private readonly IMediator _mediator;
+
+ #endregion
+
+ #region Methods
+
/// <summary>
- /// Search term service
+ /// Deletes a search term record
/// </summary>
- public class SearchTermService : ISearchTermService
+ /// <param name="searchTerm">Search term</param>
+ public virtual async Task DeleteSearchTerm(SearchTerm searchTerm)
{
- #region Fields
-
- private readonly IRepository<SearchTerm> _searchTermRepository;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- public SearchTermService(IRepository<SearchTerm> searchTermRepository,
- IMediator mediator)
- {
- _searchTermRepository = searchTermRepository;
- _mediator = mediator;
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Deletes a search term record
- /// </summary>
- /// <param name="searchTerm">Search term</param>
- public virtual async Task DeleteSearchTerm(SearchTerm searchTerm)
- {
- ArgumentNullException.ThrowIfNull(searchTerm);
-
- await _searchTermRepository.DeleteAsync(searchTerm);
-
- //event notification
- await _mediator.EntityDeleted(searchTerm);
- }
-
- /// <summary>
- /// Gets a search term record by identifier
- /// </summary>
- /// <param name="searchTermId">Search term identifier</param>
- /// <returns>Search term</returns>
- public virtual Task<SearchTerm> GetSearchTermById(string searchTermId)
- {
- return _searchTermRepository.GetByIdAsync(searchTermId);
- }
-
- /// <summary>
- /// Gets a search term record by keyword
- /// </summary>
- /// <param name="keyword">Search term keyword</param>
- /// <param name="storeId">Store identifier</param>
- /// <returns>Search term</returns>
- public virtual async Task<SearchTerm> GetSearchTermByKeyword(string keyword, string storeId)
- {
- if (string.IsNullOrEmpty(keyword))
- return null;
-
- var query = from st in _searchTermRepository.Table
- where st.Keyword == keyword && st.StoreId == storeId
- select st;
- return await Task.FromResult(query.FirstOrDefault());
- }
-
- /// <summary>
- /// Gets a search term statistics
- /// </summary>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>A list search term report lines</returns>
- public virtual async Task<IPagedList<SearchTermReportLine>> GetStats(int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = (from st in _searchTermRepository.Table
- group st by st.Keyword into groupedResult
- select new
- {
- Keyword = groupedResult.Key,
- Count = groupedResult.Sum(o => o.Count)
- })
- .OrderByDescending(m => m.Count)
- .Select(r => new SearchTermReportLine {
- Keyword = r.Keyword,
- Count = r.Count
- });
- return await PagedList<SearchTermReportLine>.Create(query, pageIndex, pageSize);
- }
-
- /// <summary>
- /// Inserts a search term record
- /// </summary>
- /// <param name="searchTerm">Search term</param>
- public virtual async Task InsertSearchTerm(SearchTerm searchTerm)
- {
- ArgumentNullException.ThrowIfNull(searchTerm);
-
- await _searchTermRepository.InsertAsync(searchTerm);
-
- //event notification
- await _mediator.EntityInserted(searchTerm);
- }
-
- /// <summary>
- /// Updates the search term record
- /// </summary>
- /// <param name="searchTerm">Search term</param>
- public virtual async Task UpdateSearchTerm(SearchTerm searchTerm)
- {
- ArgumentNullException.ThrowIfNull(searchTerm);
-
- await _searchTermRepository.UpdateAsync(searchTerm);
-
- //event notification
- await _mediator.EntityUpdated(searchTerm);
- }
-
- #endregion
+ ArgumentNullException.ThrowIfNull(searchTerm);
+
+ await _searchTermRepository.DeleteAsync(searchTerm);
+
+ //event notification
+ await _mediator.EntityDeleted(searchTerm);
}
+
+ /// <summary>
+ /// Gets a search term record by identifier
+ /// </summary>
+ /// <param name="searchTermId">Search term identifier</param>
+ /// <returns>Search term</returns>
+ public virtual Task<SearchTerm> GetSearchTermById(string searchTermId)
+ {
+ return _searchTermRepository.GetByIdAsync(searchTermId);
+ }
+
+ /// <summary>
+ /// Gets a search term record by keyword
+ /// </summary>
+ /// <param name="keyword">Search term keyword</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <returns>Search term</returns>
+ public virtual async Task<SearchTerm> GetSearchTermByKeyword(string keyword, string storeId)
+ {
+ if (string.IsNullOrEmpty(keyword))
+ return null;
+
+ var query = from st in _searchTermRepository.Table
+ where st.Keyword == keyword && st.StoreId == storeId
+ select st;
+ return await Task.FromResult(query.FirstOrDefault());
+ }
+
+ /// <summary>
+ /// Gets a search term statistics
+ /// </summary>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>A list search term report lines</returns>
+ public virtual async Task<IPagedList<SearchTermReportLine>> GetStats(int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = (from st in _searchTermRepository.Table
+ group st by st.Keyword
+ into groupedResult
+ select new {
+ Keyword = groupedResult.Key,
+ Count = groupedResult.Sum(o => o.Count)
+ })
+ .OrderByDescending(m => m.Count)
+ .Select(r => new SearchTermReportLine {
+ Keyword = r.Keyword,
+ Count = r.Count
+ });
+ return await PagedList<SearchTermReportLine>.Create(query, pageIndex, pageSize);
+ }
+
+ /// <summary>
+ /// Inserts a search term record
+ /// </summary>
+ /// <param name="searchTerm">Search term</param>
+ public virtual async Task InsertSearchTerm(SearchTerm searchTerm)
+ {
+ ArgumentNullException.ThrowIfNull(searchTerm);
+
+ await _searchTermRepository.InsertAsync(searchTerm);
+
+ //event notification
+ await _mediator.EntityInserted(searchTerm);
+ }
+
+ /// <summary>
+ /// Updates the search term record
+ /// </summary>
+ /// <param name="searchTerm">Search term</param>
+ public virtual async Task UpdateSearchTerm(SearchTerm searchTerm)
+ {
+ ArgumentNullException.ThrowIfNull(searchTerm);
+
+ await _searchTermRepository.UpdateAsync(searchTerm);
+
+ //event notification
+ await _mediator.EntityUpdated(searchTerm);
+ }
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs
index c251ca9ad..250293664 100644
--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs
@@ -4,17 +4,18 @@ namespace Grand.Business.Catalog.Services.Discounts;
public class DiscountProviderLoader : IDiscountProviderLoader
{
- private readonly IEnumerable<IDiscountProvider> _discountProviders;
private readonly IEnumerable<IDiscountAmountProvider> _discountAmountProviders;
+ private readonly IEnumerable<IDiscountProvider> _discountProviders;
- public DiscountProviderLoader(IEnumerable<IDiscountProvider> discountProviders, IEnumerable<IDiscountAmountProvider> discountAmountProviders)
+ public DiscountProviderLoader(IEnumerable<IDiscountProvider> discountProviders,
+ IEnumerable<IDiscountAmountProvider> discountAmountProviders)
{
_discountProviders = discountProviders;
_discountAmountProviders = discountAmountProviders;
}
/// <summary>
- /// Load discount provider by rule system name
+ /// Load discount provider by rule system name
/// </summary>
/// <param name="ruleSystemName">Rule system name</param>
/// <returns>Found discount</returns>
@@ -29,36 +30,36 @@ public class DiscountProviderLoader : IDiscountProviderLoader
continue;
return discountPlugin;
}
+
return null;
}
/// <summary>
- /// Load all discount providers
+ /// Load all discount providers
/// </summary>
/// <returns>Discount providers</returns>
public virtual IList<IDiscountProvider> LoadAllDiscountProviders()
{
return _discountProviders.ToList();
}
-
+
/// <summary>
- /// Get all discount amount providers
+ /// Get all discount amount providers
/// </summary>
/// <returns></returns>
public virtual IList<IDiscountAmountProvider> LoadDiscountAmountProviders()
{
return _discountAmountProviders.ToList();
}
-
+
/// <summary>
- /// Load discount amountProviderBySystemName
+ /// Load discount amountProviderBySystemName
/// </summary>
/// <param name="systemName"></param>
/// <returns></returns>
public virtual IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName)
{
- return _discountAmountProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
+ return _discountAmountProviders.FirstOrDefault(x =>
+ x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
}
-
-
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs
index 766dedd45..fb3bb627f 100644
--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs
@@ -1,10 +1,10 @@
using Grand.Business.Core.Interfaces.Catalog.Discounts;
using Grand.Business.Core.Queries.Catalog;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Infrastructure.Caching;
@@ -13,462 +13,456 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Discounts
+namespace Grand.Business.Catalog.Services.Discounts;
+
+/// <summary>
+/// Discount service
+/// </summary>
+public class DiscountService : IDiscountService
{
+ #region Ctor
+
/// <summary>
- /// Discount service
+ /// Ctor
/// </summary>
- public class DiscountService : IDiscountService
+ public DiscountService(ICacheBase cacheBase,
+ IRepository<Discount> discountRepository,
+ IRepository<DiscountCoupon> discountCouponRepository,
+ IRepository<DiscountUsageHistory> discountUsageHistoryRepository,
+ IMediator mediator, AccessControlConfig accessControlConfig)
{
+ _cacheBase = cacheBase;
+ _discountRepository = discountRepository;
+ _discountCouponRepository = discountCouponRepository;
+ _discountUsageHistoryRepository = discountUsageHistoryRepository;
+ _mediator = mediator;
+ _accessControlConfig = accessControlConfig;
+ }
- #region Fields
-
- private readonly IRepository<Discount> _discountRepository;
- private readonly IRepository<DiscountCoupon> _discountCouponRepository;
- private readonly IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public DiscountService(ICacheBase cacheBase,
- IRepository<Discount> discountRepository,
- IRepository<DiscountCoupon> discountCouponRepository,
- IRepository<DiscountUsageHistory> discountUsageHistoryRepository,
- IMediator mediator, AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _discountRepository = discountRepository;
- _discountCouponRepository = discountCouponRepository;
- _discountUsageHistoryRepository = discountUsageHistoryRepository;
- _mediator = mediator;
- _accessControlConfig = accessControlConfig;
- }
+ #endregion
- #endregion
+ #region Fields
- #region Methods
+ private readonly IRepository<Discount> _discountRepository;
+ private readonly IRepository<DiscountCoupon> _discountCouponRepository;
+ private readonly IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
+ private readonly AccessControlConfig _accessControlConfig;
- /// <summary>
- /// Gets a discount
- /// </summary>
- /// <param name="discountId">Discount identifier</param>
- /// <returns>Discount</returns>
- public virtual Task<Discount> GetDiscountById(string discountId)
- {
- var key = string.Format(CacheKey.DISCOUNTS_BY_ID_KEY, discountId);
- return _cacheBase.GetAsync(key, () => _discountRepository.GetByIdAsync(discountId));
- }
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets a discount
+ /// </summary>
+ /// <param name="discountId">Discount identifier</param>
+ /// <returns>Discount</returns>
+ public virtual Task<Discount> GetDiscountById(string discountId)
+ {
+ var key = string.Format(CacheKey.DISCOUNTS_BY_ID_KEY, discountId);
+ return _cacheBase.GetAsync(key, () => _discountRepository.GetByIdAsync(discountId));
+ }
+
+ /// <summary>
+ /// Gets active discounts by context
+ /// </summary>
+ /// <returns>Discounts</returns>
+ public virtual async Task<IList<Discount>> GetActiveDiscountsByContext(DiscountType discountType,
+ string storeId = "", string currencyCode = "")
+ {
+ var key = string.Format(CacheKey.DISCOUNTS_CONTEXT_KEY, discountType, storeId, currencyCode);
+ var allDiscounts = await _cacheBase.GetAsync(key, () => GetDiscountsQuery(discountType, storeId, currencyCode));
+
+ var nowUtc = DateTime.UtcNow;
+ var filteredDiscounts =
+ allDiscounts.Where(d => d.IsEnabled &&
+ (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc) &&
+ (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc));
+
+ return filteredDiscounts.ToList();
+ }
+
+ public virtual async Task<IList<Discount>> GetDiscountsQuery(DiscountType? discountType, string storeId = "",
+ string currencyCode = "",
+ string couponCode = "", string discountName = "")
+ {
+ var query = _discountRepository.Table.AsQueryable();
- /// <summary>
- /// Gets active discounts by context
- /// </summary>
- /// <returns>Discounts</returns>
- public virtual async Task<IList<Discount>> GetActiveDiscountsByContext(DiscountType discountType, string storeId = "", string currencyCode = "")
+ if (discountType.HasValue) query = query.Where(d => d.DiscountTypeId == discountType);
+
+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
+ query = query.Where(d => !d.LimitedToStores || d.Stores.Contains(storeId));
+
+ if (!string.IsNullOrEmpty(couponCode))
{
- var key = string.Format(CacheKey.DISCOUNTS_CONTEXT_KEY, discountType, storeId, currencyCode);
- var allDiscounts = await _cacheBase.GetAsync(key, () => GetDiscountsQuery(discountType, storeId, currencyCode));
-
- var nowUtc = DateTime.UtcNow;
- var filteredDiscounts =
- allDiscounts.Where(d => d.IsEnabled &&
- (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc) &&
- (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc));
-
- return filteredDiscounts.ToList();
+ var couponDiscountId = _discountCouponRepository.Table
+ .Where(x => x.CouponCode == couponCode)
+ .Select(x => x.DiscountId)
+ .FirstOrDefault();
+ if (couponDiscountId != default)
+ query = query.Where(d => d.Id == couponDiscountId);
+ else
+ query = query.Where(d => false);
}
- public virtual async Task<IList<Discount>> GetDiscountsQuery(DiscountType? discountType, string storeId = "", string currencyCode = "",
- string couponCode = "", string discountName = "")
- {
- var query = _discountRepository.Table.AsQueryable();
- if (discountType.HasValue)
- {
- query = query.Where(d => d.DiscountTypeId == discountType);
- }
+ if (!string.IsNullOrEmpty(discountName))
+ query = query.Where(d =>
+ d.Name != null && d.Name.Contains(discountName, StringComparison.CurrentCultureIgnoreCase));
- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)
- {
- query = query.Where(d => !d.LimitedToStores || d.Stores.Contains(storeId));
- }
+ if (!string.IsNullOrEmpty(currencyCode)) query = query.Where(d => d.CurrencyCode == currencyCode);
- if (!string.IsNullOrEmpty(couponCode))
- {
- var couponDiscountId = _discountCouponRepository.Table
- .Where(x => x.CouponCode == couponCode)
- .Select(x => x.DiscountId)
- .FirstOrDefault();
- if (couponDiscountId != default)
- query = query.Where(d => d.Id == couponDiscountId);
- else
- query = query.Where(d => false);
- }
+ query = query.OrderBy(d => d.Name);
- if (!string.IsNullOrEmpty(discountName))
- {
- query = query.Where(d => d.Name != null && d.Name.Contains(discountName, StringComparison.CurrentCultureIgnoreCase));
- }
+ return await Task.FromResult(query.ToList());
+ }
- if (!string.IsNullOrEmpty(currencyCode))
- {
- query = query.Where(d => d.CurrencyCode == currencyCode);
- }
+ /// <summary>
+ /// Inserts a discount
+ /// </summary>
+ /// <param name="discount">Discount</param>
+ public virtual async Task InsertDiscount(Discount discount)
+ {
+ ArgumentNullException.ThrowIfNull(discount);
- query = query.OrderBy(d => d.Name);
+ await _discountRepository.InsertAsync(discount);
- return await Task.FromResult(query.ToList());
- }
-
- /// <summary>
- /// Inserts a discount
- /// </summary>
- /// <param name="discount">Discount</param>
- public virtual async Task InsertDiscount(Discount discount)
- {
- ArgumentNullException.ThrowIfNull(discount);
-
- await _discountRepository.InsertAsync(discount);
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityInserted(discount);
+ }
- //event notification
- await _mediator.EntityInserted(discount);
- }
+ /// <summary>
+ /// Updates the discount
+ /// </summary>
+ /// <param name="discount">Discount</param>
+ public virtual async Task UpdateDiscount(Discount discount)
+ {
+ ArgumentNullException.ThrowIfNull(discount);
- /// <summary>
- /// Updates the discount
- /// </summary>
- /// <param name="discount">Discount</param>
- public virtual async Task UpdateDiscount(Discount discount)
- {
- ArgumentNullException.ThrowIfNull(discount);
+ await _discountRepository.UpdateAsync(discount);
- await _discountRepository.UpdateAsync(discount);
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityUpdated(discount);
+ }
- //event notification
- await _mediator.EntityUpdated(discount);
- }
+ /// <summary>
+ /// Delete discount
+ /// </summary>
+ /// <param name="discount">Discount</param>
+ public virtual async Task DeleteDiscount(Discount discount)
+ {
+ ArgumentNullException.ThrowIfNull(discount);
- /// <summary>
- /// Delete discount
- /// </summary>
- /// <param name="discount">Discount</param>
- public virtual async Task DeleteDiscount(Discount discount)
- {
- ArgumentNullException.ThrowIfNull(discount);
+ await _discountRepository.DeleteAsync(discount);
- await _discountRepository.DeleteAsync(discount);
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityDeleted(discount);
+ }
- //event notification
- await _mediator.EntityDeleted(discount);
- }
+ /// <summary>
+ /// Get discount by coupon code
+ /// </summary>
+ /// <param name="couponCode">Coupon code</param>
+ /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
+ /// <returns>Discount</returns>
+ public virtual async Task<Discount> GetDiscountByCouponCode(string couponCode, bool showHidden = false)
+ {
+ if (string.IsNullOrWhiteSpace(couponCode))
+ return null;
- /// <summary>
- /// Get discount by coupon code
- /// </summary>
- /// <param name="couponCode">Coupon code</param>
- /// <param name="showHidden">A value that indicates if it should shows hidden records</param>
- /// <returns>Discount</returns>
- public virtual async Task<Discount> GetDiscountByCouponCode(string couponCode, bool showHidden = false)
- {
- if (string.IsNullOrWhiteSpace(couponCode))
- return null;
+ var coupon = await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode);
+ if (coupon == null)
+ return null;
- var coupon = await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode);
- if (coupon == null)
- return null;
+ var discount = await GetDiscountById(coupon.DiscountId);
+ return discount;
+ }
- var discount = await GetDiscountById(coupon.DiscountId);
- return discount;
- }
+ /// <summary>
+ /// Get all coupon codes for discount
+ /// </summary>
+ /// <param name="discountId"></param>
+ /// <param name="pageIndex"></param>
+ /// <param name="pageSize"></param>
+ /// <returns></returns>
+ public virtual async Task<IPagedList<DiscountCoupon>> GetAllCouponCodesByDiscountId(string discountId,
+ int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = from d in _discountCouponRepository.Table
+ select d;
- /// <summary>
- /// Get all coupon codes for discount
- /// </summary>
- /// <param name="discountId"></param>
- /// <param name="pageIndex"></param>
- /// <param name="pageSize"></param>
- /// <returns></returns>
- public virtual async Task<IPagedList<DiscountCoupon>> GetAllCouponCodesByDiscountId(string discountId, int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from d in _discountCouponRepository.Table
- select d;
+ if (!string.IsNullOrEmpty(discountId))
+ query = query.Where(duh => duh.DiscountId == discountId);
+ query = query.OrderByDescending(c => c.CouponCode);
- if (!string.IsNullOrEmpty(discountId))
- query = query.Where(duh => duh.DiscountId == discountId);
- query = query.OrderByDescending(c => c.CouponCode);
+ return await PagedList<DiscountCoupon>.Create(query, pageIndex, pageSize);
+ }
- return await PagedList<DiscountCoupon>.Create(query, pageIndex, pageSize);
- }
+ /// <summary>
+ /// Gets a discount
+ /// </summary>
+ /// <returns>Discount</returns>
+ public virtual Task<DiscountCoupon> GetDiscountCodeById(string id)
+ {
+ return _discountCouponRepository.GetByIdAsync(id);
+ }
- /// <summary>
- /// Gets a discount
- /// </summary>
- /// <returns>Discount</returns>
- public virtual Task<DiscountCoupon> GetDiscountCodeById(string id)
- {
- return _discountCouponRepository.GetByIdAsync(id);
- }
+ /// <summary>
+ /// Get discount code by discount code
+ /// </summary>
+ /// <param name="couponCode">Coupon code</param>
+ /// <returns></returns>
+ public virtual async Task<DiscountCoupon> GetDiscountCodeByCode(string couponCode)
+ {
+ return await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode);
+ }
- /// <summary>
- /// Get discount code by discount code
- /// </summary>
- /// <param name="couponCode">Coupon code</param>
- /// <returns></returns>
- public virtual async Task<DiscountCoupon> GetDiscountCodeByCode(string couponCode)
- {
- return await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode);
- }
+ /// <summary>
+ /// Delete discount code
+ /// </summary>
+ /// <param name="coupon"></param>
+ public virtual async Task DeleteDiscountCoupon(DiscountCoupon coupon)
+ {
+ await _discountCouponRepository.DeleteAsync(coupon);
- /// <summary>
- /// Delete discount code
- /// </summary>
- /// <param name="coupon"></param>
- public virtual async Task DeleteDiscountCoupon(DiscountCoupon coupon)
- {
- await _discountCouponRepository.DeleteAsync(coupon);
-
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ }
- /// <summary>
- /// Insert discount code
- /// </summary>
- /// <param name="coupon"></param>
- public virtual async Task InsertDiscountCoupon(DiscountCoupon coupon)
- {
- await _discountCouponRepository.InsertAsync(coupon);
-
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- }
+ /// <summary>
+ /// Insert discount code
+ /// </summary>
+ /// <param name="coupon"></param>
+ public virtual async Task InsertDiscountCoupon(DiscountCoupon coupon)
+ {
+ await _discountCouponRepository.InsertAsync(coupon);
- /// <summary>
- /// Update discount code - set as used or not
- /// </summary>
- /// <param name="couponCode"></param>
- /// <param name="used"></param>
- public virtual async Task DiscountCouponSetAsUsed(string couponCode, bool used)
- {
- if (string.IsNullOrEmpty(couponCode))
- return;
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ }
- var coupon = await GetDiscountCodeByCode(couponCode);
- if (coupon != null)
- {
- if (used)
- {
- coupon.Used = true;
- coupon.Qty++;
- }
- else
- {
- coupon.Qty -= 1;
- coupon.Used = coupon.Qty > 0;
- }
- await _discountCouponRepository.UpdateAsync(coupon);
- }
- }
+ /// <summary>
+ /// Update discount code - set as used or not
+ /// </summary>
+ /// <param name="couponCode"></param>
+ /// <param name="used"></param>
+ public virtual async Task DiscountCouponSetAsUsed(string couponCode, bool used)
+ {
+ if (string.IsNullOrEmpty(couponCode))
+ return;
- /// <summary>
- /// Cancel discount if order was canceled or deleted
- /// </summary>
- /// <param name="orderId"></param>
- public virtual async Task CancelDiscount(string orderId)
+ var coupon = await GetDiscountCodeByCode(couponCode);
+ if (coupon != null)
{
- var discountUsage = _discountUsageHistoryRepository.Table.Where(x => x.OrderId == orderId).ToList();
- foreach (var item in discountUsage)
+ if (used)
{
- await DiscountCouponSetAsUsed(item.CouponCode, false);
- item.Canceled = true;
- await UpdateDiscountUsageHistory(item);
+ coupon.Used = true;
+ coupon.Qty++;
}
+ else
+ {
+ coupon.Qty -= 1;
+ coupon.Used = coupon.Qty > 0;
+ }
+
+ await _discountCouponRepository.UpdateAsync(coupon);
}
+ }
-
- /// <summary>
- /// Gets a discount usage history record
- /// </summary>
- /// <param name="discountUsageHistoryId">Discount usage history record identifier</param>
- /// <returns>Discount usage history</returns>
- public virtual Task<DiscountUsageHistory> GetDiscountUsageHistoryById(string discountUsageHistoryId)
+ /// <summary>
+ /// Cancel discount if order was canceled or deleted
+ /// </summary>
+ /// <param name="orderId"></param>
+ public virtual async Task CancelDiscount(string orderId)
+ {
+ var discountUsage = _discountUsageHistoryRepository.Table.Where(x => x.OrderId == orderId).ToList();
+ foreach (var item in discountUsage)
{
- return _discountUsageHistoryRepository.GetByIdAsync(discountUsageHistoryId);
+ await DiscountCouponSetAsUsed(item.CouponCode, false);
+ item.Canceled = true;
+ await UpdateDiscountUsageHistory(item);
}
-
- /// <summary>
- /// Insert discount usage history item
- /// </summary>
- /// <param name="discountUsageHistory">Discount usage history item</param>
- public virtual async Task InsertDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
- {
- ArgumentNullException.ThrowIfNull(discountUsageHistory);
+ }
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
- //Support for coupon code
- await DiscountCouponSetAsUsed(discountUsageHistory.CouponCode, true);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- //event notification
- await _mediator.EntityInserted(discountUsageHistory);
- }
+ /// <summary>
+ /// Gets a discount usage history record
+ /// </summary>
+ /// <param name="discountUsageHistoryId">Discount usage history record identifier</param>
+ /// <returns>Discount usage history</returns>
+ public virtual Task<DiscountUsageHistory> GetDiscountUsageHistoryById(string discountUsageHistoryId)
+ {
+ return _discountUsageHistoryRepository.GetByIdAsync(discountUsageHistoryId);
+ }
+ /// <summary>
+ /// Insert discount usage history item
+ /// </summary>
+ /// <param name="discountUsageHistory">Discount usage history item</param>
+ public virtual async Task InsertDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
+ {
+ ArgumentNullException.ThrowIfNull(discountUsageHistory);
- /// <summary>
- /// Update discount usage history item
- /// </summary>
- /// <param name="discountUsageHistory">Discount usage history item</param>
- public virtual async Task UpdateDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
- {
- ArgumentNullException.ThrowIfNull(discountUsageHistory);
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
- await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory);
+ //Support for coupon code
+ await DiscountCouponSetAsUsed(discountUsageHistory.CouponCode, true);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityInserted(discountUsageHistory);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- //event notification
- await _mediator.EntityUpdated(discountUsageHistory);
- }
+ /// <summary>
+ /// Update discount usage history item
+ /// </summary>
+ /// <param name="discountUsageHistory">Discount usage history item</param>
+ public virtual async Task UpdateDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
+ {
+ ArgumentNullException.ThrowIfNull(discountUsageHistory);
- /// <summary>
- /// Delete discount usage history record
- /// </summary>
- /// <param name="discountUsageHistory">Discount usage history record</param>
- public virtual async Task DeleteDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
- {
- ArgumentNullException.ThrowIfNull(discountUsageHistory);
+ await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory);
- await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory);
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityUpdated(discountUsageHistory);
+ }
- //event notification
- await _mediator.EntityDeleted(discountUsageHistory);
- }
+ /// <summary>
+ /// Delete discount usage history record
+ /// </summary>
+ /// <param name="discountUsageHistory">Discount usage history record</param>
+ public virtual async Task DeleteDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
+ {
+ ArgumentNullException.ThrowIfNull(discountUsageHistory);
- /// <summary>
- /// Get discount amount
- /// </summary>
- /// <param name="discount">Discount</param>
- /// <param name="amount">Amount</param>
- /// <param name="currency">currency</param>
- /// <param name="customer">Customer</param>
- /// <param name="product">Product</param>
- public virtual async Task<double> GetDiscountAmount(Discount discount, Customer customer, Currency currency, Product product, double amount)
- {
- ArgumentNullException.ThrowIfNull(discount);
+ await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory);
- //calculate discount amount
- double result;
- if (!discount.CalculateByPlugin)
- {
- if (discount.UsePercentage)
- result = (float)amount * (float)discount.DiscountPercentage / 100f;
- else
- {
- result = discount.DiscountAmount;
- }
- }
- else
- {
- result = await _mediator.Send(new GetDiscountAmountProvider(discount, customer, product, currency, amount));
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);
- //validate maximum discount amount
- if (discount.UsePercentage &&
- discount.MaximumDiscountAmount.HasValue &&
- result > discount.MaximumDiscountAmount.Value)
- result = discount.MaximumDiscountAmount.Value;
+ //event notification
+ await _mediator.EntityDeleted(discountUsageHistory);
+ }
- if (result < 0)
- result = 0;
+ /// <summary>
+ /// Get discount amount
+ /// </summary>
+ /// <param name="discount">Discount</param>
+ /// <param name="amount">Amount</param>
+ /// <param name="currency">currency</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="product">Product</param>
+ public virtual async Task<double> GetDiscountAmount(Discount discount, Customer customer, Currency currency,
+ Product product, double amount)
+ {
+ ArgumentNullException.ThrowIfNull(discount);
- return result;
+ //calculate discount amount
+ double result;
+ if (!discount.CalculateByPlugin)
+ {
+ if (discount.UsePercentage)
+ result = (float)amount * (float)discount.DiscountPercentage / 100f;
+ else
+ result = discount.DiscountAmount;
}
-
- /// <summary>
- /// Get preferred discount (with maximum discount value)
- /// </summary>
- /// <param name="discounts">A list of discounts to check</param>
- /// <param name="customer">customer</param>
- /// <param name="currency">currency</param>
- /// <param name="product"></param>
- /// <param name="amount">Amount</param>
- /// <returns>Preferred discount</returns>
- public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(
- IList<ApplyDiscount> discounts, Customer customer, Currency currency, Product product,
- double amount)
+ else
{
- ArgumentNullException.ThrowIfNull(discounts);
+ result = await _mediator.Send(new GetDiscountAmountProvider(discount, customer, product, currency, amount));
+ }
- var appliedDiscount = new List<ApplyDiscount>();
- double discountAmount = 0;
- if (!discounts.Any())
- return (appliedDiscount, discountAmount);
+ //validate maximum discount amount
+ if (discount.UsePercentage &&
+ discount.MaximumDiscountAmount.HasValue &&
+ result > discount.MaximumDiscountAmount.Value)
+ result = discount.MaximumDiscountAmount.Value;
- //check simple discounts
- foreach (var applieddiscount in discounts)
- {
- var discount = await GetDiscountById(applieddiscount.DiscountId);
- var currentDiscountValue = await GetDiscountAmount(discount, customer, currency, product, amount);
- if (!(currentDiscountValue > discountAmount)) continue;
- discountAmount = currentDiscountValue;
- appliedDiscount.Clear();
- appliedDiscount.Add(applieddiscount);
- }
- //cumulative discounts
- var cumulativeDiscounts = discounts.Where(x => x.IsCumulative).ToList();
- if (cumulativeDiscounts.Count <= 1) return (appliedDiscount, discountAmount);
- {
- double cumulativeDiscountAmount = 0;
- foreach (var item in cumulativeDiscounts)
- {
- var discount = await GetDiscountById(item.DiscountId);
- cumulativeDiscountAmount += await GetDiscountAmount(discount, customer, currency, product, amount);
- }
-
- if (!(cumulativeDiscountAmount > discountAmount)) return (appliedDiscount, discountAmount);
- discountAmount = cumulativeDiscountAmount;
-
- appliedDiscount.Clear();
- appliedDiscount.AddRange(cumulativeDiscounts);
- }
+ if (result < 0)
+ result = 0;
+
+ return result;
+ }
+
+ /// <summary>
+ /// Get preferred discount (with maximum discount value)
+ /// </summary>
+ /// <param name="discounts">A list of discounts to check</param>
+ /// <param name="customer">customer</param>
+ /// <param name="currency">currency</param>
+ /// <param name="product"></param>
+ /// <param name="amount">Amount</param>
+ /// <returns>Preferred discount</returns>
+ public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(
+ IList<ApplyDiscount> discounts, Customer customer, Currency currency, Product product,
+ double amount)
+ {
+ ArgumentNullException.ThrowIfNull(discounts);
+ var appliedDiscount = new List<ApplyDiscount>();
+ double discountAmount = 0;
+ if (!discounts.Any())
return (appliedDiscount, discountAmount);
+
+ //check simple discounts
+ foreach (var applieddiscount in discounts)
+ {
+ var discount = await GetDiscountById(applieddiscount.DiscountId);
+ var currentDiscountValue = await GetDiscountAmount(discount, customer, currency, product, amount);
+ if (!(currentDiscountValue > discountAmount)) continue;
+ discountAmount = currentDiscountValue;
+ appliedDiscount.Clear();
+ appliedDiscount.Add(applieddiscount);
}
- /// <summary>
- /// Get preferred discount (with maximum discount value)
- /// </summary>
- /// <param name="discounts">A list of discounts to check</param>
- /// <param name="customer"></param>
- /// <param name="currency">currency</param>
- /// <param name="amount">Amount</param>
- /// <returns>Preferred discount</returns>
- public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(
- IList<ApplyDiscount> discounts,
- Customer customer,
- Currency currency,
- double amount)
+ //cumulative discounts
+ var cumulativeDiscounts = discounts.Where(x => x.IsCumulative).ToList();
+ if (cumulativeDiscounts.Count <= 1) return (appliedDiscount, discountAmount);
{
- return await GetPreferredDiscount(discounts, customer, currency, null, amount);
+ double cumulativeDiscountAmount = 0;
+ foreach (var item in cumulativeDiscounts)
+ {
+ var discount = await GetDiscountById(item.DiscountId);
+ cumulativeDiscountAmount += await GetDiscountAmount(discount, customer, currency, product, amount);
+ }
+
+ if (!(cumulativeDiscountAmount > discountAmount)) return (appliedDiscount, discountAmount);
+ discountAmount = cumulativeDiscountAmount;
+
+ appliedDiscount.Clear();
+ appliedDiscount.AddRange(cumulativeDiscounts);
}
- #endregion
+ return (appliedDiscount, discountAmount);
+ }
+
+ /// <summary>
+ /// Get preferred discount (with maximum discount value)
+ /// </summary>
+ /// <param name="discounts">A list of discounts to check</param>
+ /// <param name="customer"></param>
+ /// <param name="currency">currency</param>
+ /// <param name="amount">Amount</param>
+ /// <returns>Preferred discount</returns>
+ public virtual async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(
+ IList<ApplyDiscount> discounts,
+ Customer customer,
+ Currency currency,
+ double amount)
+ {
+ return await GetPreferredDiscount(discounts, customer, currency, null, amount);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs
index 975195374..46f0ecabd 100644
--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs
@@ -14,12 +14,12 @@ namespace Grand.Business.Catalog.Services.Discounts;
public class DiscountValidationService : IDiscountValidationService
{
+ private readonly IRepository<DiscountCoupon> _discountCouponRepository;
private readonly IDiscountProviderLoader _discountProviderLoader;
private readonly IMediator _mediator;
- private readonly IRepository<DiscountCoupon> _discountCouponRepository;
-
+
public DiscountValidationService(
- IDiscountProviderLoader discountProviderLoader,
+ IDiscountProviderLoader discountProviderLoader,
IRepository<DiscountCoupon> discountCouponRepository,
IMediator mediator)
{
@@ -29,14 +29,15 @@ public class DiscountValidationService : IDiscountValidationService
}
/// <summary>
- /// Validate discount
+ /// Validate discount
/// </summary>
/// <param name="discount">Discount</param>
/// <param name="customer">Customer</param>
/// <param name="store">Store</param>
/// <param name="currency">Currency</param>
/// <returns>Discount validation result</returns>
- public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store,
+ public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer,
+ Store store,
Currency currency)
{
ArgumentNullException.ThrowIfNull(discount);
@@ -49,7 +50,7 @@ public class DiscountValidationService : IDiscountValidationService
}
/// <summary>
- /// Validate discount
+ /// Validate discount
/// </summary>
/// <param name="discount">Discount</param>
/// <param name="customer">Customer</param>
@@ -69,7 +70,7 @@ public class DiscountValidationService : IDiscountValidationService
}
/// <summary>
- /// Validate discount
+ /// Validate discount
/// </summary>
/// <param name="discount">Discount</param>
/// <param name="customer">Customer</param>
@@ -77,7 +78,8 @@ public class DiscountValidationService : IDiscountValidationService
/// <param name="currency">Currency</param>
/// <param name="couponCodesToValidate">Coupon codes</param>
/// <returns>Discount validation result</returns>
- public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store,
+ public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer,
+ Store store,
Currency currency, string[] couponCodesToValidate)
{
ArgumentNullException.ThrowIfNull(discount);
@@ -90,10 +92,10 @@ public class DiscountValidationService : IDiscountValidationService
return result;
//time range check
- DateTime now = DateTime.UtcNow;
+ var now = DateTime.UtcNow;
if (discount.StartDateUtc.HasValue)
{
- DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc);
+ var startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc);
if (startDate.CompareTo(now) > 0)
{
result.UserErrorResource = "ShoppingCart.Discount.NotStartedYet";
@@ -103,7 +105,7 @@ public class DiscountValidationService : IDiscountValidationService
if (discount.EndDateUtc.HasValue)
{
- DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc);
+ var endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc);
if (endDate.CompareTo(now) < 0)
{
result.UserErrorResource = "ShoppingCart.Discount.Expired";
@@ -125,7 +127,6 @@ public class DiscountValidationService : IDiscountValidationService
return result;
var exists = false;
foreach (var item in couponCodesToValidate)
- {
if (discount.Reused)
{
if (!await ExistsCodeInDiscount(item, discount.Id, null)) continue;
@@ -138,7 +139,6 @@ public class DiscountValidationService : IDiscountValidationService
result.CouponCode = item;
exists = true;
}
- }
if (!exists)
return result;
@@ -163,14 +163,16 @@ public class DiscountValidationService : IDiscountValidationService
{
case DiscountLimitationType.NTimes:
{
- var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id, PageSize = 1 });
+ var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery
+ { DiscountId = discount.Id, PageSize = 1 });
if (usedTimes.TotalCount >= discount.LimitationTimes)
return result;
}
break;
case DiscountLimitationType.NTimesPerUser:
{
- var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id, CustomerId = customer.Id, PageSize = 1 });
+ var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery
+ { DiscountId = discount.Id, CustomerId = customer.Id, PageSize = 1 });
if (usedTimes.TotalCount >= discount.LimitationTimes)
{
result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedAnymore";
@@ -218,7 +220,7 @@ public class DiscountValidationService : IDiscountValidationService
}
/// <summary>
- /// Exist coupon code in discount
+ /// Exist coupon code in discount
/// </summary>
/// <param name="couponCode"></param>
/// <param name="discountId"></param>
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs
index bb7f75b50..ae03c45b7 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs
@@ -11,127 +11,121 @@ using Grand.Domain.Media;
using Grand.Domain.Seo;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class BrandImportDataObject : IImportDataObject<BrandDto>
{
- public class BrandImportDataObject : IImportDataObject<BrandDto>
+ private readonly IBrandLayoutService _brandLayoutService;
+ private readonly IBrandService _brandService;
+ private readonly ILanguageService _languageService;
+ private readonly IPictureService _pictureService;
+
+ private readonly SeoSettings _seoSetting;
+ private readonly ISlugService _slugService;
+
+ public BrandImportDataObject(
+ IBrandService brandService,
+ IPictureService pictureService,
+ IBrandLayoutService brandLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
{
- private readonly IBrandService _brandService;
- private readonly IPictureService _pictureService;
- private readonly IBrandLayoutService _brandLayoutService;
- private readonly ISlugService _slugService;
- private readonly ILanguageService _languageService;
-
- private readonly SeoSettings _seoSetting;
-
- public BrandImportDataObject(
- IBrandService brandService,
- IPictureService pictureService,
- IBrandLayoutService brandLayoutService,
- ISlugService slugService,
- ILanguageService languageService,
- SeoSettings seoSetting)
- {
- _brandService = brandService;
- _pictureService = pictureService;
- _brandLayoutService = brandLayoutService;
- _slugService = slugService;
- _languageService = languageService;
+ _brandService = brandService;
+ _pictureService = pictureService;
+ _brandLayoutService = brandLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
- _seoSetting = seoSetting;
- }
+ _seoSetting = seoSetting;
+ }
- public async Task Execute(IEnumerable<BrandDto> data)
- {
- foreach (var item in data)
- {
- await Import(item);
- }
- }
+ public async Task Execute(IEnumerable<BrandDto> data)
+ {
+ foreach (var item in data) await Import(item);
+ }
- private async Task Import(BrandDto brandDto)
- {
- var brand = await _brandService.GetBrandById(brandDto.Id);
- var isNew = brand == null;
+ private async Task Import(BrandDto brandDto)
+ {
+ var brand = await _brandService.GetBrandById(brandDto.Id);
+ var isNew = brand == null;
- if (brand == null) brand = brandDto.MapTo<BrandDto, Brand>();
- else brandDto.MapTo(brand);
+ if (brand == null) brand = brandDto.MapTo<BrandDto, Brand>();
+ else brandDto.MapTo(brand);
- if (!ValidBrand(brand)) return;
+ if (!ValidBrand(brand)) return;
- if (isNew) await _brandService.InsertBrand(brand);
- else await _brandService.UpdateBrand(brand);
+ if (isNew) await _brandService.InsertBrand(brand);
+ else await _brandService.UpdateBrand(brand);
- await UpdateBrandData(brandDto, brand);
+ await UpdateBrandData(brandDto, brand);
+ }
+ private async Task UpdateBrandData(BrandDto brandDto, Brand brand)
+ {
+ if (string.IsNullOrEmpty(brand.BrandLayoutId))
+ {
+ brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault()?.Id;
}
-
- private async Task UpdateBrandData(BrandDto brandDto, Brand brand)
+ else
{
- if (string.IsNullOrEmpty(brand.BrandLayoutId))
+ var layout = await _brandLayoutService.GetBrandLayoutById(brand.BrandLayoutId);
+ if (layout == null)
brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault()?.Id;
- else
- {
- var layout = await _brandLayoutService.GetBrandLayoutById(brand.BrandLayoutId);
- if (layout == null)
- brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault()?.Id;
- }
-
- if (!string.IsNullOrEmpty(brandDto.Picture))
- {
- var picture = await LoadPicture(brandDto.Picture, brand.Name, brand.PictureId);
- if (picture != null)
- brand.PictureId = picture.Id;
- }
-
- var sename = brand.SeName ?? brand.Name;
- sename = await brand.ValidateSeName(sename, brand.Name, true, _seoSetting, _slugService, _languageService);
- brand.SeName = sename;
-
- await _brandService.UpdateBrand(brand);
- await _slugService.SaveSlug(brand, sename, "");
}
- private bool ValidBrand(Brand brand)
+ if (!string.IsNullOrEmpty(brandDto.Picture))
{
- return !string.IsNullOrEmpty(brand.Name);
+ var picture = await LoadPicture(brandDto.Picture, brand.Name, brand.PictureId);
+ if (picture != null)
+ brand.PictureId = picture.Id;
}
- /// <summary>
- /// Creates or loads the image
- /// </summary>
- /// <param name="picturePath">The path to the image file</param>
- /// <param name="name">The name of the object</param>
- /// <param name="picId">Image identifier, may be null</param>
- /// <returns>The image or null if the image has not changed</returns>
- private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ var sename = brand.SeName ?? brand.Name;
+ sename = await brand.ValidateSeName(sename, brand.Name, true, _seoSetting, _slugService, _languageService);
+ brand.SeName = sename;
+
+ await _brandService.UpdateBrand(brand);
+ await _slugService.SaveSlug(brand, sename, "");
+ }
+
+ private bool ValidBrand(Brand brand)
+ {
+ return !string.IsNullOrEmpty(brand.Name);
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
{
- if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
- return null;
-
- var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
- var pictureAlreadyExists = false;
- if (!string.IsNullOrEmpty(picId))
- {
- //compare with existing product pictures
- var existingPicture = await _pictureService.GetPictureById(picId);
-
- var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (existingBinary.SequenceEqual(validatedPictureBinary) ||
- existingBinary.SequenceEqual(newPictureBinary))
- {
- pictureAlreadyExists = true;
- }
- }
-
- if (pictureAlreadyExists) return null;
-
- var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
- _pictureService.GetPictureSeName(name));
- return newPicture;
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ pictureAlreadyExists = true;
}
-
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs
index 1ba15baef..6bce832da 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs
@@ -3,44 +3,42 @@ using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Catalog;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class BrandSchemaProperty : ISchemaProperty<Brand>
{
- public class BrandSchemaProperty : ISchemaProperty<Brand>
- {
- private readonly IPictureService _pictureService;
+ private readonly IPictureService _pictureService;
- public BrandSchemaProperty(IPictureService pictureService)
- {
- _pictureService = pictureService;
- }
+ public BrandSchemaProperty(IPictureService pictureService)
+ {
+ _pictureService = pictureService;
+ }
- public virtual async Task<PropertyByName<Brand>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Brand>("Id", p => p.Id),
- new PropertyByName<Brand>("Name", p => p.Name),
- new PropertyByName<Brand>("Description", p => p.Description),
- new PropertyByName<Brand>("BrandLayoutId", p => p.BrandLayoutId),
- new PropertyByName<Brand>("MetaKeywords", p => p.MetaKeywords),
- new PropertyByName<Brand>("MetaDescription", p => p.MetaDescription),
- new PropertyByName<Brand>("MetaTitle", p => p.MetaTitle),
- new PropertyByName<Brand>("SeName", p => p.SeName),
- new PropertyByName<Brand>("Picture", p => GetPictures(p.PictureId).Result),
- new PropertyByName<Brand>("PageSize", p => p.PageSize),
- new PropertyByName<Brand>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
- new PropertyByName<Brand>("PageSizeOptions", p => p.PageSizeOptions),
- new PropertyByName<Brand>("Published", p => p.Published),
- new PropertyByName<Brand>("DisplayOrder", p => p.DisplayOrder),
- new PropertyByName<Brand>("ExternalId", p => p.ExternalId)
- };
- return await Task.FromResult(properties);
- }
+ public virtual async Task<PropertyByName<Brand>[]> GetProperties()
+ {
+ var properties = new[] {
+ new PropertyByName<Brand>("Id", p => p.Id),
+ new PropertyByName<Brand>("Name", p => p.Name),
+ new PropertyByName<Brand>("Description", p => p.Description),
+ new PropertyByName<Brand>("BrandLayoutId", p => p.BrandLayoutId),
+ new PropertyByName<Brand>("MetaKeywords", p => p.MetaKeywords),
+ new PropertyByName<Brand>("MetaDescription", p => p.MetaDescription),
+ new PropertyByName<Brand>("MetaTitle", p => p.MetaTitle),
+ new PropertyByName<Brand>("SeName", p => p.SeName),
+ new PropertyByName<Brand>("Picture", p => GetPictures(p.PictureId).Result),
+ new PropertyByName<Brand>("PageSize", p => p.PageSize),
+ new PropertyByName<Brand>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
+ new PropertyByName<Brand>("PageSizeOptions", p => p.PageSizeOptions),
+ new PropertyByName<Brand>("Published", p => p.Published),
+ new PropertyByName<Brand>("DisplayOrder", p => p.DisplayOrder),
+ new PropertyByName<Brand>("ExternalId", p => p.ExternalId)
+ };
+ return await Task.FromResult(properties);
+ }
- protected virtual async Task<string> GetPictures(string pictureId)
- {
- var picture = await _pictureService.GetPictureById(pictureId);
- return await _pictureService.GetThumbPhysicalPath(picture);
- }
+ protected virtual async Task<string> GetPictures(string pictureId)
+ {
+ var picture = await _pictureService.GetPictureById(pictureId);
+ return await _pictureService.GetThumbPhysicalPath(picture);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs
index 29962d95a..787eeacfa 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs
@@ -11,128 +11,127 @@ using Grand.Domain.Media;
using Grand.Domain.Seo;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class CategoryImportDataObject : IImportDataObject<CategoryDto>
{
- public class CategoryImportDataObject : IImportDataObject<CategoryDto>
+ private readonly ICategoryLayoutService _categoryLayoutService;
+ private readonly ICategoryService _categoryService;
+ private readonly ILanguageService _languageService;
+ private readonly IPictureService _pictureService;
+
+ private readonly SeoSettings _seoSetting;
+ private readonly ISlugService _slugService;
+
+ public CategoryImportDataObject(
+ ICategoryService categoryService,
+ IPictureService pictureService,
+ ICategoryLayoutService categoryLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
{
- private readonly ICategoryService _categoryService;
- private readonly IPictureService _pictureService;
- private readonly ICategoryLayoutService _categoryLayoutService;
- private readonly ISlugService _slugService;
- private readonly ILanguageService _languageService;
-
- private readonly SeoSettings _seoSetting;
-
- public CategoryImportDataObject(
- ICategoryService categoryService,
- IPictureService pictureService,
- ICategoryLayoutService categoryLayoutService,
- ISlugService slugService,
- ILanguageService languageService,
- SeoSettings seoSetting)
- {
- _categoryService = categoryService;
- _pictureService = pictureService;
- _categoryLayoutService = categoryLayoutService;
- _slugService = slugService;
- _languageService = languageService;
+ _categoryService = categoryService;
+ _pictureService = pictureService;
+ _categoryLayoutService = categoryLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
- _seoSetting = seoSetting;
- }
+ _seoSetting = seoSetting;
+ }
- public async Task Execute(IEnumerable<CategoryDto> data)
- {
- foreach (var item in data)
- {
- await Import(item);
- }
- }
+ public async Task Execute(IEnumerable<CategoryDto> data)
+ {
+ foreach (var item in data) await Import(item);
+ }
- private async Task Import(CategoryDto categoryDto)
- {
- var category = await _categoryService.GetCategoryById(categoryDto.Id);
- var isNew = category == null;
- if (category == null) category = categoryDto.MapTo<CategoryDto, Category>();
- else categoryDto.MapTo(category);
+ private async Task Import(CategoryDto categoryDto)
+ {
+ var category = await _categoryService.GetCategoryById(categoryDto.Id);
+ var isNew = category == null;
+ if (category == null) category = categoryDto.MapTo<CategoryDto, Category>();
+ else categoryDto.MapTo(category);
- if (!ValidCategory(category)) return;
+ if (!ValidCategory(category)) return;
- if (isNew) await _categoryService.InsertCategory(category);
- else await _categoryService.UpdateCategory(category);
+ if (isNew) await _categoryService.InsertCategory(category);
+ else await _categoryService.UpdateCategory(category);
- await UpdateCategoryData(categoryDto, category);
- }
+ await UpdateCategoryData(categoryDto, category);
+ }
- private async Task UpdateCategoryData(CategoryDto categoryDto, Category category)
+ private async Task UpdateCategoryData(CategoryDto categoryDto, Category category)
+ {
+ if (string.IsNullOrEmpty(category.CategoryLayoutId))
{
- if (string.IsNullOrEmpty(category.CategoryLayoutId))
+ category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault()?.Id;
+ }
+ else
+ {
+ var layout = await _categoryLayoutService.GetCategoryLayoutById(category.CategoryLayoutId);
+ if (layout == null)
category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault()?.Id;
- else
- {
- var layout = await _categoryLayoutService.GetCategoryLayoutById(category.CategoryLayoutId);
- if (layout == null)
- category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault()?.Id;
- }
- if(!string.IsNullOrEmpty(category.ParentCategoryId))
- {
- var parentCategory = await _categoryService.GetCategoryById(category.ParentCategoryId);
- if (parentCategory == null)
- category.ParentCategoryId = string.Empty;
- }
- if (!string.IsNullOrEmpty(categoryDto.Picture))
- {
- var picture = await LoadPicture(categoryDto.Picture, category.Name, category.PictureId);
- if (picture != null)
- category.PictureId = picture.Id;
- }
-
- var sename = category.SeName ?? category.Name;
- sename = await category.ValidateSeName(sename, category.Name, true, _seoSetting, _slugService, _languageService);
- category.SeName = sename;
- await _categoryService.UpdateCategory(category);
- await _slugService.SaveSlug(category, sename, "");
}
- private bool ValidCategory(Category category)
+ if (!string.IsNullOrEmpty(category.ParentCategoryId))
{
- return !string.IsNullOrEmpty(category.Name);
+ var parentCategory = await _categoryService.GetCategoryById(category.ParentCategoryId);
+ if (parentCategory == null)
+ category.ParentCategoryId = string.Empty;
}
- /// <summary>
- /// Creates or loads the image
- /// </summary>
- /// <param name="picturePath">The path to the image file</param>
- /// <param name="name">The name of the object</param>
- /// <param name="picId">Image identifier, may be null</param>
- /// <returns>The image or null if the image has not changed</returns>
- private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ if (!string.IsNullOrEmpty(categoryDto.Picture))
{
- if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
- return null;
-
- var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
- var pictureAlreadyExists = false;
- if (!string.IsNullOrEmpty(picId))
- {
- //compare with existing product pictures
- var existingPicture = await _pictureService.GetPictureById(picId);
-
- var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (existingBinary.SequenceEqual(validatedPictureBinary) ||
- existingBinary.SequenceEqual(newPictureBinary))
- {
- pictureAlreadyExists = true;
- }
- }
-
- if (pictureAlreadyExists) return null;
-
- var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
- _pictureService.GetPictureSeName(name));
- return newPicture;
+ var picture = await LoadPicture(categoryDto.Picture, category.Name, category.PictureId);
+ if (picture != null)
+ category.PictureId = picture.Id;
}
+
+ var sename = category.SeName ?? category.Name;
+ sename = await category.ValidateSeName(sename, category.Name, true, _seoSetting, _slugService,
+ _languageService);
+ category.SeName = sename;
+ await _categoryService.UpdateCategory(category);
+ await _slugService.SaveSlug(category, sename, "");
+ }
+
+ private bool ValidCategory(Category category)
+ {
+ return !string.IsNullOrEmpty(category.Name);
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
+ {
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ pictureAlreadyExists = true;
+ }
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs
index 8c1364b21..1ef93750f 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs
@@ -3,49 +3,48 @@ using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Catalog;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class CategorySchemaProperty : ISchemaProperty<Category>
{
- public class CategorySchemaProperty : ISchemaProperty<Category>
+ private readonly IPictureService _pictureService;
+
+ public CategorySchemaProperty(IPictureService pictureService)
{
- private readonly IPictureService _pictureService;
+ _pictureService = pictureService;
+ }
- public CategorySchemaProperty(IPictureService pictureService)
- {
- _pictureService = pictureService;
- }
+ public virtual async Task<PropertyByName<Category>[]> GetProperties()
+ {
+ var properties = new[] {
+ new PropertyByName<Category>("Id", p => p.Id),
+ new PropertyByName<Category>("Name", p => p.Name),
+ new PropertyByName<Category>("Description", p => p.Description),
+ new PropertyByName<Category>("CategoryLayoutId", p => p.CategoryLayoutId),
+ new PropertyByName<Category>("MetaKeywords", p => p.MetaKeywords),
+ new PropertyByName<Category>("MetaDescription", p => p.MetaDescription),
+ new PropertyByName<Category>("MetaTitle", p => p.MetaTitle),
+ new PropertyByName<Category>("SeName", p => p.SeName),
+ new PropertyByName<Category>("ParentCategoryId", p => p.ParentCategoryId),
+ new PropertyByName<Category>("Picture", p => GetPictures(p.PictureId).Result),
+ new PropertyByName<Category>("PageSize", p => p.PageSize),
+ new PropertyByName<Category>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
+ new PropertyByName<Category>("PageSizeOptions", p => p.PageSizeOptions),
+ new PropertyByName<Category>("ShowOnHomePage", p => p.ShowOnHomePage),
+ new PropertyByName<Category>("IncludeInMenu", p => p.IncludeInMenu),
+ new PropertyByName<Category>("Published", p => p.Published),
+ new PropertyByName<Category>("ExternalId", p => p.ExternalId),
+ new PropertyByName<Category>("Flag", p => p.Flag),
+ new PropertyByName<Category>("FlagStyle", p => p.FlagStyle),
+ new PropertyByName<Category>("Icon", p => p.Icon),
+ new PropertyByName<Category>("DisplayOrder", p => p.DisplayOrder)
+ };
+ return await Task.FromResult(properties);
+ }
- public virtual async Task<PropertyByName<Category>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Category>("Id", p => p.Id),
- new PropertyByName<Category>("Name", p => p.Name),
- new PropertyByName<Category>("Description", p => p.Description),
- new PropertyByName<Category>("CategoryLayoutId", p => p.CategoryLayoutId),
- new PropertyByName<Category>("MetaKeywords", p => p.MetaKeywords),
- new PropertyByName<Category>("MetaDescription", p => p.MetaDescription),
- new PropertyByName<Category>("MetaTitle", p => p.MetaTitle),
- new PropertyByName<Category>("SeName", p => p.SeName),
- new PropertyByName<Category>("ParentCategoryId", p => p.ParentCategoryId),
- new PropertyByName<Category>("Picture", p => GetPictures(p.PictureId).Result),
- new PropertyByName<Category>("PageSize", p => p.PageSize),
- new PropertyByName<Category>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
- new PropertyByName<Category>("PageSizeOptions", p => p.PageSizeOptions),
- new PropertyByName<Category>("ShowOnHomePage", p => p.ShowOnHomePage),
- new PropertyByName<Category>("IncludeInMenu", p => p.IncludeInMenu),
- new PropertyByName<Category>("Published", p => p.Published),
- new PropertyByName<Category>("ExternalId", p => p.ExternalId),
- new PropertyByName<Category>("Flag", p => p.Flag),
- new PropertyByName<Category>("FlagStyle", p => p.FlagStyle),
- new PropertyByName<Category>("Icon", p => p.Icon),
- new PropertyByName<Category>("DisplayOrder", p => p.DisplayOrder)
- };
- return await Task.FromResult(properties);
- }
- protected virtual async Task<string> GetPictures(string pictureId)
- {
- var picture = await _pictureService.GetPictureById(pictureId);
- return await _pictureService.GetThumbPhysicalPath(picture);
- }
+ protected virtual async Task<string> GetPictures(string pictureId)
+ {
+ var picture = await _pictureService.GetPictureById(pictureId);
+ return await _pictureService.GetThumbPhysicalPath(picture);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs
index b42ba4858..93e46327a 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs
@@ -11,125 +11,124 @@ using Grand.Domain.Media;
using Grand.Domain.Seo;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class CollectionImportDataObject : IImportDataObject<CollectionDto>
{
- public class CollectionImportDataObject : IImportDataObject<CollectionDto>
+ private readonly ICollectionLayoutService _collectionLayoutService;
+ private readonly ICollectionService _collectionService;
+ private readonly ILanguageService _languageService;
+ private readonly IPictureService _pictureService;
+
+ private readonly SeoSettings _seoSetting;
+ private readonly ISlugService _slugService;
+
+ public CollectionImportDataObject(
+ ICollectionService collectionService,
+ IPictureService pictureService,
+ ICollectionLayoutService collectionLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
{
- private readonly ICollectionService _collectionService;
- private readonly IPictureService _pictureService;
- private readonly ICollectionLayoutService _collectionLayoutService;
- private readonly ISlugService _slugService;
- private readonly ILanguageService _languageService;
-
- private readonly SeoSettings _seoSetting;
-
- public CollectionImportDataObject(
- ICollectionService collectionService,
- IPictureService pictureService,
- ICollectionLayoutService collectionLayoutService,
- ISlugService slugService,
- ILanguageService languageService,
- SeoSettings seoSetting)
- {
- _collectionService = collectionService;
- _pictureService = pictureService;
- _collectionLayoutService = collectionLayoutService;
- _slugService = slugService;
- _languageService = languageService;
+ _collectionService = collectionService;
+ _pictureService = pictureService;
+ _collectionLayoutService = collectionLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
- _seoSetting = seoSetting;
- }
+ _seoSetting = seoSetting;
+ }
- public async Task Execute(IEnumerable<CollectionDto> data)
- {
- foreach (var item in data)
- {
- await Import(item);
- }
- }
+ public async Task Execute(IEnumerable<CollectionDto> data)
+ {
+ foreach (var item in data) await Import(item);
+ }
- private async Task Import(CollectionDto collectionDto)
- {
- var collection = await _collectionService.GetCollectionById(collectionDto.Id);
- var isNew = collection == null;
+ private async Task Import(CollectionDto collectionDto)
+ {
+ var collection = await _collectionService.GetCollectionById(collectionDto.Id);
+ var isNew = collection == null;
- if (collection == null) collection = collectionDto.MapTo<CollectionDto, Collection>();
- else collectionDto.MapTo(collection);
+ if (collection == null) collection = collectionDto.MapTo<CollectionDto, Collection>();
+ else collectionDto.MapTo(collection);
- if (!ValidCollection(collection)) return;
+ if (!ValidCollection(collection)) return;
- if (isNew) await _collectionService.InsertCollection(collection);
- else await _collectionService.UpdateCollection(collection);
+ if (isNew) await _collectionService.InsertCollection(collection);
+ else await _collectionService.UpdateCollection(collection);
- await UpdateCollectionData(collectionDto, collection);
- }
+ await UpdateCollectionData(collectionDto, collection);
+ }
- private async Task UpdateCollectionData(CollectionDto collectionDto, Collection collection)
+ private async Task UpdateCollectionData(CollectionDto collectionDto, Collection collection)
+ {
+ if (string.IsNullOrEmpty(collection.CollectionLayoutId))
{
- if (string.IsNullOrEmpty(collection.CollectionLayoutId))
- collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;
- else
- {
- var layout = await _collectionLayoutService.GetCollectionLayoutById(collection.CollectionLayoutId);
- if (layout == null)
- collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;
- }
-
- if (!string.IsNullOrEmpty(collectionDto.Picture))
- {
- var picture = await LoadPicture(collectionDto.Picture, collection.Name, collection.PictureId);
- if (picture != null)
- collection.PictureId = picture.Id;
- }
-
- var sename = collection.SeName ?? collection.Name;
- sename = await collection.ValidateSeName(sename, collection.Name, true, _seoSetting, _slugService, _languageService);
- collection.SeName = sename;
-
- await _collectionService.UpdateCollection(collection);
- await _slugService.SaveSlug(collection, sename, "");
+ collection.CollectionLayoutId =
+ (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;
+ }
+ else
+ {
+ var layout = await _collectionLayoutService.GetCollectionLayoutById(collection.CollectionLayoutId);
+ if (layout == null)
+ collection.CollectionLayoutId =
+ (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault()?.Id;
}
- private bool ValidCollection(Collection collection)
+ if (!string.IsNullOrEmpty(collectionDto.Picture))
{
- return !string.IsNullOrEmpty(collection.Name);
+ var picture = await LoadPicture(collectionDto.Picture, collection.Name, collection.PictureId);
+ if (picture != null)
+ collection.PictureId = picture.Id;
}
- /// <summary>
- /// Creates or loads the image
- /// </summary>
- /// <param name="picturePath">The path to the image file</param>
- /// <param name="name">The name of the object</param>
- /// <param name="picId">Image identifier, may be null</param>
- /// <returns>The image or null if the image has not changed</returns>
- private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ var sename = collection.SeName ?? collection.Name;
+ sename = await collection.ValidateSeName(sename, collection.Name, true, _seoSetting, _slugService,
+ _languageService);
+ collection.SeName = sename;
+
+ await _collectionService.UpdateCollection(collection);
+ await _slugService.SaveSlug(collection, sename, "");
+ }
+
+ private bool ValidCollection(Collection collection)
+ {
+ return !string.IsNullOrEmpty(collection.Name);
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ private async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
{
- if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
- return null;
-
- var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
- var pictureAlreadyExists = false;
- if (!string.IsNullOrEmpty(picId))
- {
- //compare with existing product pictures
- var existingPicture = await _pictureService.GetPictureById(picId);
-
- var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (existingBinary.SequenceEqual(validatedPictureBinary) ||
- existingBinary.SequenceEqual(newPictureBinary))
- {
- pictureAlreadyExists = true;
- }
- }
-
- if (pictureAlreadyExists) return null;
-
- var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
- _pictureService.GetPictureSeName(name));
- return newPicture;
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ pictureAlreadyExists = true;
}
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs
index 08f52250f..6744233fb 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs
@@ -3,44 +3,42 @@ using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Catalog;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class CollectionSchemaProperty : ISchemaProperty<Collection>
{
- public class CollectionSchemaProperty : ISchemaProperty<Collection>
- {
- private readonly IPictureService _pictureService;
+ private readonly IPictureService _pictureService;
- public CollectionSchemaProperty(IPictureService pictureService)
- {
- _pictureService = pictureService;
- }
+ public CollectionSchemaProperty(IPictureService pictureService)
+ {
+ _pictureService = pictureService;
+ }
- public virtual async Task<PropertyByName<Collection>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Collection>("Id", p => p.Id),
- new PropertyByName<Collection>("Name", p => p.Name),
- new PropertyByName<Collection>("Description", p => p.Description),
- new PropertyByName<Collection>("CollectionLayoutId", p => p.CollectionLayoutId),
- new PropertyByName<Collection>("MetaKeywords", p => p.MetaKeywords),
- new PropertyByName<Collection>("MetaDescription", p => p.MetaDescription),
- new PropertyByName<Collection>("MetaTitle", p => p.MetaTitle),
- new PropertyByName<Collection>("SeName", p => p.SeName),
- new PropertyByName<Collection>("Picture", p => GetPictures(p.PictureId).Result),
- new PropertyByName<Collection>("PageSize", p => p.PageSize),
- new PropertyByName<Collection>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
- new PropertyByName<Collection>("PageSizeOptions", p => p.PageSizeOptions),
- new PropertyByName<Collection>("Published", p => p.Published),
- new PropertyByName<Collection>("DisplayOrder", p => p.DisplayOrder),
- new PropertyByName<Collection>("ExternalId", p => p.ExternalId)
- };
- return await Task.FromResult(properties);
- }
+ public virtual async Task<PropertyByName<Collection>[]> GetProperties()
+ {
+ var properties = new[] {
+ new PropertyByName<Collection>("Id", p => p.Id),
+ new PropertyByName<Collection>("Name", p => p.Name),
+ new PropertyByName<Collection>("Description", p => p.Description),
+ new PropertyByName<Collection>("CollectionLayoutId", p => p.CollectionLayoutId),
+ new PropertyByName<Collection>("MetaKeywords", p => p.MetaKeywords),
+ new PropertyByName<Collection>("MetaDescription", p => p.MetaDescription),
+ new PropertyByName<Collection>("MetaTitle", p => p.MetaTitle),
+ new PropertyByName<Collection>("SeName", p => p.SeName),
+ new PropertyByName<Collection>("Picture", p => GetPictures(p.PictureId).Result),
+ new PropertyByName<Collection>("PageSize", p => p.PageSize),
+ new PropertyByName<Collection>("AllowCustomersToSelectPageSize", p => p.AllowCustomersToSelectPageSize),
+ new PropertyByName<Collection>("PageSizeOptions", p => p.PageSizeOptions),
+ new PropertyByName<Collection>("Published", p => p.Published),
+ new PropertyByName<Collection>("DisplayOrder", p => p.DisplayOrder),
+ new PropertyByName<Collection>("ExternalId", p => p.ExternalId)
+ };
+ return await Task.FromResult(properties);
+ }
- protected virtual async Task<string> GetPictures(string pictureId)
- {
- var picture = await _pictureService.GetPictureById(pictureId);
- return await _pictureService.GetThumbPhysicalPath(picture);
- }
+ protected virtual async Task<string> GetPictures(string pictureId)
+ {
+ var picture = await _pictureService.GetPictureById(pictureId);
+ return await _pictureService.GetThumbPhysicalPath(picture);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs
index 754187f5a..e2dbaca30 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs
@@ -3,34 +3,34 @@ using Grand.Business.Core.Dto;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper;
+
+public class BrandProfile : Profile, IAutoMapperProfile
{
- public class BrandProfile : Profile, IAutoMapperProfile
+ public BrandProfile()
{
- public BrandProfile()
- {
- CreateMap<BrandDto, Brand>()
- .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
- .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
- .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
- .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
- .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
- .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
- .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
- .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
- .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
- .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
- .ForMember(x => x.BrandLayoutId, opt => opt.Condition(z => z.BrandLayoutId != null))
- .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
- .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
- .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
- .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
- .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
- .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
- .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
- .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
- }
-
- public int Order => 0;
+ CreateMap<BrandDto, Brand>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize,
+ opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
+ .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
+ .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
+ .ForMember(x => x.BrandLayoutId, opt => opt.Condition(z => z.BrandLayoutId != null))
+ .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
+ .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
+ .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
+ .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
+ .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
+ .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
+ .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
+ .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
}
-}
+
+ public int Order => 0;
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs
index b8a4f3a33..383bfe4a1 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs
@@ -3,41 +3,42 @@ using Grand.Business.Core.Dto;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper;
+
+public class CategoryProfile : Profile, IAutoMapperProfile
{
- public class CategoryProfile : Profile, IAutoMapperProfile
+ public CategoryProfile()
{
- public CategoryProfile()
- {
- CreateMap<CategoryDto, Category>()
- .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
- .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
- .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
- .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
- .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
- .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
- .ForMember(x => x.FeaturedProductsOnHomePage, opt => opt.Condition(z => z.FeaturedProductsOnHomePage.HasValue))
- .ForMember(x => x.ShowOnSearchBox, opt => opt.Condition(z => z.ShowOnSearchBox.HasValue))
- .ForMember(x => x.SearchBoxDisplayOrder, opt => opt.Condition(z => z.SearchBoxDisplayOrder.HasValue))
- .ForMember(x => x.HideOnCatalog, opt => opt.Condition(z => z.HideOnCatalog.HasValue))
- .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
- .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
- .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
- .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
- .ForMember(x => x.CategoryLayoutId, opt => opt.Condition(z => z.CategoryLayoutId != null))
- .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
- .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
- .ForMember(x => x.Flag, opt => opt.Condition(z => z.Flag != null))
- .ForMember(x => x.FlagStyle, opt => opt.Condition(z => z.FlagStyle != null))
- .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
- .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
- .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
- .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
- .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
- .ForMember(x => x.ParentCategoryId, opt => opt.Condition(z => z.ParentCategoryId != null))
- .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
- }
-
- public int Order => 0;
+ CreateMap<CategoryDto, Category>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize,
+ opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.FeaturedProductsOnHomePage,
+ opt => opt.Condition(z => z.FeaturedProductsOnHomePage.HasValue))
+ .ForMember(x => x.ShowOnSearchBox, opt => opt.Condition(z => z.ShowOnSearchBox.HasValue))
+ .ForMember(x => x.SearchBoxDisplayOrder, opt => opt.Condition(z => z.SearchBoxDisplayOrder.HasValue))
+ .ForMember(x => x.HideOnCatalog, opt => opt.Condition(z => z.HideOnCatalog.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
+ .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
+ .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
+ .ForMember(x => x.CategoryLayoutId, opt => opt.Condition(z => z.CategoryLayoutId != null))
+ .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
+ .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
+ .ForMember(x => x.Flag, opt => opt.Condition(z => z.Flag != null))
+ .ForMember(x => x.FlagStyle, opt => opt.Condition(z => z.FlagStyle != null))
+ .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
+ .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
+ .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
+ .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
+ .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
+ .ForMember(x => x.ParentCategoryId, opt => opt.Condition(z => z.ParentCategoryId != null))
+ .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
}
-}
+
+ public int Order => 0;
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs
index 8cc17ac59..0e72900d6 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs
@@ -3,34 +3,36 @@ using Grand.Business.Core.Dto;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper;
+
+public class CollectionProfile : Profile, IAutoMapperProfile
{
- public class CollectionProfile : Profile, IAutoMapperProfile
+ public CollectionProfile()
{
- public CollectionProfile()
- {
- CreateMap<CollectionDto, Collection>()
- .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
- .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
- .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
- .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
- .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
- .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
- .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
- .ForMember(x => x.FeaturedProductsOnHomePage, opt => opt.Condition(z => z.FeaturedProductsOnHomePage.HasValue))
- .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
- .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
- .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
- .ForMember(x => x.CollectionLayoutId, opt => opt.Condition(z => z.CollectionLayoutId != null))
- .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
- .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
- .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
- .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
- .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
- .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
- .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
- .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
- }
- public int Order => 0;
+ CreateMap<CollectionDto, Collection>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize,
+ opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.FeaturedProductsOnHomePage,
+ opt => opt.Condition(z => z.FeaturedProductsOnHomePage.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
+ .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
+ .ForMember(x => x.BottomDescription, opt => opt.Condition(z => z.BottomDescription != null))
+ .ForMember(x => x.CollectionLayoutId, opt => opt.Condition(z => z.CollectionLayoutId != null))
+ .ForMember(x => x.Description, opt => opt.Condition(z => z.Description != null))
+ .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
+ .ForMember(x => x.Icon, opt => opt.Condition(z => z.Icon != null))
+ .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
+ .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
+ .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
+ .ForMember(x => x.PageSizeOptions, opt => opt.Condition(z => z.PageSizeOptions != null))
+ .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null));
}
-}
+
+ public int Order => 0;
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs
index e4268ece8..3d2bdc73b 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs
@@ -3,124 +3,127 @@ using Grand.Business.Core.Dto;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper;
+
+public class ProductProfile : Profile, IAutoMapperProfile
{
- public class ProductProfile : Profile, IAutoMapperProfile
+ public ProductProfile()
{
- public ProductProfile()
- {
- CreateMap<ProductDto, Product>()
- .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
- .ForMember(x => x.ProductTypeId, opt => opt.Condition(z => z.ProductTypeId.HasValue))
- .ForMember(x => x.VisibleIndividually, opt => opt.Condition(z => z.VisibleIndividually.HasValue))
- .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
- .ForMember(x => x.BestSeller, opt => opt.Condition(z => z.BestSeller.HasValue))
- .ForMember(x => x.AllowCustomerReviews, opt => opt.Condition(z => z.AllowCustomerReviews.HasValue))
- .ForMember(x => x.ApprovedRatingSum, opt => opt.Condition(z => z.ApprovedRatingSum.HasValue))
- .ForMember(x => x.NotApprovedRatingSum, opt => opt.Condition(z => z.NotApprovedRatingSum.HasValue))
- .ForMember(x => x.ApprovedTotalReviews, opt => opt.Condition(z => z.ApprovedTotalReviews.HasValue))
- .ForMember(x => x.NotApprovedTotalReviews, opt => opt.Condition(z => z.NotApprovedTotalReviews.HasValue))
- .ForMember(x => x.IsGiftVoucher, opt => opt.Condition(z => z.IsGiftVoucher.HasValue))
- .ForMember(x => x.GiftVoucherTypeId, opt => opt.Condition(z => z.GiftVoucherTypeId.HasValue))
- .ForMember(x => x.OverGiftAmount, opt => opt.Condition(z => z.OverGiftAmount.HasValue))
- .ForMember(x => x.RequireOtherProducts, opt => opt.Condition(z => z.RequireOtherProducts.HasValue))
- .ForMember(x => x.AutoAddRequiredProducts, opt => opt.Condition(z => z.AutoAddRequiredProducts.HasValue))
- .ForMember(x => x.IsDownload, opt => opt.Condition(z => z.IsDownload.HasValue))
- .ForMember(x => x.UnlimitedDownloads, opt => opt.Condition(z => z.UnlimitedDownloads.HasValue))
- .ForMember(x => x.MaxNumberOfDownloads, opt => opt.Condition(z => z.MaxNumberOfDownloads.HasValue))
- .ForMember(x => x.DownloadExpirationDays, opt => opt.Condition(z => z.DownloadExpirationDays.HasValue))
- .ForMember(x => x.DownloadActivationTypeId, opt => opt.Condition(z => z.DownloadActivationTypeId.HasValue))
- .ForMember(x => x.HasSampleDownload, opt => opt.Condition(z => z.HasSampleDownload.HasValue))
- .ForMember(x => x.HasUserAgreement, opt => opt.Condition(z => z.HasUserAgreement.HasValue))
- .ForMember(x => x.IsRecurring, opt => opt.Condition(z => z.IsRecurring.HasValue))
- .ForMember(x => x.RecurringCycleLength, opt => opt.Condition(z => z.RecurringCycleLength.HasValue))
- .ForMember(x => x.RecurringCyclePeriodId, opt => opt.Condition(z => z.RecurringCyclePeriodId.HasValue))
- .ForMember(x => x.RecurringTotalCycles, opt => opt.Condition(z => z.RecurringTotalCycles.HasValue))
- .ForMember(x => x.IncBothDate, opt => opt.Condition(z => z.IncBothDate.HasValue))
- .ForMember(x => x.Interval, opt => opt.Condition(z => z.Interval.HasValue))
- .ForMember(x => x.IntervalUnitId, opt => opt.Condition(z => z.IntervalUnitId.HasValue))
- .ForMember(x => x.IsFreeShipping, opt => opt.Condition(z => z.IsFreeShipping.HasValue))
- .ForMember(x => x.ShipSeparately, opt => opt.Condition(z => z.ShipSeparately.HasValue))
- .ForMember(x => x.AdditionalShippingCharge, opt => opt.Condition(z => z.AdditionalShippingCharge.HasValue))
- .ForMember(x => x.IsTaxExempt, opt => opt.Condition(z => z.IsTaxExempt.HasValue))
- .ForMember(x => x.IsTele, opt => opt.Condition(z => z.IsTele.HasValue))
- .ForMember(x => x.ManageInventoryMethodId, opt => opt.Condition(z => z.ManageInventoryMethodId.HasValue))
- .ForMember(x => x.UseMultipleWarehouses, opt => opt.Condition(z => z.UseMultipleWarehouses.HasValue))
- .ForMember(x => x.StockQuantity, opt => opt.Condition(z => z.StockQuantity.HasValue))
- .ForMember(x => x.ReservedQuantity, opt => opt.Condition(z => z.ReservedQuantity.HasValue))
- .ForMember(x => x.StockAvailability, opt => opt.Condition(z => z.StockAvailability.HasValue))
- .ForMember(x => x.DisplayStockQuantity, opt => opt.Condition(z => z.DisplayStockQuantity.HasValue))
- .ForMember(x => x.MinStockQuantity, opt => opt.Condition(z => z.MinStockQuantity.HasValue))
- .ForMember(x => x.LowStock, opt => opt.Condition(z => z.LowStock.HasValue))
- .ForMember(x => x.LowStockActivityId, opt => opt.Condition(z => z.LowStockActivityId.HasValue))
- .ForMember(x => x.NotifyAdminForQuantityBelow, opt => opt.Condition(z => z.NotifyAdminForQuantityBelow.HasValue))
- .ForMember(x => x.BackorderModeId, opt => opt.Condition(z => z.BackorderModeId.HasValue))
- .ForMember(x => x.AllowOutOfStockSubscriptions, opt => opt.Condition(z => z.AllowOutOfStockSubscriptions.HasValue))
- .ForMember(x => x.OrderMinimumQuantity, opt => opt.Condition(z => z.OrderMinimumQuantity.HasValue))
- .ForMember(x => x.OrderMaximumQuantity, opt => opt.Condition(z => z.OrderMaximumQuantity.HasValue))
- .ForMember(x => x.NotReturnable, opt => opt.Condition(z => z.NotReturnable.HasValue))
- .ForMember(x => x.DisableBuyButton, opt => opt.Condition(z => z.DisableBuyButton.HasValue))
- .ForMember(x => x.DisableWishlistButton, opt => opt.Condition(z => z.DisableWishlistButton.HasValue))
- .ForMember(x => x.AvailableForPreOrder, opt => opt.Condition(z => z.AvailableForPreOrder.HasValue))
- .ForMember(x => x.PreOrderDateTimeUtc, opt => opt.Condition(z => z.PreOrderDateTimeUtc.HasValue))
- .ForMember(x => x.CallForPrice, opt => opt.Condition(z => z.CallForPrice.HasValue))
- .ForMember(x => x.Price, opt => opt.Condition(z => z.Price.HasValue))
- .ForMember(x => x.OldPrice, opt => opt.Condition(z => z.OldPrice.HasValue))
- .ForMember(x => x.CatalogPrice, opt => opt.Condition(z => z.CatalogPrice.HasValue))
- .ForMember(x => x.ProductCost, opt => opt.Condition(z => z.ProductCost.HasValue))
- .ForMember(x => x.EnteredPrice, opt => opt.Condition(z => z.EnteredPrice.HasValue))
- .ForMember(x => x.MinEnteredPrice, opt => opt.Condition(z => z.MinEnteredPrice.HasValue))
- .ForMember(x => x.MaxEnteredPrice, opt => opt.Condition(z => z.MaxEnteredPrice.HasValue))
- .ForMember(x => x.BasepriceEnabled, opt => opt.Condition(z => z.BasePriceEnabled.HasValue))
- .ForMember(x => x.BasepriceAmount, opt => opt.Condition(z => z.BasePriceAmount.HasValue))
- .ForMember(x => x.BasepriceBaseAmount, opt => opt.Condition(z => z.BasePriceBaseAmount.HasValue))
- .ForMember(x => x.MarkAsNew, opt => opt.Condition(z => z.MarkAsNew.HasValue))
- .ForMember(x => x.MarkAsNewStartDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewStartDateTimeUtc.HasValue))
- .ForMember(x => x.MarkAsNewEndDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewEndDateTimeUtc.HasValue))
- .ForMember(x => x.Weight, opt => opt.Condition(z => z.Weight.HasValue))
- .ForMember(x => x.Length, opt => opt.Condition(z => z.Length.HasValue))
- .ForMember(x => x.Width, opt => opt.Condition(z => z.Width.HasValue))
- .ForMember(x => x.Height, opt => opt.Condition(z => z.Height.HasValue))
- .ForMember(x => x.AvailableStartDateTimeUtc, opt => opt.Condition(z => z.AvailableStartDateTimeUtc.HasValue))
- .ForMember(x => x.AvailableEndDateTimeUtc, opt => opt.Condition(z => z.AvailableEndDateTimeUtc.HasValue))
- .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
- .ForMember(x => x.DisplayOrderCategory, opt => opt.Condition(z => z.DisplayOrderCategory.HasValue))
- .ForMember(x => x.DisplayOrderBrand, opt => opt.Condition(z => z.DisplayOrderBrand.HasValue))
- .ForMember(x => x.DisplayOrderCollection, opt => opt.Condition(z => z.DisplayOrderCollection.HasValue))
- .ForMember(x => x.Sold, opt => opt.Condition(z => z.Sold.HasValue))
- .ForMember(x => x.Viewed, opt => opt.Condition(z => z.Viewed.HasValue))
- .ForMember(x => x.OnSale, opt => opt.Condition(z => z.OnSale.HasValue))
- .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
- .ForMember(x => x.IsShipEnabled, opt => opt.Condition(z => z.IsShipEnabled.HasValue))
- .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
- .ForMember(x => x.ShortDescription, opt => opt.Condition(z => z.ShortDescription != null))
- .ForMember(x => x.FullDescription, opt => opt.Condition(z => z.FullDescription != null))
- .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
- .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
- .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
- .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
- .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null))
- .ForMember(x => x.BrandId, opt => opt.Condition(z => z.BrandId != null))
- .ForMember(x => x.ProductLayoutId, opt => opt.Condition(z => z.ProductLayoutId != null))
- .ForMember(x => x.AdminComment, opt => opt.Condition(z => z.AdminComment != null))
- .ForMember(x => x.VendorId, opt => opt.Condition(z => z.VendorId != null))
- .ForMember(x => x.Sku, opt => opt.Condition(z => z.Sku != null))
- .ForMember(x => x.Mpn, opt => opt.Condition(z => z.Mpn != null))
- .ForMember(x => x.Gtin, opt => opt.Condition(z => z.Gtin != null))
- .ForMember(x => x.AllowedQuantities, opt => opt.Condition(z => z.AllowedQuantities != null))
- .ForMember(x => x.BasepriceBaseUnitId, opt => opt.Condition(z => z.BasePriceBaseUnitId != null))
- .ForMember(x => x.BasepriceUnitId, opt => opt.Condition(z => z.BasePriceUnitId != null))
- .ForMember(x => x.CourseId, opt => opt.Condition(z => z.CourseId != null))
- .ForMember(x => x.DeliveryDateId, opt => opt.Condition(z => z.DeliveryDateId != null))
- .ForMember(x => x.TaxCategoryId, opt => opt.Condition(z => z.TaxCategoryId != null))
- .ForMember(x => x.WarehouseId, opt => opt.Condition(z => z.WarehouseId != null))
- .ForMember(x => x.UnitId, opt => opt.Condition(z => z.UnitId != null))
- .ForMember(x => x.Flag, opt => opt.Condition(z => z.Flag != null))
- .ForMember(x => x.RequiredProductIds, opt => opt.Condition(z => z.RequiredProductIds != null))
- .ForMember(x => x.ParentGroupedProductId, opt => opt.Condition(z => z.ParentGroupedProductId != null))
- .ForMember(x => x.UserAgreementText, opt => opt.Condition(z => z.UserAgreementText != null));
- }
-
- public int Order => 0;
+ CreateMap<ProductDto, Product>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.ProductTypeId, opt => opt.Condition(z => z.ProductTypeId.HasValue))
+ .ForMember(x => x.VisibleIndividually, opt => opt.Condition(z => z.VisibleIndividually.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.BestSeller, opt => opt.Condition(z => z.BestSeller.HasValue))
+ .ForMember(x => x.AllowCustomerReviews, opt => opt.Condition(z => z.AllowCustomerReviews.HasValue))
+ .ForMember(x => x.ApprovedRatingSum, opt => opt.Condition(z => z.ApprovedRatingSum.HasValue))
+ .ForMember(x => x.NotApprovedRatingSum, opt => opt.Condition(z => z.NotApprovedRatingSum.HasValue))
+ .ForMember(x => x.ApprovedTotalReviews, opt => opt.Condition(z => z.ApprovedTotalReviews.HasValue))
+ .ForMember(x => x.NotApprovedTotalReviews, opt => opt.Condition(z => z.NotApprovedTotalReviews.HasValue))
+ .ForMember(x => x.IsGiftVoucher, opt => opt.Condition(z => z.IsGiftVoucher.HasValue))
+ .ForMember(x => x.GiftVoucherTypeId, opt => opt.Condition(z => z.GiftVoucherTypeId.HasValue))
+ .ForMember(x => x.OverGiftAmount, opt => opt.Condition(z => z.OverGiftAmount.HasValue))
+ .ForMember(x => x.RequireOtherProducts, opt => opt.Condition(z => z.RequireOtherProducts.HasValue))
+ .ForMember(x => x.AutoAddRequiredProducts, opt => opt.Condition(z => z.AutoAddRequiredProducts.HasValue))
+ .ForMember(x => x.IsDownload, opt => opt.Condition(z => z.IsDownload.HasValue))
+ .ForMember(x => x.UnlimitedDownloads, opt => opt.Condition(z => z.UnlimitedDownloads.HasValue))
+ .ForMember(x => x.MaxNumberOfDownloads, opt => opt.Condition(z => z.MaxNumberOfDownloads.HasValue))
+ .ForMember(x => x.DownloadExpirationDays, opt => opt.Condition(z => z.DownloadExpirationDays.HasValue))
+ .ForMember(x => x.DownloadActivationTypeId, opt => opt.Condition(z => z.DownloadActivationTypeId.HasValue))
+ .ForMember(x => x.HasSampleDownload, opt => opt.Condition(z => z.HasSampleDownload.HasValue))
+ .ForMember(x => x.HasUserAgreement, opt => opt.Condition(z => z.HasUserAgreement.HasValue))
+ .ForMember(x => x.IsRecurring, opt => opt.Condition(z => z.IsRecurring.HasValue))
+ .ForMember(x => x.RecurringCycleLength, opt => opt.Condition(z => z.RecurringCycleLength.HasValue))
+ .ForMember(x => x.RecurringCyclePeriodId, opt => opt.Condition(z => z.RecurringCyclePeriodId.HasValue))
+ .ForMember(x => x.RecurringTotalCycles, opt => opt.Condition(z => z.RecurringTotalCycles.HasValue))
+ .ForMember(x => x.IncBothDate, opt => opt.Condition(z => z.IncBothDate.HasValue))
+ .ForMember(x => x.Interval, opt => opt.Condition(z => z.Interval.HasValue))
+ .ForMember(x => x.IntervalUnitId, opt => opt.Condition(z => z.IntervalUnitId.HasValue))
+ .ForMember(x => x.IsFreeShipping, opt => opt.Condition(z => z.IsFreeShipping.HasValue))
+ .ForMember(x => x.ShipSeparately, opt => opt.Condition(z => z.ShipSeparately.HasValue))
+ .ForMember(x => x.AdditionalShippingCharge, opt => opt.Condition(z => z.AdditionalShippingCharge.HasValue))
+ .ForMember(x => x.IsTaxExempt, opt => opt.Condition(z => z.IsTaxExempt.HasValue))
+ .ForMember(x => x.IsTele, opt => opt.Condition(z => z.IsTele.HasValue))
+ .ForMember(x => x.ManageInventoryMethodId, opt => opt.Condition(z => z.ManageInventoryMethodId.HasValue))
+ .ForMember(x => x.UseMultipleWarehouses, opt => opt.Condition(z => z.UseMultipleWarehouses.HasValue))
+ .ForMember(x => x.StockQuantity, opt => opt.Condition(z => z.StockQuantity.HasValue))
+ .ForMember(x => x.ReservedQuantity, opt => opt.Condition(z => z.ReservedQuantity.HasValue))
+ .ForMember(x => x.StockAvailability, opt => opt.Condition(z => z.StockAvailability.HasValue))
+ .ForMember(x => x.DisplayStockQuantity, opt => opt.Condition(z => z.DisplayStockQuantity.HasValue))
+ .ForMember(x => x.MinStockQuantity, opt => opt.Condition(z => z.MinStockQuantity.HasValue))
+ .ForMember(x => x.LowStock, opt => opt.Condition(z => z.LowStock.HasValue))
+ .ForMember(x => x.LowStockActivityId, opt => opt.Condition(z => z.LowStockActivityId.HasValue))
+ .ForMember(x => x.NotifyAdminForQuantityBelow,
+ opt => opt.Condition(z => z.NotifyAdminForQuantityBelow.HasValue))
+ .ForMember(x => x.BackorderModeId, opt => opt.Condition(z => z.BackorderModeId.HasValue))
+ .ForMember(x => x.AllowOutOfStockSubscriptions,
+ opt => opt.Condition(z => z.AllowOutOfStockSubscriptions.HasValue))
+ .ForMember(x => x.OrderMinimumQuantity, opt => opt.Condition(z => z.OrderMinimumQuantity.HasValue))
+ .ForMember(x => x.OrderMaximumQuantity, opt => opt.Condition(z => z.OrderMaximumQuantity.HasValue))
+ .ForMember(x => x.NotReturnable, opt => opt.Condition(z => z.NotReturnable.HasValue))
+ .ForMember(x => x.DisableBuyButton, opt => opt.Condition(z => z.DisableBuyButton.HasValue))
+ .ForMember(x => x.DisableWishlistButton, opt => opt.Condition(z => z.DisableWishlistButton.HasValue))
+ .ForMember(x => x.AvailableForPreOrder, opt => opt.Condition(z => z.AvailableForPreOrder.HasValue))
+ .ForMember(x => x.PreOrderDateTimeUtc, opt => opt.Condition(z => z.PreOrderDateTimeUtc.HasValue))
+ .ForMember(x => x.CallForPrice, opt => opt.Condition(z => z.CallForPrice.HasValue))
+ .ForMember(x => x.Price, opt => opt.Condition(z => z.Price.HasValue))
+ .ForMember(x => x.OldPrice, opt => opt.Condition(z => z.OldPrice.HasValue))
+ .ForMember(x => x.CatalogPrice, opt => opt.Condition(z => z.CatalogPrice.HasValue))
+ .ForMember(x => x.ProductCost, opt => opt.Condition(z => z.ProductCost.HasValue))
+ .ForMember(x => x.EnteredPrice, opt => opt.Condition(z => z.EnteredPrice.HasValue))
+ .ForMember(x => x.MinEnteredPrice, opt => opt.Condition(z => z.MinEnteredPrice.HasValue))
+ .ForMember(x => x.MaxEnteredPrice, opt => opt.Condition(z => z.MaxEnteredPrice.HasValue))
+ .ForMember(x => x.BasepriceEnabled, opt => opt.Condition(z => z.BasePriceEnabled.HasValue))
+ .ForMember(x => x.BasepriceAmount, opt => opt.Condition(z => z.BasePriceAmount.HasValue))
+ .ForMember(x => x.BasepriceBaseAmount, opt => opt.Condition(z => z.BasePriceBaseAmount.HasValue))
+ .ForMember(x => x.MarkAsNew, opt => opt.Condition(z => z.MarkAsNew.HasValue))
+ .ForMember(x => x.MarkAsNewStartDateTimeUtc,
+ opt => opt.Condition(z => z.MarkAsNewStartDateTimeUtc.HasValue))
+ .ForMember(x => x.MarkAsNewEndDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewEndDateTimeUtc.HasValue))
+ .ForMember(x => x.Weight, opt => opt.Condition(z => z.Weight.HasValue))
+ .ForMember(x => x.Length, opt => opt.Condition(z => z.Length.HasValue))
+ .ForMember(x => x.Width, opt => opt.Condition(z => z.Width.HasValue))
+ .ForMember(x => x.Height, opt => opt.Condition(z => z.Height.HasValue))
+ .ForMember(x => x.AvailableStartDateTimeUtc,
+ opt => opt.Condition(z => z.AvailableStartDateTimeUtc.HasValue))
+ .ForMember(x => x.AvailableEndDateTimeUtc, opt => opt.Condition(z => z.AvailableEndDateTimeUtc.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
+ .ForMember(x => x.DisplayOrderCategory, opt => opt.Condition(z => z.DisplayOrderCategory.HasValue))
+ .ForMember(x => x.DisplayOrderBrand, opt => opt.Condition(z => z.DisplayOrderBrand.HasValue))
+ .ForMember(x => x.DisplayOrderCollection, opt => opt.Condition(z => z.DisplayOrderCollection.HasValue))
+ .ForMember(x => x.Sold, opt => opt.Condition(z => z.Sold.HasValue))
+ .ForMember(x => x.Viewed, opt => opt.Condition(z => z.Viewed.HasValue))
+ .ForMember(x => x.OnSale, opt => opt.Condition(z => z.OnSale.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.IsShipEnabled, opt => opt.Condition(z => z.IsShipEnabled.HasValue))
+ .ForMember(x => x.Name, opt => opt.Condition(z => z.Name != null))
+ .ForMember(x => x.ShortDescription, opt => opt.Condition(z => z.ShortDescription != null))
+ .ForMember(x => x.FullDescription, opt => opt.Condition(z => z.FullDescription != null))
+ .ForMember(x => x.ExternalId, opt => opt.Condition(z => z.ExternalId != null))
+ .ForMember(x => x.MetaDescription, opt => opt.Condition(z => z.MetaDescription != null))
+ .ForMember(x => x.MetaKeywords, opt => opt.Condition(z => z.MetaKeywords != null))
+ .ForMember(x => x.MetaTitle, opt => opt.Condition(z => z.MetaTitle != null))
+ .ForMember(x => x.SeName, opt => opt.Condition(z => z.SeName != null))
+ .ForMember(x => x.BrandId, opt => opt.Condition(z => z.BrandId != null))
+ .ForMember(x => x.ProductLayoutId, opt => opt.Condition(z => z.ProductLayoutId != null))
+ .ForMember(x => x.AdminComment, opt => opt.Condition(z => z.AdminComment != null))
+ .ForMember(x => x.VendorId, opt => opt.Condition(z => z.VendorId != null))
+ .ForMember(x => x.Sku, opt => opt.Condition(z => z.Sku != null))
+ .ForMember(x => x.Mpn, opt => opt.Condition(z => z.Mpn != null))
+ .ForMember(x => x.Gtin, opt => opt.Condition(z => z.Gtin != null))
+ .ForMember(x => x.AllowedQuantities, opt => opt.Condition(z => z.AllowedQuantities != null))
+ .ForMember(x => x.BasepriceBaseUnitId, opt => opt.Condition(z => z.BasePriceBaseUnitId != null))
+ .ForMember(x => x.BasepriceUnitId, opt => opt.Condition(z => z.BasePriceUnitId != null))
+ .ForMember(x => x.CourseId, opt => opt.Condition(z => z.CourseId != null))
+ .ForMember(x => x.DeliveryDateId, opt => opt.Condition(z => z.DeliveryDateId != null))
+ .ForMember(x => x.TaxCategoryId, opt => opt.Condition(z => z.TaxCategoryId != null))
+ .ForMember(x => x.WarehouseId, opt => opt.Condition(z => z.WarehouseId != null))
+ .ForMember(x => x.UnitId, opt => opt.Condition(z => z.UnitId != null))
+ .ForMember(x => x.Flag, opt => opt.Condition(z => z.Flag != null))
+ .ForMember(x => x.RequiredProductIds, opt => opt.Condition(z => z.RequiredProductIds != null))
+ .ForMember(x => x.ParentGroupedProductId, opt => opt.Condition(z => z.ParentGroupedProductId != null))
+ .ForMember(x => x.UserAgreementText, opt => opt.Condition(z => z.UserAgreementText != null));
}
-}
+
+ public int Order => 0;
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs
index 9ff245240..d87323f06 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs
@@ -14,262 +14,267 @@ using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.System;
using Grand.Domain.Catalog;
+using Grand.Domain.Common;
using Grand.Domain.Seo;
using Grand.Infrastructure.Mapper;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class ProductImportDataObject : IImportDataObject<ProductDto>
{
- public class ProductImportDataObject : IImportDataObject<ProductDto>
- {
- private readonly IProductService _productService;
- private readonly IPictureService _pictureService;
- private readonly IProductLayoutService _productLayoutService;
- private readonly IDeliveryDateService _deliveryDateService;
- private readonly ITaxCategoryService _taxService;
- private readonly IWarehouseService _warehouseService;
- private readonly IMeasureService _measureService;
- private readonly ICategoryService _categoryService;
- private readonly IProductCategoryService _productCategoryService;
- private readonly IBrandService _brandService;
- private readonly ICollectionService _collectionService;
- private readonly IProductCollectionService _productCollectionService;
- private readonly ISlugService _slugService;
- private readonly ILanguageService _languageService;
+ private readonly IBrandService _brandService;
+ private readonly ICategoryService _categoryService;
+ private readonly ICollectionService _collectionService;
+ private readonly IDeliveryDateService _deliveryDateService;
+ private readonly ILanguageService _languageService;
+ private readonly IMeasureService _measureService;
+ private readonly IPictureService _pictureService;
+ private readonly IProductCategoryService _productCategoryService;
+ private readonly IProductCollectionService _productCollectionService;
+ private readonly IProductLayoutService _productLayoutService;
+ private readonly IProductService _productService;
- private readonly SeoSettings _seoSetting;
+ private readonly SeoSettings _seoSetting;
+ private readonly ISlugService _slugService;
+ private readonly ITaxCategoryService _taxService;
+ private readonly IWarehouseService _warehouseService;
- public ProductImportDataObject(
- IProductService productService,
- IPictureService pictureService,
- IProductLayoutService productLayoutService,
- IDeliveryDateService deliveryDateService,
- ITaxCategoryService taxService,
- IWarehouseService warehouseService,
- IMeasureService measureService,
- ISlugService slugService,
- ILanguageService languageService,
- ICategoryService categoryService,
- IProductCategoryService productCategoryService,
- IBrandService brandService,
- ICollectionService collectionService,
- IProductCollectionService productCollectionService,
- SeoSettings seoSetting)
- {
- _productService = productService;
- _pictureService = pictureService;
- _productLayoutService = productLayoutService;
- _deliveryDateService = deliveryDateService;
- _taxService = taxService;
- _warehouseService = warehouseService;
- _measureService = measureService;
- _slugService = slugService;
- _languageService = languageService;
- _categoryService = categoryService;
- _productCategoryService = productCategoryService;
- _brandService = brandService;
- _collectionService = collectionService;
- _productCollectionService = productCollectionService;
- _seoSetting = seoSetting;
- }
+ public ProductImportDataObject(
+ IProductService productService,
+ IPictureService pictureService,
+ IProductLayoutService productLayoutService,
+ IDeliveryDateService deliveryDateService,
+ ITaxCategoryService taxService,
+ IWarehouseService warehouseService,
+ IMeasureService measureService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ ICategoryService categoryService,
+ IProductCategoryService productCategoryService,
+ IBrandService brandService,
+ ICollectionService collectionService,
+ IProductCollectionService productCollectionService,
+ SeoSettings seoSetting)
+ {
+ _productService = productService;
+ _pictureService = pictureService;
+ _productLayoutService = productLayoutService;
+ _deliveryDateService = deliveryDateService;
+ _taxService = taxService;
+ _warehouseService = warehouseService;
+ _measureService = measureService;
+ _slugService = slugService;
+ _languageService = languageService;
+ _categoryService = categoryService;
+ _productCategoryService = productCategoryService;
+ _brandService = brandService;
+ _collectionService = collectionService;
+ _productCollectionService = productCollectionService;
+ _seoSetting = seoSetting;
+ }
- public async Task Execute(IEnumerable<ProductDto> data)
- {
- foreach (var item in data)
- {
- await Import(item);
- }
- }
+ public async Task Execute(IEnumerable<ProductDto> data)
+ {
+ foreach (var item in data) await Import(item);
+ }
- private async Task Import(ProductDto productDto)
- {
- var product = await _productService.GetProductById(productDto.Id);
- product ??= await _productService.GetProductBySku(productDto.Sku);
+ private async Task Import(ProductDto productDto)
+ {
+ var product = await _productService.GetProductById(productDto.Id);
+ product ??= await _productService.GetProductBySku(productDto.Sku);
- var isNew = product == null;
-
- if (product == null) product = productDto.MapTo<ProductDto, Product>();
- else productDto.MapTo(product);
+ var isNew = product == null;
- if (!ValidProduct(product)) return;
+ if (product == null) product = productDto.MapTo<ProductDto, Product>();
+ else productDto.MapTo(product);
- if (isNew) await _productService.InsertProduct(product);
- else await _productService.UpdateProduct(product);
+ if (!ValidProduct(product)) return;
- await UpdateProductData(productDto, product, isNew);
+ if (isNew) await _productService.InsertProduct(product);
+ else await _productService.UpdateProduct(product);
- }
+ await UpdateProductData(productDto, product, isNew);
+ }
- private async Task UpdateProductData(ProductDto productDto, Product product, bool isNew)
- {
- await UpdateProductDataLayout(product);
- await UpdateProductDataDeliveryDate(product);
- await UpdateProductDataTaxCategory(product);
- await UpdateProductDataWarehouse(product);
- await UpdateProductDataUnit(product);
- await UpdateProductDataBrand(product);
+ private async Task UpdateProductData(ProductDto productDto, Product product, bool isNew)
+ {
+ await UpdateProductDataLayout(product);
+ await UpdateProductDataDeliveryDate(product);
+ await UpdateProductDataTaxCategory(product);
+ await UpdateProductDataWarehouse(product);
+ await UpdateProductDataUnit(product);
+ await UpdateProductDataBrand(product);
- //search engine name
- var sename = product.SeName ?? product.Name;
- sename = await product.ValidateSeName(sename, product.Name, true, _seoSetting, _slugService, _languageService);
- await _slugService.SaveSlug(product, sename, "");
- product.SeName = sename;
- await _productService.UpdateProduct(product);
+ //search engine name
+ var sename = product.SeName ?? product.Name;
+ sename = await product.ValidateSeName(sename, product.Name, true, _seoSetting, _slugService, _languageService);
+ await _slugService.SaveSlug(product, sename, "");
+ product.SeName = sename;
+ await _productService.UpdateProduct(product);
- product.LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity;
+ product.LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity;
- if (!string.IsNullOrEmpty(productDto.CategoryIds)) await PrepareProductCategories(product, productDto.CategoryIds);
+ if (!string.IsNullOrEmpty(productDto.CategoryIds))
+ await PrepareProductCategories(product, productDto.CategoryIds);
- if (!string.IsNullOrEmpty(productDto.CollectionIds)) await PrepareProductCollections(product, productDto.CollectionIds);
+ if (!string.IsNullOrEmpty(productDto.CollectionIds))
+ await PrepareProductCollections(product, productDto.CollectionIds);
- //pictures
- await PrepareProductPictures(productDto, product, isNew);
- }
+ //pictures
+ await PrepareProductPictures(productDto, product, isNew);
+ }
- private async Task UpdateProductDataLayout(Product product)
+ private async Task UpdateProductDataLayout(Product product)
+ {
+ if (string.IsNullOrEmpty(product.ProductLayoutId))
{
- if (string.IsNullOrEmpty(product.ProductLayoutId))
- product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;
- else
- {
- var layout = await _productLayoutService.GetProductLayoutById(product.ProductLayoutId);
- if (layout == null)
- product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;
- }
+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;
}
-
- private async Task UpdateProductDataDeliveryDate(Product product)
+ else
{
- if (string.IsNullOrEmpty(product.DeliveryDateId)) return;
- var deliveryDate = await _deliveryDateService.GetDeliveryDateById(product.DeliveryDateId);
- if (deliveryDate == null)
- product.DeliveryDateId = "";
+ var layout = await _productLayoutService.GetProductLayoutById(product.ProductLayoutId);
+ if (layout == null)
+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault()?.Id;
}
+ }
- private async Task UpdateProductDataTaxCategory(Product product)
- {
- if (string.IsNullOrEmpty(product.TaxCategoryId)) return;
- var taxCategory = await _taxService.GetTaxCategoryById(product.TaxCategoryId);
- if (taxCategory == null)
- product.TaxCategoryId = "";
- }
+ private async Task UpdateProductDataDeliveryDate(Product product)
+ {
+ if (string.IsNullOrEmpty(product.DeliveryDateId)) return;
+ var deliveryDate = await _deliveryDateService.GetDeliveryDateById(product.DeliveryDateId);
+ if (deliveryDate == null)
+ product.DeliveryDateId = "";
+ }
- private async Task UpdateProductDataWarehouse(Product product)
- {
- if (string.IsNullOrEmpty(product.WarehouseId)) return;
- var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);
- if (warehouse == null)
- product.WarehouseId = "";
- }
+ private async Task UpdateProductDataTaxCategory(Product product)
+ {
+ if (string.IsNullOrEmpty(product.TaxCategoryId)) return;
+ var taxCategory = await _taxService.GetTaxCategoryById(product.TaxCategoryId);
+ if (taxCategory == null)
+ product.TaxCategoryId = "";
+ }
+
+ private async Task UpdateProductDataWarehouse(Product product)
+ {
+ if (string.IsNullOrEmpty(product.WarehouseId)) return;
+ var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);
+ if (warehouse == null)
+ product.WarehouseId = "";
+ }
+
+ private async Task UpdateProductDataUnit(Product product)
+ {
+ if (string.IsNullOrEmpty(product.UnitId)) return;
+ var unit = await _measureService.GetMeasureUnitById(product.UnitId);
+ if (unit == null)
+ product.UnitId = "";
+ }
+
+ private async Task UpdateProductDataBrand(Product product)
+ {
+ if (string.IsNullOrEmpty(product.BrandId)) return;
+ var brand = await _brandService.GetBrandById(product.BrandId);
+ if (brand == null)
+ product.BrandId = "";
+ }
- private async Task UpdateProductDataUnit(Product product)
+ private async Task PrepareProductCategories(Product product, string categoryIds)
+ {
+ foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(x => x.Trim()))
{
- if (string.IsNullOrEmpty(product.UnitId)) return;
- var unit = await _measureService.GetMeasureUnitById(product.UnitId);
- if (unit == null)
- product.UnitId = "";
+ if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) != null) continue;
+ //ensure that category exists
+ var category = await _categoryService.GetCategoryById(id);
+ if (category == null) continue;
+ var productCategory = new ProductCategory {
+ CategoryId = category.Id,
+ IsFeaturedProduct = false,
+ DisplayOrder = 1
+ };
+ await _productCategoryService.InsertProductCategory(productCategory, product.Id);
}
+ }
- private async Task UpdateProductDataBrand(Product product)
+ private async Task PrepareProductCollections(Product product, string collectionIds)
+ {
+ foreach (var id in collectionIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(x => x.Trim()))
{
- if (string.IsNullOrEmpty(product.BrandId)) return;
- var brand = await _brandService.GetBrandById(product.BrandId);
- if (brand == null)
- product.BrandId = "";
+ if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) != null) continue;
+ //ensure that collection exists
+ var collection = await _collectionService.GetCollectionById(id);
+ if (collection == null) continue;
+ var productCollection = new ProductCollection {
+ CollectionId = collection.Id,
+ IsFeaturedProduct = false,
+ DisplayOrder = 1
+ };
+ await _productCollectionService.InsertProductCollection(productCollection, product.Id);
}
+ }
+
+ private async Task PrepareProductPictures(ProductDto productDto, Product product, bool isNew)
+ {
+ var picture1 = productDto.Picture1;
+ var picture2 = productDto.Picture2;
+ var picture3 = productDto.Picture3;
- private async Task PrepareProductCategories(Product product, string categoryIds)
+ foreach (var picturePath in new[] { picture1, picture2, picture3 })
{
- foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
+ if (string.IsNullOrEmpty(picturePath))
+ continue;
+ if (!picturePath.ToLower().StartsWith("http".ToLower()))
{
- if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) != null) continue;
- //ensure that category exists
- var category = await _categoryService.GetCategoryById(id);
- if (category == null) continue;
- var productCategory = new ProductCategory {
- CategoryId = category.Id,
- IsFeaturedProduct = false,
+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
+ var pictureAlreadyExists = false;
+ if (!isNew)
+ {
+ //compare with existing product pictures
+ var existingPictures = product.ProductPictures;
+ foreach (var existingPicture in existingPictures)
+ {
+ var pp = await _pictureService.GetPictureById(existingPicture.PictureId);
+ var existingBinary = await _pictureService.LoadPictureBinary(pp);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (!existingBinary.SequenceEqual(validatedPictureBinary) &&
+ !existingBinary.SequenceEqual(newPictureBinary)) continue;
+ //the same picture content
+ pictureAlreadyExists = true;
+ break;
+ }
+ }
+
+ if (pictureAlreadyExists) continue;
+ var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(product.Name), "", "", false,
+ Reference.Product, product.Id);
+ var productPicture = new ProductPicture {
+ PictureId = picture.Id,
DisplayOrder = 1
};
- await _productCategoryService.InsertProductCategory(productCategory, product.Id);
+ await _productService.InsertProductPicture(productPicture, product.Id);
}
- }
-
- private async Task PrepareProductCollections(Product product, string collectionIds)
- {
- foreach (var id in collectionIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
+ else
{
- if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) != null) continue;
- //ensure that collection exists
- var collection = await _collectionService.GetCollectionById(id);
- if (collection == null) continue;
- var productCollection = new ProductCollection {
- CollectionId = collection.Id,
- IsFeaturedProduct = false,
+ var fileBinary = await DownloadUrl.DownloadFile(picturePath);
+ if (fileBinary == null) continue;
+ var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
+ var picture = await _pictureService.InsertPicture(fileBinary, mimeType,
+ _pictureService.GetPictureSeName(product.Name), "", "", false, Reference.Product, product.Id);
+ var productPicture = new ProductPicture {
+ PictureId = picture.Id,
DisplayOrder = 1
};
- await _productCollectionService.InsertProductCollection(productCollection, product.Id);
+ await _productService.InsertProductPicture(productPicture, product.Id);
}
}
+ }
- private async Task PrepareProductPictures(ProductDto productDto, Product product, bool isNew)
- {
- var picture1 = productDto.Picture1;
- var picture2 = productDto.Picture2;
- var picture3 = productDto.Picture3;
-
- foreach (var picturePath in new[] { picture1, picture2, picture3 })
- {
- if (string.IsNullOrEmpty(picturePath))
- continue;
- if (!picturePath.ToLower().StartsWith("http".ToLower()))
- {
- var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = await File.ReadAllBytesAsync(picturePath);
- var pictureAlreadyExists = false;
- if (!isNew)
- {
- //compare with existing product pictures
- var existingPictures = product.ProductPictures;
- foreach (var existingPicture in existingPictures)
- {
- var pp = await _pictureService.GetPictureById(existingPicture.PictureId);
- var existingBinary = await _pictureService.LoadPictureBinary(pp);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (!existingBinary.SequenceEqual(validatedPictureBinary) &&
- !existingBinary.SequenceEqual(newPictureBinary)) continue;
- //the same picture content
- pictureAlreadyExists = true;
- break;
- }
- }
-
- if (pictureAlreadyExists) continue;
- var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false,
- Domain.Common.Reference.Product, product.Id);
- var productPicture = new ProductPicture {
- PictureId = picture.Id,
- DisplayOrder = 1
- };
- await _productService.InsertProductPicture(productPicture, product.Id);
- }
- else
- {
- var fileBinary = await DownloadUrl.DownloadFile(picturePath);
- if (fileBinary == null) continue;
- var mimeType = MimeTypeExtensions.GetMimeTypeFromFilePath(picturePath);
- var picture = await _pictureService.InsertPicture(fileBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false, Domain.Common.Reference.Product, product.Id);
- var productPicture = new ProductPicture {
- PictureId = picture.Id,
- DisplayOrder = 1
- };
- await _productService.InsertProductPicture(productPicture, product.Id);
- }
- }
- }
- private bool ValidProduct(Product product)
- {
- return !string.IsNullOrEmpty(product.Name);
- }
+ private bool ValidProduct(Product product)
+ {
+ return !string.IsNullOrEmpty(product.Name);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs
index cdcff395d..acecffe13 100644
--- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs
@@ -4,152 +4,153 @@ using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Catalog;
-namespace Grand.Business.Catalog.Services.ExportImport
+namespace Grand.Business.Catalog.Services.ExportImport;
+
+public class ProductSchemaProperty : ISchemaProperty<Product>
{
- public class ProductSchemaProperty : ISchemaProperty<Product>
- {
- private readonly IPictureService _pictureService;
+ private readonly IPictureService _pictureService;
- public ProductSchemaProperty(IPictureService pictureService)
- {
- _pictureService = pictureService;
- }
+ public ProductSchemaProperty(IPictureService pictureService)
+ {
+ _pictureService = pictureService;
+ }
- public virtual async Task<PropertyByName<Product>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Product>("Id", p => p.Id),
- new PropertyByName<Product>("ProductTypeId", p => (int)p.ProductTypeId),
- new PropertyByName<Product>("ParentGroupedProductId", p => p.ParentGroupedProductId),
- new PropertyByName<Product>("VisibleIndividually", p => p.VisibleIndividually),
- new PropertyByName<Product>("Name", p => p.Name),
- new PropertyByName<Product>("ShortDescription", p => p.ShortDescription),
- new PropertyByName<Product>("FullDescription", p => p.FullDescription),
- new PropertyByName<Product>("Flag", p => p.Flag),
- new PropertyByName<Product>("BrandId", p => p.BrandId),
- new PropertyByName<Product>("VendorId", p => p.VendorId),
- new PropertyByName<Product>("ProductLayoutId", p => p.ProductLayoutId),
- new PropertyByName<Product>("ShowOnHomePage", p => p.ShowOnHomePage),
- new PropertyByName<Product>("BestSeller", p => p.BestSeller),
- new PropertyByName<Product>("MetaKeywords", p => p.MetaKeywords),
- new PropertyByName<Product>("MetaDescription", p => p.MetaDescription),
- new PropertyByName<Product>("MetaTitle", p => p.MetaTitle),
- new PropertyByName<Product>("SeName", p => p.GetSeName("")),
- new PropertyByName<Product>("AllowCustomerReviews", p => p.AllowCustomerReviews),
- new PropertyByName<Product>("Published", p => p.Published),
- new PropertyByName<Product>("SKU", p => p.Sku),
- new PropertyByName<Product>("Mpn", p => p.Mpn),
- new PropertyByName<Product>("Gtin", p => p.Gtin),
- new PropertyByName<Product>("IsGiftVoucher", p => p.IsGiftVoucher),
- new PropertyByName<Product>("GiftVoucherTypeId", p => (int)p.GiftVoucherTypeId),
- new PropertyByName<Product>("OverriddenGiftVoucherAmount", p => p.OverGiftAmount),
- new PropertyByName<Product>("RequireOtherProducts", p => p.RequireOtherProducts),
- new PropertyByName<Product>("RequiredProductIds", p => p.RequiredProductIds),
- new PropertyByName<Product>("AutomaticallyAddRequiredProducts", p => p.AutoAddRequiredProducts),
- new PropertyByName<Product>("IsDownload", p => p.IsDownload),
- new PropertyByName<Product>("DownloadId", p => p.DownloadId),
- new PropertyByName<Product>("UnlimitedDownloads", p => p.UnlimitedDownloads),
- new PropertyByName<Product>("MaxNumberOfDownloads", p => p.MaxNumberOfDownloads),
- new PropertyByName<Product>("DownloadActivationTypeId", p => (int)p.DownloadActivationTypeId),
- new PropertyByName<Product>("HasSampleDownload", p => p.HasSampleDownload),
- new PropertyByName<Product>("SampleDownloadId", p => p.SampleDownloadId),
- new PropertyByName<Product>("HasUserAgreement", p => p.HasUserAgreement),
- new PropertyByName<Product>("UserAgreementText", p => p.UserAgreementText),
- new PropertyByName<Product>("IsRecurring", p => p.IsRecurring),
- new PropertyByName<Product>("RecurringCycleLength", p => p.RecurringCycleLength),
- new PropertyByName<Product>("RecurringCyclePeriodId", p => (int)p.RecurringCyclePeriodId),
- new PropertyByName<Product>("RecurringTotalCycles", p => p.RecurringTotalCycles),
- new PropertyByName<Product>("Interval", p => p.Interval),
- new PropertyByName<Product>("IntervalUnitId", p => (int)p.IntervalUnitId),
- new PropertyByName<Product>("IsShipEnabled", p => p.IsShipEnabled),
- new PropertyByName<Product>("IsFreeShipping", p => p.IsFreeShipping),
- new PropertyByName<Product>("ShipSeparately", p => p.ShipSeparately),
- new PropertyByName<Product>("AdditionalShippingCharge", p => p.AdditionalShippingCharge),
- new PropertyByName<Product>("DeliveryDateId", p => p.DeliveryDateId),
- new PropertyByName<Product>("IsTaxExempt", p => p.IsTaxExempt),
- new PropertyByName<Product>("TaxCategoryId", p => p.TaxCategoryId),
- new PropertyByName<Product>("IsTele", p => p.IsTele),
- new PropertyByName<Product>("ManageInventoryMethodId", p => (int)p.ManageInventoryMethodId),
- new PropertyByName<Product>("UseMultipleWarehouses", p => p.UseMultipleWarehouses),
- new PropertyByName<Product>("WarehouseId", p => p.WarehouseId),
- new PropertyByName<Product>("StockQuantity", p => p.StockQuantity),
- new PropertyByName<Product>("ReservedQuantity", p => p.ReservedQuantity),
- new PropertyByName<Product>("DisplayStockAvailability", p => p.StockAvailability),
- new PropertyByName<Product>("DisplayStockQuantity", p => p.DisplayStockQuantity),
- new PropertyByName<Product>("MinStockQuantity", p => p.MinStockQuantity),
- new PropertyByName<Product>("LowStockActivityId", p => (int)p.LowStockActivityId),
- new PropertyByName<Product>("NotifyAdminForQuantityBelow", p => p.NotifyAdminForQuantityBelow),
- new PropertyByName<Product>("BackorderModeId", p => (int)p.BackorderModeId),
- new PropertyByName<Product>("AllowOutOfStockSubscriptions", p => p.AllowOutOfStockSubscriptions),
- new PropertyByName<Product>("OrderMinimumQuantity", p => p.OrderMinimumQuantity),
- new PropertyByName<Product>("OrderMaximumQuantity", p => p.OrderMaximumQuantity),
- new PropertyByName<Product>("AllowedQuantities", p => p.AllowedQuantities),
- new PropertyByName<Product>("DisableBuyButton", p => p.DisableBuyButton),
- new PropertyByName<Product>("DisableWishlistButton", p => p.DisableWishlistButton),
- new PropertyByName<Product>("AvailableForPreOrder", p => p.AvailableForPreOrder),
- new PropertyByName<Product>("PreOrderDateTimeUtc", p => p.PreOrderDateTimeUtc),
- new PropertyByName<Product>("CallForPrice", p => p.CallForPrice),
- new PropertyByName<Product>("Price", p => p.Price),
- new PropertyByName<Product>("OldPrice", p => p.OldPrice),
- new PropertyByName<Product>("CatalogPrice", p => p.CatalogPrice),
- new PropertyByName<Product>("ProductCost", p => p.ProductCost),
- new PropertyByName<Product>("EnteredPrice", p => p.EnteredPrice),
- new PropertyByName<Product>("MinEnteredPrice", p => p.MinEnteredPrice),
- new PropertyByName<Product>("MaxEnteredPrice", p => p.MaxEnteredPrice),
- new PropertyByName<Product>("BasepriceEnabled", p => p.BasepriceEnabled),
- new PropertyByName<Product>("BasepriceAmount", p => p.BasepriceAmount),
- new PropertyByName<Product>("BasepriceUnitId", p => p.BasepriceUnitId),
- new PropertyByName<Product>("BasepriceBaseAmount", p => p.BasepriceBaseAmount),
- new PropertyByName<Product>("BasepriceBaseUnitId", p => p.BasepriceBaseUnitId),
- new PropertyByName<Product>("MarkAsNew", p => p.MarkAsNew),
- new PropertyByName<Product>("MarkAsNewStartDateTimeUtc", p => p.MarkAsNewStartDateTimeUtc),
- new PropertyByName<Product>("MarkAsNewEndDateTimeUtc", p => p.MarkAsNewEndDateTimeUtc),
- new PropertyByName<Product>("UnitId", p => p.UnitId),
- new PropertyByName<Product>("Weight", p => p.Weight),
- new PropertyByName<Product>("Length", p => p.Length),
- new PropertyByName<Product>("Width", p => p.Width),
- new PropertyByName<Product>("Height", p => p.Height),
- new PropertyByName<Product>("DisplayOrder", p => p.DisplayOrder),
- new PropertyByName<Product>("DisplayOrderCategory", p => p.DisplayOrderCategory),
- new PropertyByName<Product>("DisplayOrderBrand", p => p.DisplayOrderBrand),
- new PropertyByName<Product>("DisplayOrderCollection", p => p.DisplayOrderCollection),
- new PropertyByName<Product>("OnSale", p => p.OnSale),
- new PropertyByName<Product>("CategoryIds", p => string.Join(";", p.ProductCategories.Select(n => n.CategoryId).ToArray())),
- new PropertyByName<Product>("CollectionIds", p=> string.Join(";", p.ProductCollections.Select(n => n.CollectionId).ToArray())),
- new PropertyByName<Product>("Picture1", p => GetPictures(p).Result[0]),
- new PropertyByName<Product>("Picture2", p => GetPictures(p).Result[1]),
- new PropertyByName<Product>("Picture3", p => GetPictures(p).Result[2])
- };
- return await Task.FromResult(properties);
- }
+ public virtual async Task<PropertyByName<Product>[]> GetProperties()
+ {
+ var properties = new[] {
+ new PropertyByName<Product>("Id", p => p.Id),
+ new PropertyByName<Product>("ProductTypeId", p => (int)p.ProductTypeId),
+ new PropertyByName<Product>("ParentGroupedProductId", p => p.ParentGroupedProductId),
+ new PropertyByName<Product>("VisibleIndividually", p => p.VisibleIndividually),
+ new PropertyByName<Product>("Name", p => p.Name),
+ new PropertyByName<Product>("ShortDescription", p => p.ShortDescription),
+ new PropertyByName<Product>("FullDescription", p => p.FullDescription),
+ new PropertyByName<Product>("Flag", p => p.Flag),
+ new PropertyByName<Product>("BrandId", p => p.BrandId),
+ new PropertyByName<Product>("VendorId", p => p.VendorId),
+ new PropertyByName<Product>("ProductLayoutId", p => p.ProductLayoutId),
+ new PropertyByName<Product>("ShowOnHomePage", p => p.ShowOnHomePage),
+ new PropertyByName<Product>("BestSeller", p => p.BestSeller),
+ new PropertyByName<Product>("MetaKeywords", p => p.MetaKeywords),
+ new PropertyByName<Product>("MetaDescription", p => p.MetaDescription),
+ new PropertyByName<Product>("MetaTitle", p => p.MetaTitle),
+ new PropertyByName<Product>("SeName", p => p.GetSeName("")),
+ new PropertyByName<Product>("AllowCustomerReviews", p => p.AllowCustomerReviews),
+ new PropertyByName<Product>("Published", p => p.Published),
+ new PropertyByName<Product>("SKU", p => p.Sku),
+ new PropertyByName<Product>("Mpn", p => p.Mpn),
+ new PropertyByName<Product>("Gtin", p => p.Gtin),
+ new PropertyByName<Product>("IsGiftVoucher", p => p.IsGiftVoucher),
+ new PropertyByName<Product>("GiftVoucherTypeId", p => (int)p.GiftVoucherTypeId),
+ new PropertyByName<Product>("OverriddenGiftVoucherAmount", p => p.OverGiftAmount),
+ new PropertyByName<Product>("RequireOtherProducts", p => p.RequireOtherProducts),
+ new PropertyByName<Product>("RequiredProductIds", p => p.RequiredProductIds),
+ new PropertyByName<Product>("AutomaticallyAddRequiredProducts", p => p.AutoAddRequiredProducts),
+ new PropertyByName<Product>("IsDownload", p => p.IsDownload),
+ new PropertyByName<Product>("DownloadId", p => p.DownloadId),
+ new PropertyByName<Product>("UnlimitedDownloads", p => p.UnlimitedDownloads),
+ new PropertyByName<Product>("MaxNumberOfDownloads", p => p.MaxNumberOfDownloads),
+ new PropertyByName<Product>("DownloadActivationTypeId", p => (int)p.DownloadActivationTypeId),
+ new PropertyByName<Product>("HasSampleDownload", p => p.HasSampleDownload),
+ new PropertyByName<Product>("SampleDownloadId", p => p.SampleDownloadId),
+ new PropertyByName<Product>("HasUserAgreement", p => p.HasUserAgreement),
+ new PropertyByName<Product>("UserAgreementText", p => p.UserAgreementText),
+ new PropertyByName<Product>("IsRecurring", p => p.IsRecurring),
+ new PropertyByName<Product>("RecurringCycleLength", p => p.RecurringCycleLength),
+ new PropertyByName<Product>("RecurringCyclePeriodId", p => (int)p.RecurringCyclePeriodId),
+ new PropertyByName<Product>("RecurringTotalCycles", p => p.RecurringTotalCycles),
+ new PropertyByName<Product>("Interval", p => p.Interval),
+ new PropertyByName<Product>("IntervalUnitId", p => (int)p.IntervalUnitId),
+ new PropertyByName<Product>("IsShipEnabled", p => p.IsShipEnabled),
+ new PropertyByName<Product>("IsFreeShipping", p => p.IsFreeShipping),
+ new PropertyByName<Product>("ShipSeparately", p => p.ShipSeparately),
+ new PropertyByName<Product>("AdditionalShippingCharge", p => p.AdditionalShippingCharge),
+ new PropertyByName<Product>("DeliveryDateId", p => p.DeliveryDateId),
+ new PropertyByName<Product>("IsTaxExempt", p => p.IsTaxExempt),
+ new PropertyByName<Product>("TaxCategoryId", p => p.TaxCategoryId),
+ new PropertyByName<Product>("IsTele", p => p.IsTele),
+ new PropertyByName<Product>("ManageInventoryMethodId", p => (int)p.ManageInventoryMethodId),
+ new PropertyByName<Product>("UseMultipleWarehouses", p => p.UseMultipleWarehouses),
+ new PropertyByName<Product>("WarehouseId", p => p.WarehouseId),
+ new PropertyByName<Product>("StockQuantity", p => p.StockQuantity),
+ new PropertyByName<Product>("ReservedQuantity", p => p.ReservedQuantity),
+ new PropertyByName<Product>("DisplayStockAvailability", p => p.StockAvailability),
+ new PropertyByName<Product>("DisplayStockQuantity", p => p.DisplayStockQuantity),
+ new PropertyByName<Product>("MinStockQuantity", p => p.MinStockQuantity),
+ new PropertyByName<Product>("LowStockActivityId", p => (int)p.LowStockActivityId),
+ new PropertyByName<Product>("NotifyAdminForQuantityBelow", p => p.NotifyAdminForQuantityBelow),
+ new PropertyByName<Product>("BackorderModeId", p => (int)p.BackorderModeId),
+ new PropertyByName<Product>("AllowOutOfStockSubscriptions", p => p.AllowOutOfStockSubscriptions),
+ new PropertyByName<Product>("OrderMinimumQuantity", p => p.OrderMinimumQuantity),
+ new PropertyByName<Product>("OrderMaximumQuantity", p => p.OrderMaximumQuantity),
+ new PropertyByName<Product>("AllowedQuantities", p => p.AllowedQuantities),
+ new PropertyByName<Product>("DisableBuyButton", p => p.DisableBuyButton),
+ new PropertyByName<Product>("DisableWishlistButton", p => p.DisableWishlistButton),
+ new PropertyByName<Product>("AvailableForPreOrder", p => p.AvailableForPreOrder),
+ new PropertyByName<Product>("PreOrderDateTimeUtc", p => p.PreOrderDateTimeUtc),
+ new PropertyByName<Product>("CallForPrice", p => p.CallForPrice),
+ new PropertyByName<Product>("Price", p => p.Price),
+ new PropertyByName<Product>("OldPrice", p => p.OldPrice),
+ new PropertyByName<Product>("CatalogPrice", p => p.CatalogPrice),
+ new PropertyByName<Product>("ProductCost", p => p.ProductCost),
+ new PropertyByName<Product>("EnteredPrice", p => p.EnteredPrice),
+ new PropertyByName<Product>("MinEnteredPrice", p => p.MinEnteredPrice),
+ new PropertyByName<Product>("MaxEnteredPrice", p => p.MaxEnteredPrice),
+ new PropertyByName<Product>("BasepriceEnabled", p => p.BasepriceEnabled),
+ new PropertyByName<Product>("BasepriceAmount", p => p.BasepriceAmount),
+ new PropertyByName<Product>("BasepriceUnitId", p => p.BasepriceUnitId),
+ new PropertyByName<Product>("BasepriceBaseAmount", p => p.BasepriceBaseAmount),
+ new PropertyByName<Product>("BasepriceBaseUnitId", p => p.BasepriceBaseUnitId),
+ new PropertyByName<Product>("MarkAsNew", p => p.MarkAsNew),
+ new PropertyByName<Product>("MarkAsNewStartDateTimeUtc", p => p.MarkAsNewStartDateTimeUtc),
+ new PropertyByName<Product>("MarkAsNewEndDateTimeUtc", p => p.MarkAsNewEndDateTimeUtc),
+ new PropertyByName<Product>("UnitId", p => p.UnitId),
+ new PropertyByName<Product>("Weight", p => p.Weight),
+ new PropertyByName<Product>("Length", p => p.Length),
+ new PropertyByName<Product>("Width", p => p.Width),
+ new PropertyByName<Product>("Height", p => p.Height),
+ new PropertyByName<Product>("DisplayOrder", p => p.DisplayOrder),
+ new PropertyByName<Product>("DisplayOrderCategory", p => p.DisplayOrderCategory),
+ new PropertyByName<Product>("DisplayOrderBrand", p => p.DisplayOrderBrand),
+ new PropertyByName<Product>("DisplayOrderCollection", p => p.DisplayOrderCollection),
+ new PropertyByName<Product>("OnSale", p => p.OnSale),
+ new PropertyByName<Product>("CategoryIds",
+ p => string.Join(";", p.ProductCategories.Select(n => n.CategoryId).ToArray())),
+ new PropertyByName<Product>("CollectionIds",
+ p => string.Join(";", p.ProductCollections.Select(n => n.CollectionId).ToArray())),
+ new PropertyByName<Product>("Picture1", p => GetPictures(p).Result[0]),
+ new PropertyByName<Product>("Picture2", p => GetPictures(p).Result[1]),
+ new PropertyByName<Product>("Picture3", p => GetPictures(p).Result[2])
+ };
+ return await Task.FromResult(properties);
+ }
- private async Task<string[]> GetPictures(Product product)
+ private async Task<string[]> GetPictures(Product product)
+ {
+ string picture1 = null;
+ string picture2 = null;
+ string picture3 = null;
+ var i = 0;
+ foreach (var picture in product.ProductPictures.Take(3))
{
- string picture1 = null;
- string picture2 = null;
- string picture3 = null;
- var i = 0;
- foreach (var picture in product.ProductPictures.Take(3))
+ var pic = await _pictureService.GetPictureById(picture.PictureId);
+ var pictureLocalPath = await _pictureService.GetThumbPhysicalPath(pic);
+ switch (i)
{
- var pic = await _pictureService.GetPictureById(picture.PictureId);
- var pictureLocalPath = await _pictureService.GetThumbPhysicalPath(pic);
- switch (i)
- {
- case 0:
- picture1 = pictureLocalPath;
- break;
- case 1:
- picture2 = pictureLocalPath;
- break;
- case 2:
- picture3 = pictureLocalPath;
- break;
- }
- i++;
+ case 0:
+ picture1 = pictureLocalPath;
+ break;
+ case 1:
+ picture2 = pictureLocalPath;
+ break;
+ case 2:
+ picture3 = pictureLocalPath;
+ break;
}
- return [picture1, picture2, picture3];
+ i++;
}
+
+ return [picture1, picture2, picture3];
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
index d9c6ce428..e30b74250 100644
--- a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
@@ -3,101 +3,100 @@ using Grand.Domain.Directory;
using Grand.Infrastructure;
using System.Globalization;
-namespace Grand.Business.Catalog.Services.Prices
+namespace Grand.Business.Catalog.Services.Prices;
+
+/// <summary>
+/// Price formatter
+/// </summary>
+public class PriceFormatter : IPriceFormatter
{
- /// <summary>
- /// Price formatter
- /// </summary>
- public class PriceFormatter : IPriceFormatter
- {
- #region Fields
+ #region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContext _workContext;
- #endregion
+ #endregion
- #region Constructors
+ #region Constructors
- public PriceFormatter(IWorkContext workContext)
- {
- _workContext = workContext;
- }
+ public PriceFormatter(IWorkContext workContext)
+ {
+ _workContext = workContext;
+ }
- #endregion
+ #endregion
- #region Utilities
+ #region Utilities
- /// <summary>
- /// Gets currency string
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="targetCurrency">Target currency</param>
- /// <returns>Currency string without exchange rate</returns>
- protected virtual string GetCurrencyString(double amount, Currency targetCurrency)
- {
- if (targetCurrency == null)
- return amount.ToString("C");
+ /// <summary>
+ /// Gets currency string
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="targetCurrency">Target currency</param>
+ /// <returns>Currency string without exchange rate</returns>
+ protected virtual string GetCurrencyString(double amount, Currency targetCurrency)
+ {
+ if (targetCurrency == null)
+ return amount.ToString("C");
- string result;
- if (!string.IsNullOrEmpty(targetCurrency.CustomFormatting))
+ string result;
+ if (!string.IsNullOrEmpty(targetCurrency.CustomFormatting))
+ {
+ var cultureInfo = !string.IsNullOrEmpty(targetCurrency.DisplayLocale)
+ ? new CultureInfo(targetCurrency.DisplayLocale)
+ : null;
+ result = amount.ToString(targetCurrency.CustomFormatting, cultureInfo);
+ }
+ else
+ {
+ if (!string.IsNullOrEmpty(targetCurrency.DisplayLocale))
{
- var cultureInfo = !string.IsNullOrEmpty(targetCurrency.DisplayLocale)
- ? new CultureInfo(targetCurrency.DisplayLocale)
- : null;
- result = amount.ToString(targetCurrency.CustomFormatting, cultureInfo);
+ result = amount.ToString("C", new CultureInfo(targetCurrency.DisplayLocale));
}
else
{
- if (!string.IsNullOrEmpty(targetCurrency.DisplayLocale))
- {
- result = amount.ToString("C", new CultureInfo(targetCurrency.DisplayLocale));
- }
- else
- {
- result = $"{amount:N} ({targetCurrency.CurrencyCode})";
- return result;
- }
+ result = $"{amount:N} ({targetCurrency.CurrencyCode})";
+ return result;
}
-
- return result;
}
- #endregion
+ return result;
+ }
- #region Methods
+ #endregion
- /// <summary>
- /// Formats the price
- /// </summary>
- /// <param name="price">Price</param>
- /// <returns>Price</returns>
- public virtual string FormatPrice(double price)
- {
- return FormatPrice(price, _workContext.WorkingCurrency);
- }
+ #region Methods
- /// <summary>
- /// Formats the price
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="targetCurrency">Target currency</param>
- /// <returns>Price</returns>
- public string FormatPrice(double price, Currency targetCurrency)
- {
- var currencyString = GetCurrencyString(price, targetCurrency);
- return currencyString;
- }
-
- /// <summary>
- /// Formats a tax rate
- /// </summary>
- /// <param name="taxRate">Tax rate</param>
- /// <returns>Formatted tax rate</returns>
- public virtual string FormatTaxRate(double taxRate)
- {
- return taxRate.ToString("G29");
- }
+ /// <summary>
+ /// Formats the price
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <returns>Price</returns>
+ public virtual string FormatPrice(double price)
+ {
+ return FormatPrice(price, _workContext.WorkingCurrency);
+ }
- #endregion
+ /// <summary>
+ /// Formats the price
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="targetCurrency">Target currency</param>
+ /// <returns>Price</returns>
+ public string FormatPrice(double price, Currency targetCurrency)
+ {
+ var currencyString = GetCurrencyString(price, targetCurrency);
+ return currencyString;
}
+
+ /// <summary>
+ /// Formats a tax rate
+ /// </summary>
+ /// <param name="taxRate">Tax rate</param>
+ /// <returns>Formatted tax rate</returns>
+ public virtual string FormatTaxRate(double taxRate)
+ {
+ return taxRate.ToString("G29");
+ }
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
index 7d3358c11..b592bf9ad 100644
--- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
@@ -1,378 +1,398 @@
using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Catalog.Categories;
-using Grand.Business.Core.Interfaces.Catalog.Discounts;
using Grand.Business.Core.Interfaces.Catalog.Collections;
+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.Common.Directory;
using Grand.Business.Core.Queries.Catalog;
using Grand.Business.Core.Utilities.Catalog;
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Infrastructure;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Domain.Orders;
-using MediatR;
-using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Domain.Stores;
+using Grand.Infrastructure;
+using MediatR;
using System.Globalization;
-namespace Grand.Business.Catalog.Services.Prices
+namespace Grand.Business.Catalog.Services.Prices;
+
+/// <summary>
+/// Pricing service
+/// </summary>
+public class PricingService : IPricingService
{
+ #region Ctor
+
+ public PricingService(IWorkContext workContext,
+ IDiscountService discountService,
+ ICategoryService categoryService,
+ IBrandService brandService,
+ ICollectionService collectionService,
+ IProductService productService,
+ IMediator mediator,
+ ICurrencyService currencyService,
+ IDiscountValidationService discountValidationService,
+ ShoppingCartSettings shoppingCartSettings,
+ CatalogSettings catalogSettings)
+ {
+ _workContext = workContext;
+ _discountService = discountService;
+ _categoryService = categoryService;
+ _brandService = brandService;
+ _collectionService = collectionService;
+ _productService = productService;
+ _mediator = mediator;
+ _mediator = mediator;
+ _currencyService = currencyService;
+ _shoppingCartSettings = shoppingCartSettings;
+ _catalogSettings = catalogSettings;
+ _discountValidationService = discountValidationService;
+ }
+
+ #endregion
+
+ #region Nested classes
+
+ protected class ProductPrice
+ {
+ public double Price { get; set; }
+ public double AppliedDiscountAmount { get; set; }
+ public IList<ApplyDiscount> AppliedDiscounts { get; set; } = new List<ApplyDiscount>();
+ public TierPrice PreferredTierPrice { get; set; }
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IWorkContext _workContext;
+ private readonly IDiscountService _discountService;
+ private readonly ICategoryService _categoryService;
+ private readonly IBrandService _brandService;
+ private readonly ICollectionService _collectionService;
+ private readonly IProductService _productService;
+ private readonly IMediator _mediator;
+ private readonly ICurrencyService _currencyService;
+ private readonly IDiscountValidationService _discountValidationService;
+ private readonly ShoppingCartSettings _shoppingCartSettings;
+ private readonly CatalogSettings _catalogSettings;
+
+ #endregion
+
+ #region Utilities
+
/// <summary>
- /// Pricing service
+ /// Gets allowed discounts
/// </summary>
- public class PricingService : IPricingService
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns>Discounts</returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToProduct(Product product,
+ Customer customer, Store store, Currency currency)
{
- #region Fields
-
- private readonly IWorkContext _workContext;
- private readonly IDiscountService _discountService;
- private readonly ICategoryService _categoryService;
- private readonly IBrandService _brandService;
- private readonly ICollectionService _collectionService;
- private readonly IProductService _productService;
- private readonly IMediator _mediator;
- private readonly ICurrencyService _currencyService;
- private readonly IDiscountValidationService _discountValidationService;
- private readonly ShoppingCartSettings _shoppingCartSettings;
- private readonly CatalogSettings _catalogSettings;
-
- #endregion
-
- #region Ctor
-
- public PricingService(IWorkContext workContext,
- IDiscountService discountService,
- ICategoryService categoryService,
- IBrandService brandService,
- ICollectionService collectionService,
- IProductService productService,
- IMediator mediator,
- ICurrencyService currencyService,
- IDiscountValidationService discountValidationService,
- ShoppingCartSettings shoppingCartSettings,
- CatalogSettings catalogSettings)
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
+ return allowedDiscounts;
+
+ if (!product.AppliedDiscounts.Any()) return allowedDiscounts;
+ foreach (var appliedDiscount in product.AppliedDiscounts)
{
- _workContext = workContext;
- _discountService = discountService;
- _categoryService = categoryService;
- _brandService = brandService;
- _collectionService = collectionService;
- _productService = productService;
- _mediator = mediator;
- _mediator = mediator;
- _currencyService = currencyService;
- _shoppingCartSettings = shoppingCartSettings;
- _catalogSettings = catalogSettings;
- _discountValidationService = discountValidationService;
+ var discount = await _discountService.GetDiscountById(appliedDiscount);
+ if (discount == null) continue;
+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ if (validDiscount.IsValid &&
+ discount.DiscountTypeId == DiscountType.AssignedToSkus)
+ allowedDiscounts.Add(new ApplyDiscount {
+ CouponCode = validDiscount.CouponCode,
+ DiscountId = discount.Id,
+ IsCumulative = discount.IsCumulative
+ });
}
- #endregion
+ return allowedDiscounts;
+ }
- #region Nested classes
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToAllProduct(Product product,
+ Customer customer, Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
+ return allowedDiscounts;
- protected class ProductPrice
+ var discounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, store.Id,
+ currency.CurrencyCode);
+ foreach (var discount in discounts)
{
- public double Price { get; set; }
- public double AppliedDiscountAmount { get; set; }
- public IList<ApplyDiscount> AppliedDiscounts { get; set; } = new List<ApplyDiscount>();
- public TierPrice PreferredTierPrice { get; set; }
-
+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ if (validDiscount.IsValid)
+ allowedDiscounts.Add(new ApplyDiscount {
+ CouponCode = validDiscount.CouponCode,
+ DiscountId = discount.Id,
+ IsCumulative = discount.IsCumulative
+ });
}
- #endregion
-
- #region Utilities
-
- /// <summary>
- /// Gets allowed discounts
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns>Discounts</returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToProduct(Product product, Customer customer, Store store, Currency currency)
- {
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
- if (!product.AppliedDiscounts.Any()) return allowedDiscounts;
- foreach (var appliedDiscount in product.AppliedDiscounts)
+ return allowedDiscounts;
+ }
+
+
+ /// <summary>
+ /// Gets allowed discounts applied to categories
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns>Discounts</returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCategories(Product product,
+ Customer customer, Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
+ return allowedDiscounts;
+
+ foreach (var productCategory in product.ProductCategories)
+ {
+ var category = await _categoryService.GetCategoryById(productCategory.CategoryId);
+ if (category == null || !category.AppliedDiscounts.Any()) continue;
+ foreach (var appliedDiscount in category.AppliedDiscounts)
{
var discount = await _discountService.GetDiscountById(appliedDiscount);
if (discount == null) continue;
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
- if (validDiscount.IsValid &&
- discount.DiscountTypeId == DiscountType.AssignedToSkus)
+ var validDiscount =
+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)
allowedDiscounts.Add(new ApplyDiscount {
CouponCode = validDiscount.CouponCode,
DiscountId = discount.Id,
IsCumulative = discount.IsCumulative
});
}
- return allowedDiscounts;
}
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToAllProduct(Product product, Customer customer, Store store, Currency currency)
- {
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
+ return allowedDiscounts;
+ }
- var discounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, storeId: store.Id, currencyCode: currency.CurrencyCode);
- foreach (var discount in discounts)
- {
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
- if (validDiscount.IsValid)
- allowedDiscounts.Add(new ApplyDiscount {
- CouponCode = validDiscount.CouponCode,
- DiscountId = discount.Id,
- IsCumulative = discount.IsCumulative
- });
- }
+ /// <summary>
+ /// Get allowed discount applied to brands
+ /// </summary>
+ /// <param name="product"></param>
+ /// <param name="customer"></param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns></returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToBrands(Product product,
+ Customer customer, Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
- }
-
- /// <summary>
- /// Gets allowed discounts applied to categories
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns>Discounts</returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCategories(Product product, Customer customer, Store store, Currency currency)
+ if (string.IsNullOrEmpty(product.BrandId)) return allowedDiscounts;
+ var brand = await _brandService.GetBrandById(product.BrandId);
+ if (brand == null) return allowedDiscounts;
+ if (!brand.AppliedDiscounts.Any()) return allowedDiscounts;
+ foreach (var appliedDiscount in brand.AppliedDiscounts)
{
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
+ var discount = await _discountService.GetDiscountById(appliedDiscount);
+ if (discount == null) continue;
+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ if (validDiscount.IsValid &&
+ discount.DiscountTypeId == DiscountType.AssignedToBrands)
+ allowedDiscounts.Add(new ApplyDiscount {
+ CouponCode = validDiscount.CouponCode,
+ DiscountId = discount.Id,
+ IsCumulative = discount.IsCumulative
+ });
+ }
- foreach (var productCategory in product.ProductCategories)
- {
- var category = await _categoryService.GetCategoryById(productCategory.CategoryId);
- if (category == null || !category.AppliedDiscounts.Any()) continue;
- foreach (var appliedDiscount in category.AppliedDiscounts)
- {
- var discount = await _discountService.GetDiscountById(appliedDiscount);
- if (discount == null) continue;
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
- if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)
- allowedDiscounts.Add(new ApplyDiscount {
- CouponCode = validDiscount.CouponCode,
- DiscountId = discount.Id,
- IsCumulative = discount.IsCumulative
- });
- }
- }
+ return allowedDiscounts;
+ }
+
+ /// <summary>
+ /// Gets allowed discounts applied to collections
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns>Discounts</returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCollections(Product product,
+ Customer customer, Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
- }
- /// <summary>
- /// Get allowed discount applied to brands
- /// </summary>
- /// <param name="product"></param>
- /// <param name="customer"></param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns></returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToBrands(Product product, Customer customer, Store store, Currency currency)
+ foreach (var productCollection in product.ProductCollections)
{
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
-
- if (string.IsNullOrEmpty(product.BrandId)) return allowedDiscounts;
- var brand = await _brandService.GetBrandById(product.BrandId);
- if (brand == null) return allowedDiscounts;
- if (!brand.AppliedDiscounts.Any()) return allowedDiscounts;
- foreach (var appliedDiscount in brand.AppliedDiscounts)
+ var collection = await _collectionService.GetCollectionById(productCollection.CollectionId);
+ if (collection == null || !collection.AppliedDiscounts.Any()) continue;
+ foreach (var appliedDiscount in collection.AppliedDiscounts)
{
var discount = await _discountService.GetDiscountById(appliedDiscount);
if (discount == null) continue;
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ var validDiscount =
+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
if (validDiscount.IsValid &&
- discount.DiscountTypeId == DiscountType.AssignedToBrands)
+ discount.DiscountTypeId == DiscountType.AssignedToCollections)
allowedDiscounts.Add(new ApplyDiscount {
CouponCode = validDiscount.CouponCode,
DiscountId = discount.Id,
IsCumulative = discount.IsCumulative
});
}
- return allowedDiscounts;
}
- /// <summary>
- /// Gets allowed discounts applied to collections
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns>Discounts</returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCollections(Product product, Customer customer, Store store, Currency currency)
- {
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
+ return allowedDiscounts;
+ }
- foreach (var productCollection in product.ProductCollections)
- {
- var collection = await _collectionService.GetCollectionById(productCollection.CollectionId);
- if (collection == null || !collection.AppliedDiscounts.Any()) continue;
- foreach (var appliedDiscount in collection.AppliedDiscounts)
- {
- var discount = await _discountService.GetDiscountById(appliedDiscount);
- if (discount == null) continue;
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
- if (validDiscount.IsValid &&
- discount.DiscountTypeId == DiscountType.AssignedToCollections)
- allowedDiscounts.Add(new ApplyDiscount {
- CouponCode = validDiscount.CouponCode,
- DiscountId = discount.Id,
- IsCumulative = discount.IsCumulative
- });
- }
- }
+ /// <summary>
+ /// Get allowed discounts applied to vendors
+ /// </summary>
+ /// <param name="product"></param>
+ /// <param name="customer"></param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns></returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToVendors(Product product,
+ Customer customer, Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
- }
- /// <summary>
- /// Get allowed discounts applied to vendors
- /// </summary>
- /// <param name="product"></param>
- /// <param name="customer"></param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns></returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToVendors(Product product, Customer customer, Store store, Currency currency)
+ if (string.IsNullOrEmpty(product.VendorId)) return allowedDiscounts;
+
+ var vendor = await _mediator.Send(new GetVendorByIdQuery { Id = product.VendorId });
+ if (vendor == null) return allowedDiscounts;
+ if (!vendor.AppliedDiscounts.Any()) return allowedDiscounts;
+ foreach (var appliedDiscount in vendor.AppliedDiscounts)
{
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
-
- if (string.IsNullOrEmpty(product.VendorId)) return allowedDiscounts;
-
- var vendor = await _mediator.Send(new GetVendorByIdQuery { Id = product.VendorId });
- if (vendor == null) return allowedDiscounts;
- if (!vendor.AppliedDiscounts.Any()) return allowedDiscounts;
- foreach (var appliedDiscount in vendor.AppliedDiscounts)
- {
- var discount = await _discountService.GetDiscountById(appliedDiscount);
- if (discount == null) continue;
- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
- if (validDiscount.IsValid &&
- discount.DiscountTypeId == DiscountType.AssignedToVendors)
- allowedDiscounts.Add(new ApplyDiscount {
- CouponCode = validDiscount.CouponCode,
- DiscountId = discount.Id,
- IsCumulative = discount.IsCumulative
- });
- }
- return allowedDiscounts;
+ var discount = await _discountService.GetDiscountById(appliedDiscount);
+ if (discount == null) continue;
+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);
+ if (validDiscount.IsValid &&
+ discount.DiscountTypeId == DiscountType.AssignedToVendors)
+ allowedDiscounts.Add(new ApplyDiscount {
+ CouponCode = validDiscount.CouponCode,
+ DiscountId = discount.Id,
+ IsCumulative = discount.IsCumulative
+ });
}
- /// <summary>
- /// Gets allowed discounts
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <returns>Discounts</returns>
- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscounts(Product product, Customer customer, Store store, Currency currency)
- {
- var allowedDiscounts = new List<ApplyDiscount>();
- if (_catalogSettings.IgnoreDiscounts)
- return allowedDiscounts;
-
- //discounts applied to products
- foreach (var discount in await GetAllowedDiscountsAppliedToProduct(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
-
- //discounts applied to all products
- foreach (var discount in await GetAllowedDiscountsAppliedToAllProduct(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
-
- //discounts applied to categories
- foreach (var discount in await GetAllowedDiscountsAppliedToCategories(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
-
- //discounts applied to brands
- foreach (var discount in await GetAllowedDiscountsAppliedToBrands(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
-
- //discounts applied to collections
- foreach (var discount in await GetAllowedDiscountsAppliedToCollections(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
-
- //discounts applied to vendors
- foreach (var discount in await GetAllowedDiscountsAppliedToVendors(product, customer, store, currency))
- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
- allowedDiscounts.Add(discount);
+ return allowedDiscounts;
+ }
+ /// <summary>
+ /// Gets allowed discounts
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <returns>Discounts</returns>
+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscounts(Product product, Customer customer,
+ Store store, Currency currency)
+ {
+ var allowedDiscounts = new List<ApplyDiscount>();
+ if (_catalogSettings.IgnoreDiscounts)
return allowedDiscounts;
- }
- /// <summary>
- /// Gets discount amount
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">The customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <param name="productPriceWithoutDiscount">Already calculated product price without discount</param>
- /// <returns>Discount amount</returns>
- protected virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetDiscountAmount(Product product,
- Customer customer, Store store, Currency currency, double productPriceWithoutDiscount)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //discounts applied to products
+ foreach (var discount in await GetAllowedDiscountsAppliedToProduct(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ //discounts applied to all products
+ foreach (var discount in await GetAllowedDiscountsAppliedToAllProduct(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ //discounts applied to categories
+ foreach (var discount in await GetAllowedDiscountsAppliedToCategories(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ //discounts applied to brands
+ foreach (var discount in await GetAllowedDiscountsAppliedToBrands(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ //discounts applied to collections
+ foreach (var discount in await GetAllowedDiscountsAppliedToCollections(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ //discounts applied to vendors
+ foreach (var discount in await GetAllowedDiscountsAppliedToVendors(product, customer, store, currency))
+ if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))
+ allowedDiscounts.Add(discount);
+
+ return allowedDiscounts;
+ }
- //we don't apply discounts to products with price entered by a customer
- if (product.EnteredPrice)
- return (0, null);
+ /// <summary>
+ /// Gets discount amount
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">The customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <param name="productPriceWithoutDiscount">Already calculated product price without discount</param>
+ /// <returns>Discount amount</returns>
+ protected virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetDiscountAmount(
+ Product product,
+ Customer customer, Store store, Currency currency, double productPriceWithoutDiscount)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- //discounts are disabled
- if (_catalogSettings.IgnoreDiscounts)
- return (0, null);
+ //we don't apply discounts to products with price entered by a customer
+ if (product.EnteredPrice)
+ return (0, null);
- var allowedDiscounts = await GetAllowedDiscounts(product, customer, store, currency);
+ //discounts are disabled
+ if (_catalogSettings.IgnoreDiscounts)
+ return (0, null);
- //no discounts
- if (!allowedDiscounts.Any())
- return (0, null);
+ var allowedDiscounts = await GetAllowedDiscounts(product, customer, store, currency);
- var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency, product, productPriceWithoutDiscount);
-
- return (preferredDiscount.discountAmount, preferredDiscount.appliedDiscount);
- }
+ //no discounts
+ if (!allowedDiscounts.Any())
+ return (0, null);
+ var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency,
+ product, productPriceWithoutDiscount);
- #endregion
+ return (preferredDiscount.discountAmount, preferredDiscount.appliedDiscount);
+ }
+
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets the final price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">The customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">The currency</param>
- /// <param name="additionalCharge">Additional charge</param>
- /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
- /// <param name="quantity">Shopping cart item quantity</param>
- /// <returns>Final price</returns>
- public virtual async Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(
+ /// <summary>
+ /// Gets the final price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">The customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">The currency</param>
+ /// <param name="additionalCharge">Additional charge</param>
+ /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
+ /// <param name="quantity">Shopping cart item quantity</param>
+ /// <returns>Final price</returns>
+ public virtual async
+ Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice
+ preferredTierPrice)>
+ GetFinalPrice(
Product product,
Customer customer,
Store store,
@@ -380,24 +400,28 @@ namespace Grand.Business.Catalog.Services.Prices
double additionalCharge = 0,
bool includeDiscounts = true,
int quantity = 1)
- {
- return await GetFinalPrice(product, customer, store, currency, additionalCharge, includeDiscounts, quantity, null, null);
- }
+ {
+ return await GetFinalPrice(product, customer, store, currency, additionalCharge, includeDiscounts, quantity,
+ null, null);
+ }
- /// <summary>
- /// Gets the final price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">The customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">Currency</param>
- /// <param name="additionalCharge">Additional charge</param>
- /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
- /// <param name="quantity">Shopping cart item quantity</param>
- /// <param name="rentalStartDate">Rental period start date (for rental products)</param>
- /// <param name="rentalEndDate">Rental period end date (for rental products)</param>
- /// <returns>Final price</returns>
- public virtual async Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(
+ /// <summary>
+ /// Gets the final price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">The customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">Currency</param>
+ /// <param name="additionalCharge">Additional charge</param>
+ /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
+ /// <param name="quantity">Shopping cart item quantity</param>
+ /// <param name="rentalStartDate">Rental period start date (for rental products)</param>
+ /// <param name="rentalEndDate">Rental period end date (for rental products)</param>
+ /// <returns>Final price</returns>
+ public virtual async
+ Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice
+ preferredTierPrice)>
+ GetFinalPrice(
Product product,
Customer customer,
Store store,
@@ -407,126 +431,133 @@ namespace Grand.Business.Catalog.Services.Prices
int quantity,
DateTime? rentalStartDate,
DateTime? rentalEndDate)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+
+ double discountAmount = 0;
+ var appliedDiscounts = new List<ApplyDiscount>();
+
+ async Task<ProductPrice> PrepareModel()
{
- ArgumentNullException.ThrowIfNull(product);
+ var result = new ProductPrice();
- double discountAmount = 0;
- var appliedDiscounts = new List<ApplyDiscount>();
+ //initial price
+ var price =
+ product.ProductPrices.FirstOrDefault(x => x.CurrencyCode == currency.CurrencyCode)?.Price ??
+ await _currencyService.ConvertFromPrimaryStoreCurrency(product.Price, currency);
- async Task<ProductPrice> PrepareModel()
+ //tier prices
+ var tierPrice = product.GetPreferredTierPrice(customer, store.Id, currency.CurrencyCode, quantity);
+ if (tierPrice != null)
{
- var result = new ProductPrice();
+ price = tierPrice.Price;
+ result.PreferredTierPrice = tierPrice;
+ }
- //initial price
- var price =
- product.ProductPrices.FirstOrDefault(x => x.CurrencyCode == currency.CurrencyCode)?.Price ??
- await _currencyService.ConvertFromPrimaryStoreCurrency(product.Price, currency);
+ //customer product price
+ if (_catalogSettings.CustomerProductPrice)
+ {
+ var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery
+ { CustomerId = customer.Id, ProductId = product.Id });
+ if (customerPrice.HasValue && customerPrice.Value <
+ await _currencyService.ConvertToPrimaryStoreCurrency(price, currency))
+ price = await _currencyService.ConvertFromPrimaryStoreCurrency(customerPrice.Value, currency);
+ }
- //tier prices
- var tierPrice = product.GetPreferredTierPrice(customer, store.Id, currency.CurrencyCode, quantity);
- if (tierPrice != null)
- {
- price = tierPrice.Price;
- result.PreferredTierPrice = tierPrice;
- }
+ //additional charge
+ price += additionalCharge;
- //customer product price
- if (_catalogSettings.CustomerProductPrice)
+ //reservations
+ if (product.ProductTypeId == ProductType.Reservation)
+ if (rentalStartDate.HasValue && rentalEndDate.HasValue)
{
- var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery { CustomerId = customer.Id, ProductId = product.Id });
- if (customerPrice.HasValue && customerPrice.Value < await _currencyService.ConvertToPrimaryStoreCurrency(price, currency))
- price = await _currencyService.ConvertFromPrimaryStoreCurrency(customerPrice.Value, currency);
+ _ = product.IncBothDate
+ ? double.TryParse(
+ ((rentalEndDate - rentalStartDate).Value.TotalDays + 1).ToString(CultureInfo
+ .InvariantCulture), out var d)
+ : double.TryParse(
+ (rentalEndDate - rentalStartDate).Value.TotalDays.ToString(CultureInfo.InvariantCulture),
+ out d);
+ price *= d;
}
- //additional charge
- price += additionalCharge;
-
- //reservations
- if (product.ProductTypeId == ProductType.Reservation)
- if (rentalStartDate.HasValue && rentalEndDate.HasValue)
- {
- _ = product.IncBothDate ? double.TryParse(((rentalEndDate - rentalStartDate).Value.TotalDays + 1).ToString(CultureInfo.InvariantCulture), out var d) :
- double.TryParse((rentalEndDate - rentalStartDate).Value.TotalDays.ToString(CultureInfo.InvariantCulture), out d);
- price *= d;
- }
+ if (includeDiscounts)
+ {
+ //discount
+ var (tmpDiscountAmount, tmpAppliedDiscounts) =
+ await GetDiscountAmount(product, customer, store, currency, price);
+ price -= tmpDiscountAmount;
- if (includeDiscounts)
+ if (tmpAppliedDiscounts != null)
{
- //discount
- var (tmpDiscountAmount, tmpAppliedDiscounts) = await GetDiscountAmount(product, customer, store, currency, price);
- price -= tmpDiscountAmount;
-
- if (tmpAppliedDiscounts != null)
- {
- result.AppliedDiscounts = tmpAppliedDiscounts.ToList();
- result.AppliedDiscountAmount = tmpDiscountAmount;
- }
+ result.AppliedDiscounts = tmpAppliedDiscounts.ToList();
+ result.AppliedDiscountAmount = tmpDiscountAmount;
}
+ }
- if (price < 0)
- price = 0;
+ if (price < 0)
+ price = 0;
- //rounding
- result.Price = _shoppingCartSettings.RoundPrices ? RoundingHelper.RoundPrice(price, currency) : price;
+ //rounding
+ result.Price = _shoppingCartSettings.RoundPrices ? RoundingHelper.RoundPrice(price, currency) : price;
- return result;
- }
+ return result;
+ }
- var modelprice = await PrepareModel();
-
- if (!includeDiscounts)
- return (modelprice.Price, discountAmount, appliedDiscounts, modelprice.PreferredTierPrice);
- appliedDiscounts = modelprice.AppliedDiscounts.ToList();
- if (appliedDiscounts.Any())
- {
- discountAmount = modelprice.AppliedDiscountAmount;
- }
+ var modelprice = await PrepareModel();
+ if (!includeDiscounts)
return (modelprice.Price, discountAmount, appliedDiscounts, modelprice.PreferredTierPrice);
- }
+ appliedDiscounts = modelprice.AppliedDiscounts.ToList();
+ if (appliedDiscounts.Any()) discountAmount = modelprice.AppliedDiscountAmount;
+ return (modelprice.Price, discountAmount, appliedDiscounts, modelprice.PreferredTierPrice);
+ }
- /// <summary>
- /// Gets the shopping cart unit price
- /// </summary>
- /// <param name="shoppingCartItem">The shopping cart item</param>
- /// <param name="product">Product</param>
- /// <param name="includeDiscounts">Include discounts or not for price</param>
- /// <returns>Shopping cart unit price (one item)</returns>
- public virtual async Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetUnitPrice(ShoppingCartItem shoppingCartItem,
+
+ /// <summary>
+ /// Gets the shopping cart unit price
+ /// </summary>
+ /// <param name="shoppingCartItem">The shopping cart item</param>
+ /// <param name="product">Product</param>
+ /// <param name="includeDiscounts">Include discounts or not for price</param>
+ /// <returns>Shopping cart unit price (one item)</returns>
+ public virtual async Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)>
+ GetUnitPrice(ShoppingCartItem shoppingCartItem,
Product product, bool includeDiscounts = true)
- {
- ArgumentNullException.ThrowIfNull(shoppingCartItem);
-
- return await GetUnitPrice(product,
- _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency,
- shoppingCartItem.ShoppingCartTypeId,
- shoppingCartItem.Quantity,
- shoppingCartItem.Attributes,
- shoppingCartItem.EnteredPrice,
- shoppingCartItem.RentalStartDateUtc,
- shoppingCartItem.RentalEndDateUtc,
- includeDiscounts);
- }
+ {
+ ArgumentNullException.ThrowIfNull(shoppingCartItem);
+
+ return await GetUnitPrice(product,
+ _workContext.CurrentCustomer,
+ _workContext.CurrentStore,
+ _workContext.WorkingCurrency,
+ shoppingCartItem.ShoppingCartTypeId,
+ shoppingCartItem.Quantity,
+ shoppingCartItem.Attributes,
+ shoppingCartItem.EnteredPrice,
+ shoppingCartItem.RentalStartDateUtc,
+ shoppingCartItem.RentalEndDateUtc,
+ includeDiscounts);
+ }
- /// <summary>
- /// Gets the shopping cart unit price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <param name="store">Store</param>
- /// <param name="currency">The currency</param>
- /// <param name="shoppingCartType">Shopping cart type</param>
- /// <param name="quantity">Quantity</param>
- /// <param name="attributes">Product attributes</param>
- /// <param name="customerEnteredPrice">Customer entered price</param>
- /// <param name="rentalStartDate">Rental start date</param>
- /// <param name="rentalEndDate">Rental end date</param>
- /// <param name="includeDiscounts">Include discounts or not for price</param>
- /// <returns>Shopping cart unit price</returns>
- public virtual async Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetUnitPrice(
+ /// <summary>
+ /// Gets the shopping cart unit price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="store">Store</param>
+ /// <param name="currency">The currency</param>
+ /// <param name="shoppingCartType">Shopping cart type</param>
+ /// <param name="quantity">Quantity</param>
+ /// <param name="attributes">Product attributes</param>
+ /// <param name="customerEnteredPrice">Customer entered price</param>
+ /// <param name="rentalStartDate">Rental start date</param>
+ /// <param name="rentalEndDate">Rental end date</param>
+ /// <param name="includeDiscounts">Include discounts or not for price</param>
+ /// <returns>Shopping cart unit price</returns>
+ public virtual async Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)>
+ GetUnitPrice(
Product product,
Customer customer,
Store store,
@@ -538,235 +569,228 @@ namespace Grand.Business.Catalog.Services.Prices
DateTime? rentalStartDate,
DateTime? rentalEndDate,
bool includeDiscounts)
- {
- ArgumentNullException.ThrowIfNull(product);
- ArgumentNullException.ThrowIfNull(customer);
+ {
+ ArgumentNullException.ThrowIfNull(product);
+ ArgumentNullException.ThrowIfNull(customer);
- double discountAmount = 0;
- var appliedDiscounts = new List<ApplyDiscount>();
+ double discountAmount = 0;
+ var appliedDiscounts = new List<ApplyDiscount>();
- double? finalPrice = null;
+ double? finalPrice = null;
- if (customerEnteredPrice.HasValue)
- finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(customerEnteredPrice.Value, currency);
+ if (customerEnteredPrice.HasValue)
+ finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(customerEnteredPrice.Value, currency);
- if (!finalPrice.HasValue)
+ if (!finalPrice.HasValue)
+ {
+ var combination = product.FindProductAttributeCombination(attributes);
+ if (combination != null)
{
- var combination = product.FindProductAttributeCombination(attributes);
- if (combination != null)
+ if (combination.OverriddenPrice.HasValue)
+ finalPrice =
+ await _currencyService.ConvertFromPrimaryStoreCurrency(combination.OverriddenPrice.Value,
+ currency);
+ if (combination.TierPrices.Any())
{
- if (combination.OverriddenPrice.HasValue)
- finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(combination.OverriddenPrice.Value, currency);
- if (combination.TierPrices.Any())
- {
- var storeId = store.Id;
- var actualTierPrices = combination.TierPrices.Where(x => string.IsNullOrEmpty(x.StoreId) || x.StoreId == storeId)
- .Where(x => string.IsNullOrEmpty(x.CustomerGroupId) ||
- customer.Groups.Contains(x.CustomerGroupId)).ToList();
- var tierPrice = actualTierPrices.LastOrDefault(price => quantity >= price.Quantity);
- if (tierPrice != null)
- finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(tierPrice.Price, currency);
- }
+ var storeId = store.Id;
+ var actualTierPrices = combination.TierPrices
+ .Where(x => string.IsNullOrEmpty(x.StoreId) || x.StoreId == storeId)
+ .Where(x => string.IsNullOrEmpty(x.CustomerGroupId) ||
+ customer.Groups.Contains(x.CustomerGroupId)).ToList();
+ var tierPrice = actualTierPrices.LastOrDefault(price => quantity >= price.Quantity);
+ if (tierPrice != null)
+ finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(tierPrice.Price, currency);
}
}
- if (!finalPrice.HasValue)
+ }
+
+ if (!finalPrice.HasValue)
+ {
+ //summarize price of all attributes
+ double attributesTotalPrice = 0;
+ if (attributes != null && attributes.Any())
{
- //summarize price of all attributes
- double attributesTotalPrice = 0;
- if (attributes != null && attributes.Any())
- {
- var attributeValues = product.ParseProductAttributeValues(attributes);
- if (attributeValues != null)
- {
- foreach (var attributeValue in attributeValues)
- {
- attributesTotalPrice += await GetProductAttributeValuePriceAdjustment(attributeValue);
- }
- }
- if (product.ProductTypeId == ProductType.BundledProduct)
+ var attributeValues = product.ParseProductAttributeValues(attributes);
+ if (attributeValues != null)
+ foreach (var attributeValue in attributeValues)
+ attributesTotalPrice += await GetProductAttributeValuePriceAdjustment(attributeValue);
+ if (product.ProductTypeId == ProductType.BundledProduct)
+ foreach (var item in product.BundleProducts)
{
- foreach (var item in product.BundleProducts)
- {
- var p1 = await _productService.GetProductById(item.ProductId);
- var bundledProductsAttributeValues = p1?.ParseProductAttributeValues(attributes);
- if (bundledProductsAttributeValues == null) continue;
- foreach (var attributeValue in bundledProductsAttributeValues)
- {
- attributesTotalPrice += item.Quantity * await GetProductAttributeValuePriceAdjustment(attributeValue);
- }
- }
+ var p1 = await _productService.GetProductById(item.ProductId);
+ var bundledProductsAttributeValues = p1?.ParseProductAttributeValues(attributes);
+ if (bundledProductsAttributeValues == null) continue;
+ foreach (var attributeValue in bundledProductsAttributeValues)
+ attributesTotalPrice += item.Quantity *
+ await GetProductAttributeValuePriceAdjustment(attributeValue);
}
- }
- if (!product.EnteredPrice)
- {
- var qty = 0;
- if (_shoppingCartSettings.GroupTierPrices)
- {
- qty = customer.ShoppingCartItems
- .Where(x => x.ProductId == product.Id)
- .Where(x => x.ShoppingCartTypeId == shoppingCartType)
- .Sum(x => x.Quantity);
- }
- if (qty == 0)
- qty = quantity;
-
- var getfinalPrice = await GetFinalPrice(product,
- customer,
- store,
- currency,
- attributesTotalPrice,
- includeDiscounts,
- qty,
- rentalStartDate,
- rentalEndDate);
-
- finalPrice = getfinalPrice.finalPrice;
- discountAmount = getfinalPrice.discountAmount;
- appliedDiscounts = getfinalPrice.appliedDiscounts;
- }
}
- finalPrice ??= 0;
-
- //rounding
- if (_shoppingCartSettings.RoundPrices)
+ if (!product.EnteredPrice)
{
- finalPrice = RoundingHelper.RoundPrice(finalPrice.Value, currency);
+ var qty = 0;
+ if (_shoppingCartSettings.GroupTierPrices)
+ qty = customer.ShoppingCartItems
+ .Where(x => x.ProductId == product.Id)
+ .Where(x => x.ShoppingCartTypeId == shoppingCartType)
+ .Sum(x => x.Quantity);
+ if (qty == 0)
+ qty = quantity;
+
+ var getfinalPrice = await GetFinalPrice(product,
+ customer,
+ store,
+ currency,
+ attributesTotalPrice,
+ includeDiscounts,
+ qty,
+ rentalStartDate,
+ rentalEndDate);
+
+ finalPrice = getfinalPrice.finalPrice;
+ discountAmount = getfinalPrice.discountAmount;
+ appliedDiscounts = getfinalPrice.appliedDiscounts;
}
- return (finalPrice.Value, discountAmount, appliedDiscounts);
}
- /// <summary>
- /// Gets the shopping cart item sub total
- /// </summary>
- /// <param name="shoppingCartItem">The shopping cart item</param>
- /// <param name="product">Product</param>
- /// <param name="includeDiscounts">Include discounts or not for price</param>
- /// <returns>Shopping cart item sub total</returns>
- public virtual async Task<(double subTotal, double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetSubTotal(ShoppingCartItem shoppingCartItem, Product product,
- bool includeDiscounts = true)
- {
- ArgumentNullException.ThrowIfNull(shoppingCartItem);
+ finalPrice ??= 0;
- double subTotal;
- //unit price
- var getUnitPrice = await GetUnitPrice(shoppingCartItem, product, includeDiscounts);
- var unitPrice = getUnitPrice.unitprice;
- var discountAmount = getUnitPrice.discountAmount;
- List<ApplyDiscount> appliedDiscounts = getUnitPrice.appliedDiscounts;
+ //rounding
+ if (_shoppingCartSettings.RoundPrices) finalPrice = RoundingHelper.RoundPrice(finalPrice.Value, currency);
+ return (finalPrice.Value, discountAmount, appliedDiscounts);
+ }
- //discount
- if (appliedDiscounts.Any())
- {
- Discount oneAndOnlyDiscount = null;
- if (appliedDiscounts.Count == 1)
- oneAndOnlyDiscount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault()?.DiscountId);
+ /// <summary>
+ /// Gets the shopping cart item sub total
+ /// </summary>
+ /// <param name="shoppingCartItem">The shopping cart item</param>
+ /// <param name="product">Product</param>
+ /// <param name="includeDiscounts">Include discounts or not for price</param>
+ /// <returns>Shopping cart item sub total</returns>
+ public virtual async Task<(double subTotal, double discountAmount, List<ApplyDiscount> appliedDiscounts)>
+ GetSubTotal(ShoppingCartItem shoppingCartItem, Product product,
+ bool includeDiscounts = true)
+ {
+ ArgumentNullException.ThrowIfNull(shoppingCartItem);
- if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: not null } &&
- shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value)
- {
- //we cannot apply discount for all shopping cart items
- var discountedQuantity = oneAndOnlyDiscount.MaximumDiscountedQuantity.Value;
- var discountedSubTotal = unitPrice * discountedQuantity;
- discountAmount *= discountedQuantity;
+ double subTotal;
+ //unit price
+ var getUnitPrice = await GetUnitPrice(shoppingCartItem, product, includeDiscounts);
+ var unitPrice = getUnitPrice.unitprice;
+ var discountAmount = getUnitPrice.discountAmount;
+ var appliedDiscounts = getUnitPrice.appliedDiscounts;
+
+ //discount
+ if (appliedDiscounts.Any())
+ {
+ Discount oneAndOnlyDiscount = null;
+ if (appliedDiscounts.Count == 1)
+ oneAndOnlyDiscount =
+ await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault()?.DiscountId);
- var notDiscountedQuantity = shoppingCartItem.Quantity - discountedQuantity;
- var notDiscountedUnitPrice = await GetUnitPrice(shoppingCartItem, product, false);
- var notDiscountedSubTotal = notDiscountedUnitPrice.unitprice * notDiscountedQuantity;
+ if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: not null } &&
+ shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value)
+ {
+ //we cannot apply discount for all shopping cart items
+ var discountedQuantity = oneAndOnlyDiscount.MaximumDiscountedQuantity.Value;
+ var discountedSubTotal = unitPrice * discountedQuantity;
+ discountAmount *= discountedQuantity;
- subTotal = discountedSubTotal + notDiscountedSubTotal;
- }
- else
- {
- //discount is applied to all items (quantity)
- discountAmount *= shoppingCartItem.Quantity;
+ var notDiscountedQuantity = shoppingCartItem.Quantity - discountedQuantity;
+ var notDiscountedUnitPrice = await GetUnitPrice(shoppingCartItem, product, false);
+ var notDiscountedSubTotal = notDiscountedUnitPrice.unitprice * notDiscountedQuantity;
- subTotal = unitPrice * shoppingCartItem.Quantity;
- }
+ subTotal = discountedSubTotal + notDiscountedSubTotal;
}
else
{
+ //discount is applied to all items (quantity)
+ discountAmount *= shoppingCartItem.Quantity;
+
subTotal = unitPrice * shoppingCartItem.Quantity;
}
- return (subTotal, discountAmount, appliedDiscounts);
+ }
+ else
+ {
+ subTotal = unitPrice * shoppingCartItem.Quantity;
}
+ return (subTotal, discountAmount, appliedDiscounts);
+ }
- /// <summary>
- /// Gets the product cost (one item)
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="attributes">Shopping cart item attributes</param>
- /// <returns>Product cost (one item)</returns>
- public virtual async Task<double> GetProductCost(Product product, IList<CustomAttribute> attributes)
- {
- ArgumentNullException.ThrowIfNull(product);
+ /// <summary>
+ /// Gets the product cost (one item)
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="attributes">Shopping cart item attributes</param>
+ /// <returns>Product cost (one item)</returns>
+ public virtual async Task<double> GetProductCost(Product product, IList<CustomAttribute> attributes)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- var cost = product.ProductCost;
- var attributeValues = product.ParseProductAttributeValues(attributes);
- foreach (var attributeValue in attributeValues)
+ var cost = product.ProductCost;
+ var attributeValues = product.ParseProductAttributeValues(attributes);
+ foreach (var attributeValue in attributeValues)
+ switch (attributeValue.AttributeValueTypeId)
{
- switch (attributeValue.AttributeValueTypeId)
+ case AttributeValueType.Simple:
{
- case AttributeValueType.Simple:
- {
- //simple attribute
- cost += attributeValue.Cost;
- }
- break;
- case AttributeValueType.AssociatedToProduct:
- {
- //bundled product
- var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);
- if (associatedProduct != null)
- cost += associatedProduct.ProductCost * attributeValue.Quantity;
- }
- break;
+ //simple attribute
+ cost += attributeValue.Cost;
}
- }
-
- return cost;
- }
- /// <summary>
- /// Get a price adjustment of a product attribute value
- /// </summary>
- /// <param name="value">Product attribute value</param>
- /// <returns>Price adjustment</returns>
- public virtual async Task<double> GetProductAttributeValuePriceAdjustment(ProductAttributeValue value)
- {
- ArgumentNullException.ThrowIfNull(value);
-
- double adjustment = 0;
- switch (value.AttributeValueTypeId)
- {
- case AttributeValueType.Simple:
- {
- //simple attribute
- adjustment = value.PriceAdjustment;
- if (adjustment > 0)
- adjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(adjustment, _workContext.WorkingCurrency);
- }
break;
case AttributeValueType.AssociatedToProduct:
- {
- //bundled product
- var associatedProduct = await _productService.GetProductById(value.AssociatedProductId);
- if (associatedProduct != null)
- {
- adjustment = (await GetFinalPrice(associatedProduct,
- _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency,
- additionalCharge: value.PriceAdjustment, includeDiscounts: true)).finalPrice * value.Quantity;
- }
- }
+ {
+ //bundled product
+ var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);
+ if (associatedProduct != null)
+ cost += associatedProduct.ProductCost * attributeValue.Quantity;
+ }
break;
}
- return adjustment;
+ return cost;
+ }
+
+ /// <summary>
+ /// Get a price adjustment of a product attribute value
+ /// </summary>
+ /// <param name="value">Product attribute value</param>
+ /// <returns>Price adjustment</returns>
+ public virtual async Task<double> GetProductAttributeValuePriceAdjustment(ProductAttributeValue value)
+ {
+ ArgumentNullException.ThrowIfNull(value);
+
+ double adjustment = 0;
+ switch (value.AttributeValueTypeId)
+ {
+ case AttributeValueType.Simple:
+ {
+ //simple attribute
+ adjustment = value.PriceAdjustment;
+ if (adjustment > 0)
+ adjustment =
+ await _currencyService.ConvertFromPrimaryStoreCurrency(adjustment,
+ _workContext.WorkingCurrency);
+ }
+ break;
+ case AttributeValueType.AssociatedToProduct:
+ {
+ //bundled product
+ var associatedProduct = await _productService.GetProductById(value.AssociatedProductId);
+ if (associatedProduct != null)
+ adjustment = (await GetFinalPrice(associatedProduct,
+ _workContext.CurrentCustomer,
+ _workContext.CurrentStore,
+ _workContext.WorkingCurrency,
+ value.PriceAdjustment)).finalPrice * value.Quantity;
+ }
+ break;
}
- #endregion
+ return adjustment;
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs
index 8da39d21d..938c29163 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs
@@ -1,179 +1,178 @@
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Caching;
-using Grand.Infrastructure.Caching.Constants;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Caching.Constants;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Auction service
+/// </summary>
+public class AuctionService : IAuctionService
{
- /// <summary>
- /// Auction service
- /// </summary>
- public class AuctionService : IAuctionService
+ private readonly IRepository<Bid> _bidRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
+ private readonly IRepository<Product> _productRepository;
+
+ public AuctionService(IRepository<Bid> bidRepository,
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- private readonly IRepository<Bid> _bidRepository;
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
-
- public AuctionService(IRepository<Bid> bidRepository,
- IRepository<Product> productRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _bidRepository = bidRepository;
- _productRepository = productRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
+ _bidRepository = bidRepository;
+ _productRepository = productRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- public virtual Task<Bid> GetBid(string id)
- {
- return _bidRepository.GetByIdAsync(id);
- }
+ public virtual Task<Bid> GetBid(string id)
+ {
+ return _bidRepository.GetByIdAsync(id);
+ }
- public virtual async Task<Bid> GetLatestBid(string productId)
- {
- var bid = _bidRepository.Table
- .Where(x=>x.ProductId == productId)
- .OrderByDescending(x => x.Date)
- .ToList();
+ public virtual async Task<Bid> GetLatestBid(string productId)
+ {
+ var bid = _bidRepository.Table
+ .Where(x => x.ProductId == productId)
+ .OrderByDescending(x => x.Date)
+ .ToList();
- return await Task.FromResult(bid.FirstOrDefault());
- }
+ return await Task.FromResult(bid.FirstOrDefault());
+ }
- public virtual async Task<IPagedList<Bid>> GetBidsByProductId(string productId, int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = _bidRepository.Table.Where(x => x.ProductId == productId).OrderByDescending(x => x.Date);
- return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));
- }
+ public virtual async Task<IPagedList<Bid>> GetBidsByProductId(string productId, int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = _bidRepository.Table.Where(x => x.ProductId == productId).OrderByDescending(x => x.Date);
+ return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));
+ }
- public virtual async Task<IPagedList<Bid>> GetBidsByCustomerId(string customerId, int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = _bidRepository.Table.Where(x => x.CustomerId == customerId);
- return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));
- }
+ public virtual async Task<IPagedList<Bid>> GetBidsByCustomerId(string customerId, int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = _bidRepository.Table.Where(x => x.CustomerId == customerId);
+ return await Task.FromResult(new PagedList<Bid>(query, pageIndex, pageSize));
+ }
- public virtual async Task InsertBid(Bid bid)
- {
- ArgumentNullException.ThrowIfNull(bid);
+ public virtual async Task InsertBid(Bid bid)
+ {
+ ArgumentNullException.ThrowIfNull(bid);
- await _bidRepository.InsertAsync(bid);
- await _mediator.EntityInserted(bid);
- }
+ await _bidRepository.InsertAsync(bid);
+ await _mediator.EntityInserted(bid);
+ }
- public virtual async Task UpdateBid(Bid bid)
- {
- ArgumentNullException.ThrowIfNull(bid);
+ public virtual async Task UpdateBid(Bid bid)
+ {
+ ArgumentNullException.ThrowIfNull(bid);
- await _bidRepository.UpdateAsync(bid);
- await _mediator.EntityUpdated(bid);
- }
- public virtual async Task DeleteBid(Bid bid)
- {
- ArgumentNullException.ThrowIfNull(bid);
+ await _bidRepository.UpdateAsync(bid);
+ await _mediator.EntityUpdated(bid);
+ }
- await _bidRepository.DeleteAsync(bid);
- await _mediator.EntityDeleted(bid);
+ public virtual async Task DeleteBid(Bid bid)
+ {
+ ArgumentNullException.ThrowIfNull(bid);
- var productToUpdate = await _productRepository.GetByIdAsync(bid.ProductId);
- var bids = await GetBidsByProductId(bid.ProductId);
- var highestBid = bids.MaxBy(x => x.Amount);
- if (productToUpdate != null)
- {
- await UpdateHighestBid(productToUpdate, highestBid?.Amount ?? 0, highestBid != null ? highestBid.CustomerId : "");
- }
- }
- public virtual async Task UpdateHighestBid(Product product, double bid, string highestBidder)
- {
- product.HighestBid = bid;
- product.HighestBidder = highestBidder;
- await _productRepository.UpdateAsync(product);
+ await _bidRepository.DeleteAsync(bid);
+ await _mediator.EntityDeleted(bid);
+
+ var productToUpdate = await _productRepository.GetByIdAsync(bid.ProductId);
+ var bids = await GetBidsByProductId(bid.ProductId);
+ var highestBid = bids.MaxBy(x => x.Amount);
+ if (productToUpdate != null)
+ await UpdateHighestBid(productToUpdate, highestBid?.Amount ?? 0,
+ highestBid != null ? highestBid.CustomerId : "");
+ }
- await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ public virtual async Task UpdateHighestBid(Product product, double bid, string highestBidder)
+ {
+ product.HighestBid = bid;
+ product.HighestBidder = highestBidder;
+ await _productRepository.UpdateAsync(product);
- await _mediator.EntityUpdated(product);
- }
+ await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- public virtual async Task<IList<Product>> GetAuctionsToEnd()
- {
- return await Task.FromResult(_productRepository.Table
- .Where(x => x.ProductTypeId == ProductType.Auction &&
+ await _mediator.EntityUpdated(product);
+ }
+
+ public virtual async Task<IList<Product>> GetAuctionsToEnd()
+ {
+ return await Task.FromResult(_productRepository.Table
+ .Where(x => x.ProductTypeId == ProductType.Auction &&
!x.AuctionEnded && x.AvailableEndDateTimeUtc < DateTime.UtcNow).ToList());
- }
+ }
- public virtual async Task UpdateAuctionEnded(Product product, bool ended, bool endDate = false)
- {
- product.AuctionEnded = ended;
- if (endDate)
- product.AvailableEndDateTimeUtc = DateTime.UtcNow;
+ public virtual async Task UpdateAuctionEnded(Product product, bool ended, bool endDate = false)
+ {
+ product.AuctionEnded = ended;
+ if (endDate)
+ product.AvailableEndDateTimeUtc = DateTime.UtcNow;
- await _productRepository.UpdateAsync(product);
+ await _productRepository.UpdateAsync(product);
- await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- await _mediator.EntityUpdated(product);
- }
- /// <summary>
- /// New bid
- /// </summary>
- /// <param name="customer"></param>
- /// <param name="product"></param>
- /// <param name="store"></param>
- /// <param name="warehouseId"></param>
- /// <param name="language"></param>
- /// <param name="amount"></param>
- public virtual async Task NewBid(Customer customer, Product product, Store store, Language language, string warehouseId, double amount)
- {
- var latest = await GetLatestBid(product.Id);
- await InsertBid(new Bid
- {
- Date = DateTime.UtcNow,
- Amount = amount,
- CustomerId = customer.Id,
- ProductId = product.Id,
- StoreId = store.Id,
- WarehouseId = warehouseId
- });
-
- if (latest != null)
- {
- if (latest.CustomerId != customer.Id)
- {
- await _mediator.Send(new SendOutBidCustomerCommand {
- Product = product,
- Bid = latest,
- Language = language
- });
- }
- }
- product.HighestBid = amount;
- await UpdateHighestBid(product, amount, customer.Id);
- }
+ await _mediator.EntityUpdated(product);
+ }
- /// <summary>
- /// Cancel bid
- /// </summary>
- /// <param name="orderId">OrderId</param>
- public virtual async Task CancelBidByOrder(string orderId)
+ /// <summary>
+ /// New bid
+ /// </summary>
+ /// <param name="customer"></param>
+ /// <param name="product"></param>
+ /// <param name="store"></param>
+ /// <param name="warehouseId"></param>
+ /// <param name="language"></param>
+ /// <param name="amount"></param>
+ public virtual async Task NewBid(Customer customer, Product product, Store store, Language language,
+ string warehouseId, double amount)
+ {
+ var latest = await GetLatestBid(product.Id);
+ await InsertBid(new Bid {
+ Date = DateTime.UtcNow,
+ Amount = amount,
+ CustomerId = customer.Id,
+ ProductId = product.Id,
+ StoreId = store.Id,
+ WarehouseId = warehouseId
+ });
+
+ if (latest != null)
+ if (latest.CustomerId != customer.Id)
+ await _mediator.Send(new SendOutBidCustomerCommand {
+ Product = product,
+ Bid = latest,
+ Language = language
+ });
+ product.HighestBid = amount;
+ await UpdateHighestBid(product, amount, customer.Id);
+ }
+
+ /// <summary>
+ /// Cancel bid
+ /// </summary>
+ /// <param name="orderId">OrderId</param>
+ public virtual async Task CancelBidByOrder(string orderId)
+ {
+ var bid = await _bidRepository.GetOneAsync(x => x.OrderId == orderId);
+ if (bid != null)
{
- var bid = await _bidRepository.GetOneAsync(x => x.OrderId == orderId);
- if (bid != null)
+ await _bidRepository.DeleteAsync(bid);
+ var product = await _productRepository.GetByIdAsync(bid.ProductId);
+ if (product != null)
{
- await _bidRepository.DeleteAsync(bid);
- var product = await _productRepository.GetByIdAsync(bid.ProductId);
- if (product != null)
- {
- await UpdateHighestBid(product, 0, "");
- await UpdateAuctionEnded(product, false);
- }
+ await UpdateHighestBid(product, 0, "");
+ await UpdateAuctionEnded(product, false);
}
}
}
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs
index e4609c967..de203cfdd 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs
@@ -5,234 +5,202 @@ using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Domain.Catalog;
using Grand.Domain.Seo;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Copy Product service
+/// </summary>
+public class CopyProductService : ICopyProductService
{
+ #region Ctor
+
+ public CopyProductService(IProductService productService,
+ ILanguageService languageService,
+ ISlugService slugService,
+ SeoSettings seoSettings)
+ {
+ _productService = productService;
+ _languageService = languageService;
+ _slugService = slugService;
+ _seoSettings = seoSettings;
+ }
+
+ #endregion
+
+ #region Methods
+
/// <summary>
- /// Copy Product service
+ /// Create a copy of product with all depended data
/// </summary>
- public class CopyProductService : ICopyProductService
+ /// <param name="product">The product to copy</param>
+ /// <param name="newName">The name of product duplicate</param>
+ /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
+ /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
+ /// <returns>Product copy</returns>
+ public virtual async Task<Product> CopyProduct(Product product, string newName,
+ bool isPublished = true, bool copyAssociatedProducts = true)
{
- #region Fields
-
- private readonly IProductService _productService;
- private readonly ILanguageService _languageService;
- private readonly ISlugService _slugService;
- private readonly SeoSettings _seoSettings;
- #endregion
-
- #region Ctor
-
- public CopyProductService(IProductService productService,
- ILanguageService languageService,
- ISlugService slugService,
- SeoSettings seoSettings)
- {
- _productService = productService;
- _languageService = languageService;
- _slugService = slugService;
- _seoSettings = seoSettings;
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Create a copy of product with all depended data
- /// </summary>
- /// <param name="product">The product to copy</param>
- /// <param name="newName">The name of product duplicate</param>
- /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
- /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
- /// <returns>Product copy</returns>
- public virtual async Task<Product> CopyProduct(Product product, string newName,
- bool isPublished = true, bool copyAssociatedProducts = true)
- {
- ArgumentNullException.ThrowIfNull(product);
-
- if (string.IsNullOrEmpty(newName))
- newName = $"{product.Name} - CopyProduct";
-
- // product
- var productCopy = new Product {
- ProductTypeId = product.ProductTypeId,
- ParentGroupedProductId = product.ParentGroupedProductId,
- VisibleIndividually = product.VisibleIndividually,
- Name = newName,
- ShortDescription = product.ShortDescription,
- FullDescription = product.FullDescription,
- Flag = product.Flag,
- BrandId = product.BrandId,
- VendorId = product.VendorId,
- ProductLayoutId = product.ProductLayoutId,
- AdminComment = product.AdminComment,
- ShowOnHomePage = product.ShowOnHomePage,
- BestSeller = product.BestSeller,
- MetaKeywords = product.MetaKeywords,
- MetaDescription = product.MetaDescription,
- MetaTitle = product.MetaTitle,
- AllowCustomerReviews = product.AllowCustomerReviews,
- LimitedToStores = product.LimitedToStores,
- Sku = product.Sku,
- Mpn = product.Mpn,
- Gtin = product.Gtin,
- IsGiftVoucher = product.IsGiftVoucher,
- GiftVoucherTypeId = product.GiftVoucherTypeId,
- OverGiftAmount = product.OverGiftAmount,
- RequireOtherProducts = product.RequireOtherProducts,
- RequiredProductIds = product.RequiredProductIds,
- AutoAddRequiredProducts = product.AutoAddRequiredProducts,
- IsDownload = product.IsDownload,
- UnlimitedDownloads = product.UnlimitedDownloads,
- MaxNumberOfDownloads = product.MaxNumberOfDownloads,
- DownloadExpirationDays = product.DownloadExpirationDays,
- DownloadActivationTypeId = product.DownloadActivationTypeId,
- HasSampleDownload = product.HasSampleDownload,
- HasUserAgreement = product.HasUserAgreement,
- UserAgreementText = product.UserAgreementText,
- IsRecurring = product.IsRecurring,
- RecurringCycleLength = product.RecurringCycleLength,
- RecurringCyclePeriodId = product.RecurringCyclePeriodId,
- RecurringTotalCycles = product.RecurringTotalCycles,
- IsShipEnabled = product.IsShipEnabled,
- IsFreeShipping = product.IsFreeShipping,
- ShipSeparately = product.ShipSeparately,
- AdditionalShippingCharge = product.AdditionalShippingCharge,
- DeliveryDateId = product.DeliveryDateId,
- IsTaxExempt = product.IsTaxExempt,
- TaxCategoryId = product.TaxCategoryId,
- IsTele = product.IsTele,
- ManageInventoryMethodId = product.ManageInventoryMethodId,
- UseMultipleWarehouses = product.UseMultipleWarehouses,
- WarehouseId = product.WarehouseId,
- StockQuantity = product.StockQuantity,
- StockAvailability = product.StockAvailability,
- DisplayStockQuantity = product.DisplayStockQuantity,
- MinStockQuantity = product.MinStockQuantity,
- LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity,
- LowStockActivityId = product.LowStockActivityId,
- NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow,
- BackorderModeId = product.BackorderModeId,
- AllowOutOfStockSubscriptions = product.AllowOutOfStockSubscriptions,
- OrderMinimumQuantity = product.OrderMinimumQuantity,
- OrderMaximumQuantity = product.OrderMaximumQuantity,
- AllowedQuantities = product.AllowedQuantities,
- DisableBuyButton = product.DisableBuyButton,
- DisableWishlistButton = product.DisableWishlistButton,
- AvailableForPreOrder = product.AvailableForPreOrder,
- PreOrderDateTimeUtc = product.PreOrderDateTimeUtc,
- CallForPrice = product.CallForPrice,
- Price = product.Price,
- OldPrice = product.OldPrice,
- CatalogPrice = product.CatalogPrice,
- StartPrice = product.StartPrice,
- ProductCost = product.ProductCost,
- EnteredPrice = product.EnteredPrice,
- MinEnteredPrice = product.MinEnteredPrice,
- MaxEnteredPrice = product.MaxEnteredPrice,
- BasepriceEnabled = product.BasepriceEnabled,
- BasepriceAmount = product.BasepriceAmount,
- BasepriceUnitId = product.BasepriceUnitId,
- BasepriceBaseAmount = product.BasepriceBaseAmount,
- BasepriceBaseUnitId = product.BasepriceBaseUnitId,
- MarkAsNew = product.MarkAsNew,
- MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
- MarkAsNewEndDateTimeUtc = product.MarkAsNewEndDateTimeUtc,
- Weight = product.Weight,
- Length = product.Length,
- Width = product.Width,
- Height = product.Height,
- AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
- AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc,
- DisplayOrder = product.DisplayOrder,
- Published = isPublished,
- Locales = product.Locales,
- CustomerGroups = product.CustomerGroups,
- Stores = product.Stores
- };
-
- // product <-> warehouses mappings
- foreach (var pwi in product.ProductWarehouseInventory)
- {
- productCopy.ProductWarehouseInventory.Add(pwi);
- }
-
- // product <-> categories mappings
- foreach (var productCategory in product.ProductCategories)
- {
- productCopy.ProductCategories.Add(productCategory);
- }
-
- // product <-> collections mappings
- foreach (var productCollections in product.ProductCollections)
- {
- productCopy.ProductCollections.Add(productCollections);
- }
-
- // product <-> related products mappings
- foreach (var relatedProduct in product.RelatedProducts)
- {
- productCopy.RelatedProducts.Add(relatedProduct);
- }
-
- //product tags
- foreach (var productTag in product.ProductTags)
- {
- productCopy.ProductTags.Add(productTag);
- }
-
- // product <-> attributes mappings
- foreach (var productAttributeMapping in product.ProductAttributeMappings)
- {
- productCopy.ProductAttributeMappings.Add(productAttributeMapping);
- }
- //attribute combinations
- foreach (var combination in product.ProductAttributeCombinations)
- {
- productCopy.ProductAttributeCombinations.Add(combination);
- }
-
- foreach (var csProduct in product.CrossSellProduct)
- {
- productCopy.CrossSellProduct.Add(csProduct);
- }
-
- foreach (var reProduct in product.RecommendedProduct)
- {
- productCopy.RecommendedProduct.Add(reProduct);
- }
-
- // product specifications
- foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
- {
- productCopy.ProductSpecificationAttributes.Add(productSpecificationAttribute);
- }
-
- //tier prices
- foreach (var tierPrice in product.TierPrices)
- {
- productCopy.TierPrices.Add(tierPrice);
- }
-
- // product <-> discounts mapping
- foreach (var discount in product.AppliedDiscounts)
- {
- productCopy.AppliedDiscounts.Add(discount);
-
- }
-
- //validate search engine name
- await _productService.InsertProduct(productCopy);
-
- //search engine name
- var seName = await productCopy.ValidateSeName("", productCopy.Name, true, _seoSettings, _slugService, _languageService);
- productCopy.SeName = seName;
- await _productService.UpdateProduct(productCopy);
- await _slugService.SaveSlug(productCopy, seName, "");
-
- return productCopy;
- }
-
- #endregion
+ ArgumentNullException.ThrowIfNull(product);
+
+ if (string.IsNullOrEmpty(newName))
+ newName = $"{product.Name} - CopyProduct";
+
+ // product
+ var productCopy = new Product {
+ ProductTypeId = product.ProductTypeId,
+ ParentGroupedProductId = product.ParentGroupedProductId,
+ VisibleIndividually = product.VisibleIndividually,
+ Name = newName,
+ ShortDescription = product.ShortDescription,
+ FullDescription = product.FullDescription,
+ Flag = product.Flag,
+ BrandId = product.BrandId,
+ VendorId = product.VendorId,
+ ProductLayoutId = product.ProductLayoutId,
+ AdminComment = product.AdminComment,
+ ShowOnHomePage = product.ShowOnHomePage,
+ BestSeller = product.BestSeller,
+ MetaKeywords = product.MetaKeywords,
+ MetaDescription = product.MetaDescription,
+ MetaTitle = product.MetaTitle,
+ AllowCustomerReviews = product.AllowCustomerReviews,
+ LimitedToStores = product.LimitedToStores,
+ Sku = product.Sku,
+ Mpn = product.Mpn,
+ Gtin = product.Gtin,
+ IsGiftVoucher = product.IsGiftVoucher,
+ GiftVoucherTypeId = product.GiftVoucherTypeId,
+ OverGiftAmount = product.OverGiftAmount,
+ RequireOtherProducts = product.RequireOtherProducts,
+ RequiredProductIds = product.RequiredProductIds,
+ AutoAddRequiredProducts = product.AutoAddRequiredProducts,
+ IsDownload = product.IsDownload,
+ UnlimitedDownloads = product.UnlimitedDownloads,
+ MaxNumberOfDownloads = product.MaxNumberOfDownloads,
+ DownloadExpirationDays = product.DownloadExpirationDays,
+ DownloadActivationTypeId = product.DownloadActivationTypeId,
+ HasSampleDownload = product.HasSampleDownload,
+ HasUserAgreement = product.HasUserAgreement,
+ UserAgreementText = product.UserAgreementText,
+ IsRecurring = product.IsRecurring,
+ RecurringCycleLength = product.RecurringCycleLength,
+ RecurringCyclePeriodId = product.RecurringCyclePeriodId,
+ RecurringTotalCycles = product.RecurringTotalCycles,
+ IsShipEnabled = product.IsShipEnabled,
+ IsFreeShipping = product.IsFreeShipping,
+ ShipSeparately = product.ShipSeparately,
+ AdditionalShippingCharge = product.AdditionalShippingCharge,
+ DeliveryDateId = product.DeliveryDateId,
+ IsTaxExempt = product.IsTaxExempt,
+ TaxCategoryId = product.TaxCategoryId,
+ IsTele = product.IsTele,
+ ManageInventoryMethodId = product.ManageInventoryMethodId,
+ UseMultipleWarehouses = product.UseMultipleWarehouses,
+ WarehouseId = product.WarehouseId,
+ StockQuantity = product.StockQuantity,
+ StockAvailability = product.StockAvailability,
+ DisplayStockQuantity = product.DisplayStockQuantity,
+ MinStockQuantity = product.MinStockQuantity,
+ LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity,
+ LowStockActivityId = product.LowStockActivityId,
+ NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow,
+ BackorderModeId = product.BackorderModeId,
+ AllowOutOfStockSubscriptions = product.AllowOutOfStockSubscriptions,
+ OrderMinimumQuantity = product.OrderMinimumQuantity,
+ OrderMaximumQuantity = product.OrderMaximumQuantity,
+ AllowedQuantities = product.AllowedQuantities,
+ DisableBuyButton = product.DisableBuyButton,
+ DisableWishlistButton = product.DisableWishlistButton,
+ AvailableForPreOrder = product.AvailableForPreOrder,
+ PreOrderDateTimeUtc = product.PreOrderDateTimeUtc,
+ CallForPrice = product.CallForPrice,
+ Price = product.Price,
+ OldPrice = product.OldPrice,
+ CatalogPrice = product.CatalogPrice,
+ StartPrice = product.StartPrice,
+ ProductCost = product.ProductCost,
+ EnteredPrice = product.EnteredPrice,
+ MinEnteredPrice = product.MinEnteredPrice,
+ MaxEnteredPrice = product.MaxEnteredPrice,
+ BasepriceEnabled = product.BasepriceEnabled,
+ BasepriceAmount = product.BasepriceAmount,
+ BasepriceUnitId = product.BasepriceUnitId,
+ BasepriceBaseAmount = product.BasepriceBaseAmount,
+ BasepriceBaseUnitId = product.BasepriceBaseUnitId,
+ MarkAsNew = product.MarkAsNew,
+ MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
+ MarkAsNewEndDateTimeUtc = product.MarkAsNewEndDateTimeUtc,
+ Weight = product.Weight,
+ Length = product.Length,
+ Width = product.Width,
+ Height = product.Height,
+ AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
+ AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc,
+ DisplayOrder = product.DisplayOrder,
+ Published = isPublished,
+ Locales = product.Locales,
+ CustomerGroups = product.CustomerGroups,
+ Stores = product.Stores
+ };
+
+ // product <-> warehouses mappings
+ foreach (var pwi in product.ProductWarehouseInventory) productCopy.ProductWarehouseInventory.Add(pwi);
+
+ // product <-> categories mappings
+ foreach (var productCategory in product.ProductCategories) productCopy.ProductCategories.Add(productCategory);
+
+ // product <-> collections mappings
+ foreach (var productCollections in product.ProductCollections)
+ productCopy.ProductCollections.Add(productCollections);
+
+ // product <-> related products mappings
+ foreach (var relatedProduct in product.RelatedProducts) productCopy.RelatedProducts.Add(relatedProduct);
+
+ //product tags
+ foreach (var productTag in product.ProductTags) productCopy.ProductTags.Add(productTag);
+
+ // product <-> attributes mappings
+ foreach (var productAttributeMapping in product.ProductAttributeMappings)
+ productCopy.ProductAttributeMappings.Add(productAttributeMapping);
+ //attribute combinations
+ foreach (var combination in product.ProductAttributeCombinations)
+ productCopy.ProductAttributeCombinations.Add(combination);
+
+ foreach (var csProduct in product.CrossSellProduct) productCopy.CrossSellProduct.Add(csProduct);
+
+ foreach (var reProduct in product.RecommendedProduct) productCopy.RecommendedProduct.Add(reProduct);
+
+ // product specifications
+ foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
+ productCopy.ProductSpecificationAttributes.Add(productSpecificationAttribute);
+
+ //tier prices
+ foreach (var tierPrice in product.TierPrices) productCopy.TierPrices.Add(tierPrice);
+
+ // product <-> discounts mapping
+ foreach (var discount in product.AppliedDiscounts) productCopy.AppliedDiscounts.Add(discount);
+
+ //validate search engine name
+ await _productService.InsertProduct(productCopy);
+
+ //search engine name
+ var seName =
+ await productCopy.ValidateSeName("", productCopy.Name, true, _seoSettings, _slugService, _languageService);
+ productCopy.SeName = seName;
+ await _productService.UpdateProduct(productCopy);
+ await _slugService.SaveSlug(productCopy, seName, "");
+
+ return productCopy;
}
+
+ #endregion
+
+ #region Fields
+
+ private readonly IProductService _productService;
+ private readonly ILanguageService _languageService;
+ private readonly ISlugService _slugService;
+ private readonly SeoSettings _seoSettings;
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs
index da1a4b018..47eea7c08 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs
@@ -1,133 +1,134 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+public class CustomerGroupProductService : ICustomerGroupProductService
{
- public class CustomerGroupProductService : ICustomerGroupProductService
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
+ private readonly IMediator _mediator;
+
+
+ public CustomerGroupProductService(IRepository<CustomerGroupProduct> customerGroupProductRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- private readonly IRepository<CustomerGroupProduct> _customerGroupProductRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _customerGroupProductRepository = customerGroupProductRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
+ #region Customer Group Products
- public CustomerGroupProductService(IRepository<CustomerGroupProduct> customerGroupProductRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _customerGroupProductRepository = customerGroupProductRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
-
- #region Customer Group Products
-
- /// <summary>
- /// Delete a customer group product
- /// </summary>
- /// <param name="customerGroupProduct">Customer group product</param>
- public virtual async Task DeleteCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
- {
- ArgumentNullException.ThrowIfNull(customerGroupProduct);
+ /// <summary>
+ /// Delete a customer group product
+ /// </summary>
+ /// <param name="customerGroupProduct">Customer group product</param>
+ public virtual async Task DeleteCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroupProduct);
- await _customerGroupProductRepository.DeleteAsync(customerGroupProduct);
+ await _customerGroupProductRepository.DeleteAsync(customerGroupProduct);
- //clear cache
- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupProduct.CustomerGroupId));
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
+ //clear cache
+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY,
+ customerGroupProduct.CustomerGroupId));
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
- //event notification
- await _mediator.EntityDeleted(customerGroupProduct);
- }
+ //event notification
+ await _mediator.EntityDeleted(customerGroupProduct);
+ }
- /// <summary>
- /// Inserts a customer group product
- /// </summary>
- /// <param name="customerGroupProduct">Customer group product</param>
- public virtual async Task InsertCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
- {
- ArgumentNullException.ThrowIfNull(customerGroupProduct);
+ /// <summary>
+ /// Inserts a customer group product
+ /// </summary>
+ /// <param name="customerGroupProduct">Customer group product</param>
+ public virtual async Task InsertCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroupProduct);
- await _customerGroupProductRepository.InsertAsync(customerGroupProduct);
+ await _customerGroupProductRepository.InsertAsync(customerGroupProduct);
- //clear cache
- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupProduct.CustomerGroupId));
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
+ //clear cache
+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY,
+ customerGroupProduct.CustomerGroupId));
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
- //event notification
- await _mediator.EntityInserted(customerGroupProduct);
- }
+ //event notification
+ await _mediator.EntityInserted(customerGroupProduct);
+ }
- /// <summary>
- /// Updates the customer group product
- /// </summary>
- /// <param name="customerGroupProduct">Customer group product</param>
- public virtual async Task UpdateCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
- {
- ArgumentNullException.ThrowIfNull(customerGroupProduct);
+ /// <summary>
+ /// Updates the customer group product
+ /// </summary>
+ /// <param name="customerGroupProduct">Customer group product</param>
+ public virtual async Task UpdateCustomerGroupProduct(CustomerGroupProduct customerGroupProduct)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroupProduct);
- await _customerGroupProductRepository.UpdateAsync(customerGroupProduct);
+ await _customerGroupProductRepository.UpdateAsync(customerGroupProduct);
- //clear cache
- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupProduct.CustomerGroupId));
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
+ //clear cache
+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY,
+ customerGroupProduct.CustomerGroupId));
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
- //event notification
- await _mediator.EntityUpdated(customerGroupProduct);
- }
+ //event notification
+ await _mediator.EntityUpdated(customerGroupProduct);
+ }
- /// <summary>
- /// Gets customer groups products for customer group
- /// </summary>
- /// <param name="customerGroupId">Customer group id</param>
- /// <returns>Customer group products</returns>
- public virtual async Task<IList<CustomerGroupProduct>> GetCustomerGroupProducts(string customerGroupId)
- {
- var key = string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupId);
- return await _cacheBase.GetAsync(key, async () =>
- {
- return await Task.FromResult(_customerGroupProductRepository
- .Table.Where(x => x.CustomerGroupId == customerGroupId)
- .OrderBy(x => x.DisplayOrder)
- .ToList());
- });
- }
-
- /// <summary>
- /// Gets customer groups products for customer group
- /// </summary>
- /// <param name="customerGroupId">Customer group id</param>
- /// <param name="productId">Product id</param>
- /// <returns>Customer group product</returns>
- public virtual async Task<CustomerGroupProduct> GetCustomerGroupProduct(string customerGroupId, string productId)
- {
- return await Task.FromResult(_customerGroupProductRepository.Table
- .Where(x => x.CustomerGroupId == customerGroupId && x.ProductId == productId)
- .OrderBy(x => x.DisplayOrder).FirstOrDefault());
- }
-
- /// <summary>
- /// Gets customer groups product
- /// </summary>
- /// <param name="id">Ident</param>
- /// <returns>Customer group product</returns>
- public virtual async Task<CustomerGroupProduct> GetCustomerGroupProductById(string id)
+ /// <summary>
+ /// Gets customer groups products for customer group
+ /// </summary>
+ /// <param name="customerGroupId">Customer group id</param>
+ /// <returns>Customer group products</returns>
+ public virtual async Task<IList<CustomerGroupProduct>> GetCustomerGroupProducts(string customerGroupId)
+ {
+ var key = string.Format(CacheKey.CUSTOMERGROUPSPRODUCTS_ROLE_KEY, customerGroupId);
+ return await _cacheBase.GetAsync(key, async () =>
{
- var query = from cr in _customerGroupProductRepository.Table
- where cr.Id == id
- orderby cr.DisplayOrder
- select cr;
+ return await Task.FromResult(_customerGroupProductRepository
+ .Table.Where(x => x.CustomerGroupId == customerGroupId)
+ .OrderBy(x => x.DisplayOrder)
+ .ToList());
+ });
+ }
- return await Task.FromResult(query.FirstOrDefault());
- }
+ /// <summary>
+ /// Gets customer groups products for customer group
+ /// </summary>
+ /// <param name="customerGroupId">Customer group id</param>
+ /// <param name="productId">Product id</param>
+ /// <returns>Customer group product</returns>
+ public virtual async Task<CustomerGroupProduct> GetCustomerGroupProduct(string customerGroupId, string productId)
+ {
+ return await Task.FromResult(_customerGroupProductRepository.Table
+ .Where(x => x.CustomerGroupId == customerGroupId && x.ProductId == productId)
+ .OrderBy(x => x.DisplayOrder).FirstOrDefault());
+ }
+ /// <summary>
+ /// Gets customer groups product
+ /// </summary>
+ /// <param name="id">Ident</param>
+ /// <returns>Customer group product</returns>
+ public virtual async Task<CustomerGroupProduct> GetCustomerGroupProductById(string id)
+ {
+ var query = from cr in _customerGroupProductRepository.Table
+ where cr.Id == id
+ orderby cr.DisplayOrder
+ select cr;
- #endregion
+ return await Task.FromResult(query.FirstOrDefault());
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
index fd95232b9..64f9f41ad 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
@@ -1,313 +1,365 @@
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Events.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
-using Grand.Data;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+public class InventoryManageService : IInventoryManageService
{
- public class InventoryManageService : IInventoryManageService
+ #region Ctor
+
+ public InventoryManageService(
+ IRepository<Product> productRepository,
+ IRepository<InventoryJournal> inventoryJournalRepository,
+ IStockQuantityService stockQuantityService,
+ ICacheBase cacheBase,
+ IMediator mediator,
+ CatalogSettings catalogSettings)
+ {
+ _productRepository = productRepository;
+ _inventoryJournalRepository = inventoryJournalRepository;
+ _stockQuantityService = stockQuantityService;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ _catalogSettings = catalogSettings;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<InventoryJournal> _inventoryJournalRepository;
+ private readonly IStockQuantityService _stockQuantityService;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
+ private readonly CatalogSettings _catalogSettings;
+
+ #endregion
+
+ #region Utilities methods
+
+ private async Task ManageStockInventory(Product product, ShipmentItem shipmentItem)
{
- #region Fields
-
- private readonly IRepository<Product> _productRepository;
- private readonly IRepository<InventoryJournal> _inventoryJournalRepository;
- private readonly IStockQuantityService _stockQuantityService;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
- private readonly CatalogSettings _catalogSettings;
-
- #endregion
-
- #region Ctor
-
- public InventoryManageService(
- IRepository<Product> productRepository,
- IRepository<InventoryJournal> inventoryJournalRepository,
- IStockQuantityService stockQuantityService,
- ICacheBase cacheBase,
- IMediator mediator,
- CatalogSettings catalogSettings)
+ if (product.UseMultipleWarehouses)
{
- _productRepository = productRepository;
- _inventoryJournalRepository = inventoryJournalRepository;
- _stockQuantityService = stockQuantityService;
- _cacheBase = cacheBase;
- _mediator = mediator;
- _catalogSettings = catalogSettings;
- }
+ var pwi = product.ProductWarehouseInventory.FirstOrDefault(pi =>
+ pi.WarehouseId == shipmentItem.WarehouseId);
+ if (pwi == null)
+ return;
- #endregion
+ pwi.ReservedQuantity -= shipmentItem.Quantity;
+ pwi.StockQuantity -= shipmentItem.Quantity;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- #region Utilities methods
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- private async Task ManageStockInventory(Product product, ShipmentItem shipmentItem)
+ product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);
+ await UpdateStockProduct(product);
+ }
+ else
{
- if (product.UseMultipleWarehouses)
- {
- var pwi = product.ProductWarehouseInventory.FirstOrDefault(pi => pi.WarehouseId == shipmentItem.WarehouseId);
- if (pwi == null)
- return;
+ product.ReservedQuantity -= shipmentItem.Quantity;
+ product.StockQuantity -= shipmentItem.Quantity;
+ await UpdateStockProduct(product);
+ }
+ }
- pwi.ReservedQuantity -= shipmentItem.Quantity;
- pwi.StockQuantity -= shipmentItem.Quantity;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ private async Task ManageStockByAttributesInventory(Product product, ShipmentItem shipmentItem)
+ {
+ var combination = product.FindProductAttributeCombination(shipmentItem.Attributes);
+ if (combination == null)
+ return;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ if (!product.UseMultipleWarehouses)
+ {
+ combination.ReservedQuantity -= shipmentItem.Quantity;
+ combination.StockQuantity -= shipmentItem.Quantity;
+ if (combination.ReservedQuantity < 0)
+ combination.ReservedQuantity = 0;
- product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);
- await UpdateStockProduct(product);
- }
- else
- {
- product.ReservedQuantity -= shipmentItem.Quantity;
- product.StockQuantity -= shipmentItem.Quantity;
- await UpdateStockProduct(product);
- }
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
- private async Task ManageStockByAttributesInventory(Product product, ShipmentItem shipmentItem)
+ else
{
- var combination = product.FindProductAttributeCombination(shipmentItem.Attributes);
- if (combination == null)
+ var pwi = combination.WarehouseInventory.FirstOrDefault(pi => pi.WarehouseId == shipmentItem.WarehouseId);
+ if (pwi == null)
return;
- if (!product.UseMultipleWarehouses)
- {
- combination.ReservedQuantity -= shipmentItem.Quantity;
- combination.StockQuantity -= shipmentItem.Quantity;
- if (combination.ReservedQuantity < 0)
- combination.ReservedQuantity = 0;
+ pwi.ReservedQuantity -= shipmentItem.Quantity;
+ pwi.StockQuantity -= shipmentItem.Quantity;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- }
- else
+ combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
+ combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
+
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ }
+
+ product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ await UpdateStockProduct(product);
+ }
+
+ private async Task ManageStockByBundleProductsInventory(Product product, Shipment shipment,
+ ShipmentItem shipmentItem)
+ {
+ foreach (var item in product.BundleProducts)
+ {
+ var p1 = await _productRepository.GetByIdAsync(item.ProductId);
+ if (p1 == null || p1.Id == product.Id ||
+ p1.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;
+ var shipmentItem1 = new ShipmentItem {
+ Id = shipmentItem.Id,
+ Attributes = shipmentItem.Attributes,
+ OrderItemId = shipmentItem.OrderItemId,
+ ProductId = shipmentItem.ProductId,
+ Quantity = shipmentItem.Quantity * item.Quantity,
+ WarehouseId = shipmentItem.WarehouseId
+ };
+ if (!await CheckExistsInventoryJournal(p1, shipmentItem1))
+ await BookReservedInventory(p1, shipment, shipmentItem1);
+ }
+ }
+
+ private async Task ManageAttributesInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)
+ {
+ var attributeValues = product.ParseProductAttributeValues(shipmentItem.Attributes);
+ foreach (var attributeValue in attributeValues)
+ {
+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;
+ //associated product
+ var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);
+ if (associatedProduct == null
+ || associatedProduct.Id == product.Id
+ || associatedProduct.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;
+ if (await CheckExistsInventoryJournal(associatedProduct, shipmentItem)) continue;
+ var item = new ShipmentItem {
+ Id = shipmentItem.Id,
+ Attributes = shipmentItem.Attributes,
+ OrderItemId = shipmentItem.OrderItemId,
+ ProductId = shipmentItem.ProductId,
+ Quantity = shipmentItem.Quantity * attributeValue.Quantity,
+ WarehouseId = shipmentItem.WarehouseId
+ };
+ await BookReservedInventory(associatedProduct, shipment, item);
+ }
+ }
+
+ private async Task<bool> CheckExistsInventoryJournal(Product product, ShipmentItem shipmentItem)
+ {
+ var query = from j in _inventoryJournalRepository.Table
+ where j.ProductId == product.Id && j.PositionId == shipmentItem.Id
+ select j.Id;
+
+ return await Task.FromResult(query.Any());
+ }
+
+ private async Task ReverseBookedInventory(Product product, InventoryJournal inventoryJournal)
+ {
+ switch (product.ManageInventoryMethodId)
+ {
+ //standard manage stock
+ case ManageInventoryMethod.ManageStock when product.UseMultipleWarehouses:
{
- var pwi = combination.WarehouseInventory.FirstOrDefault(pi => pi.WarehouseId == shipmentItem.WarehouseId);
+ var pwi = product.ProductWarehouseInventory.FirstOrDefault(x =>
+ x.WarehouseId == inventoryJournal.WarehouseId);
if (pwi == null)
return;
- pwi.ReservedQuantity -= shipmentItem.Quantity;
- pwi.StockQuantity -= shipmentItem.Quantity;
+ pwi.StockQuantity += inventoryJournal.OutQty;
+ pwi.ReservedQuantity += inventoryJournal.OutQty;
if (pwi.ReservedQuantity < 0)
pwi.ReservedQuantity = 0;
- combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
- combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
-
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id,
+ pwi);
await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
-
+ break;
}
- product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- await UpdateStockProduct(product);
- }
- private async Task ManageStockByBundleProductsInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)
- {
- foreach (var item in product.BundleProducts)
+ case ManageInventoryMethod.ManageStock:
+ product.StockQuantity += inventoryJournal.OutQty;
+ product.ReservedQuantity += inventoryJournal.OutQty;
+ await UpdateStockProduct(product);
+ break;
+ //manage stock by attributes
+ case ManageInventoryMethod.ManageStockByAttributes:
{
- var p1 = await _productRepository.GetByIdAsync(item.ProductId);
- if (p1 == null || p1.Id == product.Id ||
- p1.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;
- var shipmentItem1 = new ShipmentItem {
- Id = shipmentItem.Id,
- Attributes = shipmentItem.Attributes,
- OrderItemId = shipmentItem.OrderItemId,
- ProductId = shipmentItem.ProductId,
- Quantity = shipmentItem.Quantity * item.Quantity,
- WarehouseId = shipmentItem.WarehouseId
- };
- if (!await CheckExistsInventoryJournal(p1, shipmentItem1))
+ var combination = product.FindProductAttributeCombination(inventoryJournal.Attributes);
+ if (combination == null)
+ return;
+
+ if (!product.UseMultipleWarehouses)
{
- await BookReservedInventory(p1, shipment, shipmentItem1);
- }
- }
- }
- private async Task ManageAttributesInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)
- {
- var attributeValues = product.ParseProductAttributeValues(shipmentItem.Attributes);
- foreach (var attributeValue in attributeValues)
- {
- if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;
- //associated product
- var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);
- if (associatedProduct == null
- || associatedProduct.Id == product.Id
- || associatedProduct.ManageInventoryMethodId == ManageInventoryMethod.DontManageStock) continue;
- if (await CheckExistsInventoryJournal(associatedProduct, shipmentItem)) continue;
- var item = new ShipmentItem {
- Id = shipmentItem.Id,
- Attributes = shipmentItem.Attributes,
- OrderItemId = shipmentItem.OrderItemId,
- ProductId = shipmentItem.ProductId,
- Quantity = shipmentItem.Quantity * attributeValue.Quantity,
- WarehouseId = shipmentItem.WarehouseId
- };
- await BookReservedInventory(associatedProduct, shipment, item);
- }
- }
+ combination.StockQuantity += inventoryJournal.OutQty;
+ combination.ReservedQuantity += inventoryJournal.OutQty;
+ if (combination.ReservedQuantity < 0)
+ combination.ReservedQuantity = 0;
- private async Task<bool> CheckExistsInventoryJournal(Product product, ShipmentItem shipmentItem)
- {
- var query = from j in _inventoryJournalRepository.Table
- where j.ProductId == product.Id && j.PositionId == shipmentItem.Id
- select j.Id;
+ product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- return await Task.FromResult(query.Any());
- }
- private async Task ReverseBookedInventory(Product product, InventoryJournal inventoryJournal)
- {
- switch (product.ManageInventoryMethodId)
- {
- //standard manage stock
- case ManageInventoryMethod.ManageStock when product.UseMultipleWarehouses:
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+
+ await UpdateStockProduct(product);
+ }
+ else
{
- var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == inventoryJournal.WarehouseId);
+ var pwi = combination.WarehouseInventory.FirstOrDefault(x =>
+ x.WarehouseId == inventoryJournal.WarehouseId);
if (pwi == null)
return;
pwi.StockQuantity += inventoryJournal.OutQty;
pwi.ReservedQuantity += inventoryJournal.OutQty;
+
if (pwi.ReservedQuantity < 0)
pwi.ReservedQuantity = 0;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
+ combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
+ combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
+ product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- break;
- }
- case ManageInventoryMethod.ManageStock:
- product.StockQuantity += inventoryJournal.OutQty;
- product.ReservedQuantity += inventoryJournal.OutQty;
await UpdateStockProduct(product);
- break;
- //manage stock by attributes
- case ManageInventoryMethod.ManageStockByAttributes:
- {
- var combination = product.FindProductAttributeCombination(inventoryJournal.Attributes);
- if (combination == null)
- return;
-
- if (!product.UseMultipleWarehouses)
- {
- combination.StockQuantity += inventoryJournal.OutQty;
- combination.ReservedQuantity += inventoryJournal.OutQty;
- if (combination.ReservedQuantity < 0)
- combination.ReservedQuantity = 0;
+ }
- product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ break;
+ }
+ }
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ await _inventoryJournalRepository.DeleteAsync(inventoryJournal);
+ }
- await UpdateStockProduct(product);
+ private async Task InsertInventoryJournal(Product product, Shipment shipment, ShipmentItem shipmentItem)
+ {
+ var ij = new InventoryJournal {
+ CreateDateUtc = DateTime.UtcNow,
+ ObjectType = typeof(Shipment).Name,
+ ObjectId = shipment.Id,
+ PositionId = shipmentItem.Id,
+ Attributes = shipmentItem.Attributes,
+ ProductId = product.Id,
+ WarehouseId = shipmentItem.WarehouseId,
+ Reference = shipment.ShipmentNumber.ToString(),
+ Comments = $"Shipment - {shipment.TrackingNumber}",
+ OutQty = shipmentItem.Quantity
+ };
+ await _inventoryJournalRepository.InsertAsync(ij);
+ }
+ #endregion
- }
- else
- {
- var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == inventoryJournal.WarehouseId);
- if (pwi == null)
- return;
+ #region Inventory management methods
- pwi.StockQuantity += inventoryJournal.OutQty;
- pwi.ReservedQuantity += inventoryJournal.OutQty;
+ /// <summary>
+ /// Adjust reserved inventory
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="quantityToChange">Quantity to increase or decrease</param>
+ /// <param name="attributes">Attributes</param>
+ /// <param name="warehouseId">Warehouse ident</param>
+ public virtual async Task AdjustReserved(Product product, int quantityToChange,
+ IList<CustomAttribute> attributes = null, string warehouseId = "")
+ {
+ ArgumentNullException.ThrowIfNull(product);
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ if (quantityToChange == 0)
+ return;
- combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
- combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
- product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
+ {
+ var prevStockQuantity = _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId);
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- await UpdateStockProduct(product);
+ //update stock quantity
+ if (quantityToChange < 0)
+ await ReserveInventory(product, quantityToChange, warehouseId);
+ else
+ await UnblockReservedInventory(product, quantityToChange, warehouseId);
- }
+ if (product.UseMultipleWarehouses)
+ {
+ product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);
- break;
- }
+ await UpdateStockProduct(product);
}
- await _inventoryJournalRepository.DeleteAsync(inventoryJournal);
- }
- private async Task InsertInventoryJournal(Product product, Shipment shipment, ShipmentItem shipmentItem)
- {
- var ij = new InventoryJournal {
- CreateDateUtc = DateTime.UtcNow,
- ObjectType = typeof(Shipment).Name,
- ObjectId = shipment.Id,
- PositionId = shipmentItem.Id,
- Attributes = shipmentItem.Attributes,
- ProductId = product.Id,
- WarehouseId = shipmentItem.WarehouseId,
- Reference = shipment.ShipmentNumber.ToString(),
- Comments = $"Shipment - {shipment.TrackingNumber}",
- OutQty = shipmentItem.Quantity
- };
- await _inventoryJournalRepository.InsertAsync(ij);
+ //check if minimum quantity is reached
+ if (quantityToChange < 0 && product.MinStockQuantity >=
+ _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId))
+ switch (product.LowStockActivityId)
+ {
+ case LowStockActivity.DisableBuyButton:
+ product.DisableBuyButton = true;
+ product.LowStock = true;
- }
+ await _productRepository.UpdateField(product.Id, x => x.DisableBuyButton,
+ product.DisableBuyButton);
+ await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- #endregion
+ //event notification
+ await _mediator.EntityUpdated(product);
- #region Inventory management methods
+ break;
+ case LowStockActivity.Unpublish:
+ product.Published = false;
+ product.LowStock = true;
- /// <summary>
- /// Adjust reserved inventory
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="quantityToChange">Quantity to increase or decrease</param>
- /// <param name="attributes">Attributes</param>
- /// <param name="warehouseId">Warehouse ident</param>
- public virtual async Task AdjustReserved(Product product, int quantityToChange, IList<CustomAttribute> attributes = null, string warehouseId = "")
- {
- ArgumentNullException.ThrowIfNull(product);
+ await _productRepository.UpdateField(product.Id, x => x.Published, product.Published);
+ await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- if (quantityToChange == 0)
- return;
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
- {
- var prevStockQuantity = _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId);
+ //event
+ await _mediator.Publish(new ProductUnPublishEvent(product));
- //update stock quantity
- if (quantityToChange < 0)
- await ReserveInventory(product, quantityToChange, warehouseId);
- else
- await UnblockReservedInventory(product, quantityToChange, warehouseId);
+ //event notification
+ await _mediator.EntityUpdated(product);
- if (product.UseMultipleWarehouses)
- {
- product.StockQuantity = product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductWarehouseInventory.Sum(x => x.ReservedQuantity);
-
- await UpdateStockProduct(product);
+ break;
}
- //check if minimum quantity is reached
- if (quantityToChange < 0 && product.MinStockQuantity >= _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId))
- {
+
+ //qty is increased. product is out of stock (minimum stock quantity is reached again)?
+ if (_catalogSettings.PublishBackProductWhenCancellingOrders)
+ if (quantityToChange > 0 && product.MinStockQuantity >= prevStockQuantity)
switch (product.LowStockActivityId)
{
case LowStockActivity.DisableBuyButton:
- product.DisableBuyButton = true;
- product.LowStock = true;
+ product.DisableBuyButton = false;
+ product.LowStock = product.MinStockQuantity <= prevStockQuantity;
- await _productRepository.UpdateField(product.Id, x => x.DisableBuyButton, product.DisableBuyButton);
+ await _productRepository.UpdateField(product.Id, x => x.DisableBuyButton,
+ product.DisableBuyButton);
await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+
//cache
await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
@@ -316,8 +368,8 @@ namespace Grand.Business.Catalog.Services.Products
break;
case LowStockActivity.Unpublish:
- product.Published = false;
- product.LowStock = true;
+ product.Published = true;
+ product.LowStock = product.MinStockQuantity < prevStockQuantity;
await _productRepository.UpdateField(product.Id, x => x.Published, product.Published);
await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
@@ -327,413 +379,360 @@ namespace Grand.Business.Catalog.Services.Products
await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
//event
- await _mediator.Publish(new ProductUnPublishEvent(product));
+ await _mediator.Publish(new ProductPublishEvent(product));
//event notification
await _mediator.EntityUpdated(product);
break;
}
- }
- //qty is increased. product is out of stock (minimum stock quantity is reached again)?
- if (_catalogSettings.PublishBackProductWhenCancellingOrders)
- {
- if (quantityToChange > 0 && product.MinStockQuantity >= prevStockQuantity)
- {
- switch (product.LowStockActivityId)
- {
- case LowStockActivity.DisableBuyButton:
- product.DisableBuyButton = false;
- product.LowStock = product.MinStockQuantity <= prevStockQuantity;
-
- await _productRepository.UpdateField(product.Id, x => x.DisableBuyButton, product.DisableBuyButton);
- await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
-
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- //event notification
- await _mediator.EntityUpdated(product);
-
- break;
- case LowStockActivity.Unpublish:
- product.Published = true;
- product.LowStock = product.MinStockQuantity < prevStockQuantity;
-
- await _productRepository.UpdateField(product.Id, x => x.Published, product.Published);
- await _productRepository.UpdateField(product.Id, x => x.LowStock, product.LowStock);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
-
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
-
- //event
- await _mediator.Publish(new ProductPublishEvent(product));
-
- //event notification
- await _mediator.EntityUpdated(product);
+ //send email notification
+ if (quantityToChange < 0 && _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId) <
+ product.NotifyAdminForQuantityBelow)
+ await _mediator.Send(new SendQuantityBelowStoreOwnerCommand {
+ Product = product
+ });
+ }
- break;
- }
- }
- }
+ if (attributes != null && product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
+ {
+ var combination = product.FindProductAttributeCombination(attributes);
+ if (combination != null)
+ {
+ if (quantityToChange < 0)
+ await ReserveInventoryCombination(product, combination, quantityToChange, warehouseId);
+ else
+ await UnblockReservedInventoryCombination(product, combination, quantityToChange, warehouseId);
//send email notification
- if (quantityToChange < 0 && _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId) < product.NotifyAdminForQuantityBelow)
- {
+ if (quantityToChange < 0 && combination.StockQuantity < combination.NotifyAdminForQuantityBelow)
await _mediator.Send(new SendQuantityBelowStoreOwnerCommand {
- Product = product
+ Product = product,
+ ProductAttributeCombination = combination
});
- }
- }
-
- if (attributes != null && product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
- {
- var combination = product.FindProductAttributeCombination(attributes);
- if (combination != null)
- {
- if (quantityToChange < 0)
- await ReserveInventoryCombination(product, combination, quantityToChange, warehouseId);
- else
- await UnblockReservedInventoryCombination(product, combination, quantityToChange, warehouseId);
-
- //send email notification
- if (quantityToChange < 0 && combination.StockQuantity < combination.NotifyAdminForQuantityBelow)
- {
- await _mediator.Send(new SendQuantityBelowStoreOwnerCommand {
- Product = product,
- ProductAttributeCombination = combination
- });
- }
- }
- }
-
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts)
- {
- foreach (var item in product.BundleProducts)
- {
- var p1 = await _productRepository.GetByIdAsync(item.ProductId);
- if (p1 is { ManageInventoryMethodId: ManageInventoryMethod.ManageStock or ManageInventoryMethod.ManageStockByAttributes })
- {
- await AdjustReserved(p1, quantityToChange * item.Quantity, attributes, warehouseId);
- }
- }
}
+ }
- //bundled products
- var attributeValues = product.ParseProductAttributeValues(attributes);
- foreach (var attributeValue in attributeValues)
+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts)
+ foreach (var item in product.BundleProducts)
{
- if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;
- //associated product (bundle)
- var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);
- if (associatedProduct != null)
- {
- await AdjustReserved(associatedProduct, quantityToChange * attributeValue.Quantity, null, warehouseId);
- }
+ var p1 = await _productRepository.GetByIdAsync(item.ProductId);
+ if (p1 is {
+ ManageInventoryMethodId: ManageInventoryMethod.ManageStock
+ or ManageInventoryMethod.ManageStockByAttributes
+ }) await AdjustReserved(p1, quantityToChange * item.Quantity, attributes, warehouseId);
}
- //event notification
- await _mediator.EntityUpdated(product);
- }
-
- /// <summary>
- /// Reserve the given quantity in the warehouses.
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="quantity">Quantity, must be negative</param>
- /// <param name="warehouseId"></param>
- protected virtual async Task ReserveInventory(Product product, int quantity, string warehouseId)
+ //bundled products
+ var attributeValues = product.ParseProductAttributeValues(attributes);
+ foreach (var attributeValue in attributeValues)
{
- ArgumentNullException.ThrowIfNull(product);
-
- if (quantity >= 0)
- throw new ArgumentException("Value must be negative.", nameof(quantity));
-
- var qty = -quantity;
+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct) continue;
+ //associated product (bundle)
+ var associatedProduct = await _productRepository.GetByIdAsync(attributeValue.AssociatedProductId);
+ if (associatedProduct != null)
+ await AdjustReserved(associatedProduct, quantityToChange * attributeValue.Quantity, null, warehouseId);
+ }
- if (!product.UseMultipleWarehouses)
- {
- product.ReservedQuantity += qty;
- await UpdateStockProduct(product);
- }
- else
- {
- var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null)
- return;
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- pwi.ReservedQuantity += qty;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ /// <summary>
+ /// Reserve the given quantity in the warehouses.
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="quantity">Quantity, must be negative</param>
+ /// <param name="warehouseId"></param>
+ protected virtual async Task ReserveInventory(Product product, int quantity, string warehouseId)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ if (quantity >= 0)
+ throw new ArgumentException("Value must be negative.", nameof(quantity));
- }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ var qty = -quantity;
- //event notification
- await _mediator.EntityUpdated(product);
+ if (!product.UseMultipleWarehouses)
+ {
+ product.ReservedQuantity += qty;
+ await UpdateStockProduct(product);
}
-
-
- /// <summary>
- /// Reserve the given quantity in the warehouses.
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="combination">Combination</param>
- /// <param name="quantity">Quantity, must be negative</param>
- /// <param name="warehouseId">Warehouse ident</param>
- protected virtual async Task ReserveInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId)
+ else
{
- ArgumentNullException.ThrowIfNull(product);
- ArgumentNullException.ThrowIfNull(combination);
+ var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null)
+ return;
- if (quantity >= 0)
- throw new ArgumentException("Value must be negative.", nameof(quantity));
+ pwi.ReservedQuantity += qty;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- var qty = -quantity;
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ }
- if (!product.UseMultipleWarehouses)
- {
- combination.ReservedQuantity += qty;
- if (combination.ReservedQuantity < 0)
- combination.ReservedQuantity = 0;
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- }
- else
- {
- var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null)
- return;
+ /// <summary>
+ /// Reserve the given quantity in the warehouses.
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="combination">Combination</param>
+ /// <param name="quantity">Quantity, must be negative</param>
+ /// <param name="warehouseId">Warehouse ident</param>
+ protected virtual async Task ReserveInventoryCombination(Product product, ProductAttributeCombination combination,
+ int quantity, string warehouseId)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+ ArgumentNullException.ThrowIfNull(combination);
- pwi.ReservedQuantity += qty;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ if (quantity >= 0)
+ throw new ArgumentException("Value must be negative.", nameof(quantity));
- combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
- combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
+ var qty = -quantity;
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ if (!product.UseMultipleWarehouses)
+ {
+ combination.ReservedQuantity += qty;
+ if (combination.ReservedQuantity < 0)
+ combination.ReservedQuantity = 0;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- //event notification
- await _mediator.EntityUpdated(product);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
-
- /// <summary>
- /// Unblocks the given quantity reserved items in the warehouses
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="quantity">Quantity, must be positive</param>
- /// <param name="warehouseId">Warehouse ident</param>
- protected virtual async Task UnblockReservedInventory(Product product, int quantity, string warehouseId)
+ else
{
- ArgumentNullException.ThrowIfNull(product);
-
- if (quantity < 0)
- throw new ArgumentException("Value must be positive.", nameof(quantity));
-
- var qty = quantity;
-
- if (!product.UseMultipleWarehouses)
- {
- product.ReservedQuantity -= qty;
- await UpdateStockProduct(product);
- }
- else
- {
- if (!product.ProductWarehouseInventory.Any())
- return;
-
- var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null)
- return;
+ var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null)
+ return;
- pwi.ReservedQuantity -= qty;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ pwi.ReservedQuantity += qty;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
+ combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
- }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- //event notification
- await _mediator.EntityUpdated(product);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
- /// <summary>
- /// Unblocks the given quantity reserved items in the warehouses
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="combination">Combination</param>
- /// <param name="quantity">Quantity, must be positive</param>
- /// <param name="warehouseId">Warehouse ident</param>
- protected virtual async Task UnblockReservedInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- if (quantity < 0)
- throw new ArgumentException("Value must be positive.", nameof(quantity));
-
- if (!product.UseMultipleWarehouses)
- {
- combination.ReservedQuantity -= quantity;
- if (combination.ReservedQuantity < 0)
- combination.ReservedQuantity = 0;
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ /// <summary>
+ /// Unblocks the given quantity reserved items in the warehouses
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="quantity">Quantity, must be positive</param>
+ /// <param name="warehouseId">Warehouse ident</param>
+ protected virtual async Task UnblockReservedInventory(Product product, int quantity, string warehouseId)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ if (quantity < 0)
+ throw new ArgumentException("Value must be positive.", nameof(quantity));
- }
- else
- {
- var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null)
- return;
+ var qty = quantity;
- pwi.ReservedQuantity -= quantity;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
-
- combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
+ if (!product.UseMultipleWarehouses)
+ {
+ product.ReservedQuantity -= qty;
+ await UpdateStockProduct(product);
+ }
+ else
+ {
+ if (!product.ProductWarehouseInventory.Any())
+ return;
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null)
+ return;
- }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ pwi.ReservedQuantity -= qty;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- //event notification
- await _mediator.EntityUpdated(product);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
- /// <summary>
- /// Book the reserved quantity
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="shipment">Shipment</param>
- /// <param name="shipmentItem">Shipment item</param>
- public virtual async Task BookReservedInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)
- {
- ArgumentNullException.ThrowIfNull(product);
- ArgumentNullException.ThrowIfNull(shipment);
- ArgumentNullException.ThrowIfNull(shipmentItem);
-
- //standard manage stock
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
- {
- await ManageStockInventory(product, shipmentItem);
- }
- //manage stock by attributes
- if (shipmentItem.Attributes != null && product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
- {
- await ManageStockByAttributesInventory(product, shipmentItem);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- //manage stock by bundle products
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts)
- {
- await ManageStockByBundleProductsInventory(product, shipment, shipmentItem);
- }
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- //check if exist associated products
- if (shipmentItem.Attributes != null && shipmentItem.Attributes.Any())
- {
- await ManageAttributesInventory(product, shipment, shipmentItem);
- }
+ /// <summary>
+ /// Unblocks the given quantity reserved items in the warehouses
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="combination">Combination</param>
+ /// <param name="quantity">Quantity, must be positive</param>
+ /// <param name="warehouseId">Warehouse ident</param>
+ protected virtual async Task UnblockReservedInventoryCombination(Product product,
+ ProductAttributeCombination combination, int quantity, string warehouseId)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ if (quantity < 0)
+ throw new ArgumentException("Value must be positive.", nameof(quantity));
- //event notification
- await _mediator.EntityUpdated(product);
+ if (!product.UseMultipleWarehouses)
+ {
+ combination.ReservedQuantity -= quantity;
+ if (combination.ReservedQuantity < 0)
+ combination.ReservedQuantity = 0;
- //insert inventory journal
- if (product.ManageInventoryMethodId is ManageInventoryMethod.ManageStock or ManageInventoryMethod.ManageStockByAttributes)
- await InsertInventoryJournal(product, shipment, shipmentItem);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
-
- /// <summary>
- /// Reverse booked inventory
- /// </summary>
- /// <param name="shipment">Shipment</param>
- /// <param name="shipmentItem">Shipment item</param>
- /// <returns>Quantity reversed</returns>
- public virtual async Task ReverseBookedInventory(Shipment shipment, ShipmentItem shipmentItem)
+ else
{
- ArgumentNullException.ThrowIfNull(shipment);
- ArgumentNullException.ThrowIfNull(shipmentItem);
+ var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null)
+ return;
- var inventoryJournals = _inventoryJournalRepository.Table.Where(j => j.PositionId == shipmentItem.Id);
+ pwi.ReservedQuantity -= quantity;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- foreach (var inventoryJournal in inventoryJournals)
- {
- var product = await _productRepository.GetByIdAsync(inventoryJournal.ProductId);
- if (product == null)
- continue;
+ combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
- await ReverseBookedInventory(product, inventoryJournal);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id,
+ combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- //event notification
- await _mediator.EntityUpdated(product);
- }
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- }
+ /// <summary>
+ /// Book the reserved quantity
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="shipment">Shipment</param>
+ /// <param name="shipmentItem">Shipment item</param>
+ public virtual async Task BookReservedInventory(Product product, Shipment shipment, ShipmentItem shipmentItem)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+ ArgumentNullException.ThrowIfNull(shipment);
+ ArgumentNullException.ThrowIfNull(shipmentItem);
+
+ //standard manage stock
+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
+ await ManageStockInventory(product, shipmentItem);
+ //manage stock by attributes
+ if (shipmentItem.Attributes != null &&
+ product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
+ await ManageStockByAttributesInventory(product, shipmentItem);
+
+ //manage stock by bundle products
+ if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts)
+ await ManageStockByBundleProductsInventory(product, shipment, shipmentItem);
+
+ //check if exist associated products
+ if (shipmentItem.Attributes != null && shipmentItem.Attributes.Any())
+ await ManageAttributesInventory(product, shipment, shipmentItem);
+
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+
+ //event notification
+ await _mediator.EntityUpdated(product);
+
+ //insert inventory journal
+ if (product.ManageInventoryMethodId is ManageInventoryMethod.ManageStock
+ or ManageInventoryMethod.ManageStockByAttributes)
+ await InsertInventoryJournal(product, shipment, shipmentItem);
+ }
+
+ /// <summary>
+ /// Reverse booked inventory
+ /// </summary>
+ /// <param name="shipment">Shipment</param>
+ /// <param name="shipmentItem">Shipment item</param>
+ /// <returns>Quantity reversed</returns>
+ public virtual async Task ReverseBookedInventory(Shipment shipment, ShipmentItem shipmentItem)
+ {
+ ArgumentNullException.ThrowIfNull(shipment);
+ ArgumentNullException.ThrowIfNull(shipmentItem);
+ var inventoryJournals = _inventoryJournalRepository.Table.Where(j => j.PositionId == shipmentItem.Id);
- public virtual async Task UpdateStockProduct(Product product, bool mediator = true)
+ foreach (var inventoryJournal in inventoryJournals)
{
- ArgumentNullException.ThrowIfNull(product);
-
- if (product.ReservedQuantity < 0)
- product.ReservedQuantity = 0;
-
- //update
- await _productRepository.UpdateField(product.Id, x => x.StockQuantity, product.StockQuantity);
- await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
- await _productRepository.UpdateField(product.Id, x => x.LowStock, (product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ var product = await _productRepository.GetByIdAsync(inventoryJournal.ProductId);
+ if (product == null)
+ continue;
+ await ReverseBookedInventory(product, inventoryJournal);
//cache
await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- //event notification
- if (mediator)
- await _mediator.Publish(new UpdateStockEvent(product));
-
//event notification
await _mediator.EntityUpdated(product);
}
+ }
+
+
+ public virtual async Task UpdateStockProduct(Product product, bool mediator = true)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+ if (product.ReservedQuantity < 0)
+ product.ReservedQuantity = 0;
- #endregion
+ //update
+ await _productRepository.UpdateField(product.Id, x => x.StockQuantity, product.StockQuantity);
+ await _productRepository.UpdateField(product.Id, x => x.ReservedQuantity, product.ReservedQuantity);
+ await _productRepository.UpdateField(product.Id, x => x.LowStock,
+ (product.MinStockQuantity > 0 &&
+ product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) ||
+ product.StockQuantity - product.ReservedQuantity <= 0);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+
+
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+
+ //event notification
+ if (mediator)
+ await _mediator.Publish(new UpdateStockEvent(product));
+
+ //event notification
+ await _mediator.EntityUpdated(product);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs
index 05fbe65bd..0614a1a46 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs
@@ -1,188 +1,188 @@
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
-using Grand.Data;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Out of stock subscription service
+/// </summary>
+public class OutOfStockSubscriptionService : IOutOfStockSubscriptionService
{
+ #region Ctor
+
/// <summary>
- /// Out of stock subscription service
+ /// Ctor
/// </summary>
- public class OutOfStockSubscriptionService : IOutOfStockSubscriptionService
+ public OutOfStockSubscriptionService(IRepository<OutOfStockSubscription> outOfStockSubscriptionRepository,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<OutOfStockSubscription> _outOfStockSubscriptionRepository;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public OutOfStockSubscriptionService(IRepository<OutOfStockSubscription> outOfStockSubscriptionRepository,
- IMediator mediator)
- {
- _outOfStockSubscriptionRepository = outOfStockSubscriptionRepository;
- _mediator = mediator;
- }
-
- #endregion
-
- #region Methods
-
-
- /// <summary>
- /// Gets all subscriptions
- /// </summary>
- /// <param name="customerId">Customer identifier</param>
- /// <param name="storeId">Store identifier; pass "" to load all records</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Subscriptions</returns>
- public virtual async Task<IPagedList<OutOfStockSubscription>> GetAllSubscriptionsByCustomerId(string customerId,
- string storeId = "", int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _outOfStockSubscriptionRepository.Table
- select p;
- //customer
- query = query.Where(x => x.CustomerId == customerId);
- //store
- if (!string.IsNullOrEmpty(storeId))
- query = query.Where(x => x.StoreId == storeId);
-
- query = query.OrderByDescending(x => x.CreatedOnUtc);
-
- return await PagedList<OutOfStockSubscription>.Create(query, pageIndex, pageSize);
- }
-
-
-
- /// <summary>
- /// Gets all subscriptions
- /// </summary>
- /// <param name="customerId">Customer id</param>
- /// <param name="productId">Product identifier</param>
- /// <param name="attributes">Attributes</param>
- /// <param name="storeId">Store identifier</param>
- /// <param name="warehouseId">Warehouse identifier</param>
- /// <returns>Subscriptions</returns>
- public virtual async Task<OutOfStockSubscription> FindSubscription(string customerId, string productId, IList<CustomAttribute> attributes, string storeId, string warehouseId)
- {
- var query = from biss in _outOfStockSubscriptionRepository.Table
- orderby biss.CreatedOnUtc descending
- where biss.CustomerId == customerId &&
- biss.ProductId == productId &&
- biss.StoreId == storeId &&
- biss.WarehouseId == warehouseId
- select biss;
-
- var outOfStockSubscriptionlist = await Task.FromResult(query.ToList());
- if (attributes != null && attributes.Any())
- outOfStockSubscriptionlist = outOfStockSubscriptionlist.Where(x => x.Attributes.All(y => attributes.Any(z => z.Key == y.Key && z.Value == y.Value))).ToList();
-
- return outOfStockSubscriptionlist.FirstOrDefault();
- }
-
- /// <summary>
- /// Gets a subscription
- /// </summary>
- /// <param name="subscriptionId">Subscription identifier</param>
- /// <returns>Subscription</returns>
- public virtual async Task<OutOfStockSubscription> GetSubscriptionById(string subscriptionId)
- {
- var subscription = await _outOfStockSubscriptionRepository.GetByIdAsync(subscriptionId);
- return subscription;
- }
-
- /// <summary>
- /// Inserts subscription
- /// </summary>
- /// <param name="subscription">Subscription</param>
- public virtual async Task InsertSubscription(OutOfStockSubscription subscription)
- {
- ArgumentNullException.ThrowIfNull(subscription);
-
- await _outOfStockSubscriptionRepository.InsertAsync(subscription);
-
- //event notification
- await _mediator.EntityInserted(subscription);
- }
-
- /// <summary>
- /// Updates subscription
- /// </summary>
- /// <param name="subscription">Subscription</param>
- public virtual async Task UpdateSubscription(OutOfStockSubscription subscription)
- {
- ArgumentNullException.ThrowIfNull(subscription);
-
- await _outOfStockSubscriptionRepository.UpdateAsync(subscription);
-
- //event notification
- await _mediator.EntityUpdated(subscription);
- }
- /// <summary>
- /// Delete a out of stock subscription
- /// </summary>
- /// <param name="subscription">Subscription</param>
- public virtual async Task DeleteSubscription(OutOfStockSubscription subscription)
- {
- ArgumentNullException.ThrowIfNull(subscription);
-
- await _outOfStockSubscriptionRepository.DeleteAsync(subscription);
-
- //event notification
- await _mediator.EntityDeleted(subscription);
- }
-
- /// <summary>
- /// Send notification to subscribers
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="warehouse">Warehouse ident</param>
- /// <returns>Number of sent email</returns>
- public virtual async Task SendNotificationsToSubscribers(Product product, string warehouse)
- {
- ArgumentNullException.ThrowIfNull(product);
-
- var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand {
- Product = product,
- Warehouse = warehouse
- });
-
- for (var i = 0; i <= subscriptions.Count - 1; i++)
- await DeleteSubscription(subscriptions[i]);
- }
-
- /// <summary>
- /// Send notification to subscribers
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="attributes">Attribute</param>
- /// <param name="warehouse">Warehouse ident</param>
- /// <returns>Number of sent email</returns>
- public virtual async Task SendNotificationsToSubscribers(Product product, IList<CustomAttribute> attributes, string warehouse)
- {
- ArgumentNullException.ThrowIfNull(product);
-
- var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand {
- Product = product,
- Warehouse = warehouse,
- Attributes = attributes
- });
-
- for (var i = 0; i <= subscriptions.Count - 1; i++)
- await DeleteSubscription(subscriptions[i]);
-
- }
-
- #endregion
+ _outOfStockSubscriptionRepository = outOfStockSubscriptionRepository;
+ _mediator = mediator;
}
-}
+
+ #endregion
+
+ #region Fields
+
+ private readonly IRepository<OutOfStockSubscription> _outOfStockSubscriptionRepository;
+ private readonly IMediator _mediator;
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets all subscriptions
+ /// </summary>
+ /// <param name="customerId">Customer identifier</param>
+ /// <param name="storeId">Store identifier; pass "" to load all records</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Subscriptions</returns>
+ public virtual async Task<IPagedList<OutOfStockSubscription>> GetAllSubscriptionsByCustomerId(string customerId,
+ string storeId = "", int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = from p in _outOfStockSubscriptionRepository.Table
+ select p;
+ //customer
+ query = query.Where(x => x.CustomerId == customerId);
+ //store
+ if (!string.IsNullOrEmpty(storeId))
+ query = query.Where(x => x.StoreId == storeId);
+
+ query = query.OrderByDescending(x => x.CreatedOnUtc);
+
+ return await PagedList<OutOfStockSubscription>.Create(query, pageIndex, pageSize);
+ }
+
+
+ /// <summary>
+ /// Gets all subscriptions
+ /// </summary>
+ /// <param name="customerId">Customer id</param>
+ /// <param name="productId">Product identifier</param>
+ /// <param name="attributes">Attributes</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <param name="warehouseId">Warehouse identifier</param>
+ /// <returns>Subscriptions</returns>
+ public virtual async Task<OutOfStockSubscription> FindSubscription(string customerId, string productId,
+ IList<CustomAttribute> attributes, string storeId, string warehouseId)
+ {
+ var query = from biss in _outOfStockSubscriptionRepository.Table
+ orderby biss.CreatedOnUtc descending
+ where biss.CustomerId == customerId &&
+ biss.ProductId == productId &&
+ biss.StoreId == storeId &&
+ biss.WarehouseId == warehouseId
+ select biss;
+
+ var outOfStockSubscriptionlist = await Task.FromResult(query.ToList());
+ if (attributes != null && attributes.Any())
+ outOfStockSubscriptionlist = outOfStockSubscriptionlist.Where(x =>
+ x.Attributes.All(y => attributes.Any(z => z.Key == y.Key && z.Value == y.Value))).ToList();
+
+ return outOfStockSubscriptionlist.FirstOrDefault();
+ }
+
+ /// <summary>
+ /// Gets a subscription
+ /// </summary>
+ /// <param name="subscriptionId">Subscription identifier</param>
+ /// <returns>Subscription</returns>
+ public virtual async Task<OutOfStockSubscription> GetSubscriptionById(string subscriptionId)
+ {
+ var subscription = await _outOfStockSubscriptionRepository.GetByIdAsync(subscriptionId);
+ return subscription;
+ }
+
+ /// <summary>
+ /// Inserts subscription
+ /// </summary>
+ /// <param name="subscription">Subscription</param>
+ public virtual async Task InsertSubscription(OutOfStockSubscription subscription)
+ {
+ ArgumentNullException.ThrowIfNull(subscription);
+
+ await _outOfStockSubscriptionRepository.InsertAsync(subscription);
+
+ //event notification
+ await _mediator.EntityInserted(subscription);
+ }
+
+ /// <summary>
+ /// Updates subscription
+ /// </summary>
+ /// <param name="subscription">Subscription</param>
+ public virtual async Task UpdateSubscription(OutOfStockSubscription subscription)
+ {
+ ArgumentNullException.ThrowIfNull(subscription);
+
+ await _outOfStockSubscriptionRepository.UpdateAsync(subscription);
+
+ //event notification
+ await _mediator.EntityUpdated(subscription);
+ }
+
+ /// <summary>
+ /// Delete a out of stock subscription
+ /// </summary>
+ /// <param name="subscription">Subscription</param>
+ public virtual async Task DeleteSubscription(OutOfStockSubscription subscription)
+ {
+ ArgumentNullException.ThrowIfNull(subscription);
+
+ await _outOfStockSubscriptionRepository.DeleteAsync(subscription);
+
+ //event notification
+ await _mediator.EntityDeleted(subscription);
+ }
+
+ /// <summary>
+ /// Send notification to subscribers
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="warehouse">Warehouse ident</param>
+ /// <returns>Number of sent email</returns>
+ public virtual async Task SendNotificationsToSubscribers(Product product, string warehouse)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+
+ var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand {
+ Product = product,
+ Warehouse = warehouse
+ });
+
+ for (var i = 0; i <= subscriptions.Count - 1; i++)
+ await DeleteSubscription(subscriptions[i]);
+ }
+
+ /// <summary>
+ /// Send notification to subscribers
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="attributes">Attribute</param>
+ /// <param name="warehouse">Warehouse ident</param>
+ /// <returns>Number of sent email</returns>
+ public virtual async Task SendNotificationsToSubscribers(Product product, IList<CustomAttribute> attributes,
+ string warehouse)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+
+ var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand {
+ Product = product,
+ Warehouse = warehouse,
+ Attributes = attributes
+ });
+
+ for (var i = 0; i <= subscriptions.Count - 1; i++)
+ await DeleteSubscription(subscriptions[i]);
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
index aec76fc07..a103dcb20 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
@@ -10,267 +10,271 @@ using Grand.Infrastructure;
using Grand.SharedKernel.Extensions;
using System.Net;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product attribute formatter
+/// </summary>
+public class ProductAttributeFormatter : IProductAttributeFormatter
{
+ private readonly IPriceFormatter _priceFormatter;
+ private readonly IPricingService _pricingService;
+ private readonly IProductAttributeService _productAttributeService;
+ private readonly IProductService _productService;
+ private readonly ITaxService _taxService;
+ private readonly IWorkContext _workContext;
+
+ public ProductAttributeFormatter(IWorkContext workContext,
+ IProductAttributeService productAttributeService,
+ ITaxService taxService,
+ IPriceFormatter priceFormatter,
+ IPricingService priceCalculationService,
+ IProductService productService)
+ {
+ _workContext = workContext;
+ _productAttributeService = productAttributeService;
+ _taxService = taxService;
+ _priceFormatter = priceFormatter;
+ _pricingService = priceCalculationService;
+ _productService = productService;
+ }
+
/// <summary>
- /// Product attribute formatter
+ /// Formats attributes
/// </summary>
- public class ProductAttributeFormatter : IProductAttributeFormatter
+ /// <param name="product">Product</param>
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Attributes</returns>
+ public virtual Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes)
{
- private readonly IWorkContext _workContext;
- private readonly IProductAttributeService _productAttributeService;
- private readonly ITaxService _taxService;
- private readonly IPriceFormatter _priceFormatter;
- private readonly IPricingService _pricingService;
- private readonly IProductService _productService;
-
- public ProductAttributeFormatter(IWorkContext workContext,
- IProductAttributeService productAttributeService,
- ITaxService taxService,
- IPriceFormatter priceFormatter,
- IPricingService priceCalculationService,
- IProductService productService)
- {
- _workContext = workContext;
- _productAttributeService = productAttributeService;
- _taxService = taxService;
- _priceFormatter = priceFormatter;
- _pricingService = priceCalculationService;
- _productService = productService;
- }
-
- /// <summary>
- /// Formats attributes
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Attributes</returns>
- public virtual Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes)
- {
- var customer = _workContext.CurrentCustomer;
- return FormatAttributes(product, customAttributes, customer);
- }
+ var customer = _workContext.CurrentCustomer;
+ return FormatAttributes(product, customAttributes, customer);
+ }
- /// <summary>
- /// Formats attributes
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customAttributes">Attributes</param>
- /// <param name="customer">Customer</param>
- /// <param name="separator">Separator</param>
- /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
- /// <param name="renderPrices">A value indicating whether to render prices</param>
- /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
- /// <param name="renderGiftVoucherAttributes">A value indicating whether to render gift voucher attributes</param>
- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>
- /// <param name="showInAdmin">Show in admin</param>
- /// <returns>Attributes</returns>
- public virtual async Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes,
- Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true,
- bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true,
- bool allowHyperlinks = true, bool showInAdmin = false)
- {
+ /// <summary>
+ /// Formats attributes
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customAttributes">Attributes</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="separator">Separator</param>
+ /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
+ /// <param name="renderPrices">A value indicating whether to render prices</param>
+ /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
+ /// <param name="renderGiftVoucherAttributes">A value indicating whether to render gift voucher attributes</param>
+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>
+ /// <param name="showInAdmin">Show in admin</param>
+ /// <returns>Attributes</returns>
+ public virtual async Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes,
+ Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true,
+ bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true,
+ bool allowHyperlinks = true, bool showInAdmin = false)
+ {
+ var result = new StringBuilder();
- var result = new StringBuilder();
+ if (customAttributes == null || !customAttributes.Any())
+ return result.ToString();
- if (customAttributes == null || !customAttributes.Any())
- return result.ToString();
+ var langId = _workContext.WorkingLanguage != null
+ ? _workContext.WorkingLanguage.Id
+ : customer?.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);
- var langId = _workContext.WorkingLanguage != null ? _workContext.WorkingLanguage.Id : customer?.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);
+ if (string.IsNullOrEmpty(langId))
+ langId = "";
- if (string.IsNullOrEmpty(langId))
- langId = "";
+ //attributes
+ if (renderProductAttributes)
+ {
+ result = await PrepareFormattedAttribute(product, customAttributes, langId, separator, htmlEncode,
+ renderPrices, allowHyperlinks, showInAdmin);
- //attributes
- if (renderProductAttributes)
+ if (product.ProductTypeId == ProductType.BundledProduct)
{
- result = await PrepareFormattedAttribute(product, customAttributes, langId, separator, htmlEncode,
- renderPrices, allowHyperlinks, showInAdmin);
-
- if (product.ProductTypeId == ProductType.BundledProduct)
+ var i = 0;
+ if (result.Length > 0) result.Append(separator);
+ foreach (var bundle in product.BundleProducts)
{
- var i = 0;
- if (result.Length > 0)
+ var p1 = await _productService.GetProductById(bundle.ProductId);
+ if (p1 == null) continue;
+ if (i > 0)
+ result.Append(separator);
+
+ if (p1.VisibleIndividually)
+ result.Append(
+ $"<a href=\"{p1.GetSeName(langId)}\"> {(htmlEncode ? WebUtility.HtmlEncode(p1.GetTranslation(x => x.Name, langId)) : p1.GetTranslation(x => x.Name, langId))} </a>");
+ else
+ result.Append(
+ $"{(htmlEncode ? WebUtility.HtmlEncode(p1.GetTranslation(x => x.Name, langId)) : p1.GetTranslation(x => x.Name, langId))}");
+ var formattedAttribute = await PrepareFormattedAttribute(p1, customAttributes, langId, separator,
+ htmlEncode,
+ renderPrices, allowHyperlinks, showInAdmin);
+ if (formattedAttribute.Length > 0)
{
result.Append(separator);
+ result.Append(formattedAttribute);
}
- foreach (var bundle in product.BundleProducts)
- {
- var p1 = await _productService.GetProductById(bundle.ProductId);
- if (p1 == null) continue;
- if (i > 0)
- result.Append(separator);
- if (p1.VisibleIndividually)
- {
- result.Append($"<a href=\"{p1.GetSeName(langId)}\"> {(htmlEncode ? WebUtility.HtmlEncode(p1.GetTranslation(x => x.Name, langId)) : p1.GetTranslation(x => x.Name, langId))} </a>");
- }
- else
- {
- result.Append($"{(htmlEncode ? WebUtility.HtmlEncode(p1.GetTranslation(x => x.Name, langId)) : p1.GetTranslation(x => x.Name, langId))}");
- }
- var formattedAttribute = await PrepareFormattedAttribute(p1, customAttributes, langId, separator, htmlEncode,
- renderPrices, allowHyperlinks, showInAdmin);
- if (formattedAttribute.Length > 0)
- {
- result.Append(separator);
- result.Append(formattedAttribute);
- }
- i++;
- }
+ i++;
}
-
}
+ }
- //gift vouchers
- if (!renderGiftVoucherAttributes) return result.ToString();
- if (!product.IsGiftVoucher) return result.ToString();
- GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,
- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);
-
- //sender
- var giftVoucherFrom = product.GiftVoucherTypeId == GiftVoucherType.Virtual
- ? $"{giftVoucherSenderName} <{giftVoucherSenderEmail}>" : $"{giftVoucherSenderName}";
- //recipient
- var giftVoucherFor = product.GiftVoucherTypeId == GiftVoucherType.Virtual
- ? $"{giftVoucherRecipientName} <{giftVoucherRecipientEmail}>" : $"{giftVoucherRecipientName}";
+ //gift vouchers
+ if (!renderGiftVoucherAttributes) return result.ToString();
+ if (!product.IsGiftVoucher) return result.ToString();
+ GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName,
+ out var giftVoucherRecipientEmail,
+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);
- //encode (if required)
- if (htmlEncode)
- {
- giftVoucherFrom = WebUtility.HtmlEncode(giftVoucherFrom);
- giftVoucherFor = WebUtility.HtmlEncode(giftVoucherFor);
- }
+ //sender
+ var giftVoucherFrom = product.GiftVoucherTypeId == GiftVoucherType.Virtual
+ ? $"{giftVoucherSenderName} <{giftVoucherSenderEmail}>"
+ : $"{giftVoucherSenderName}";
+ //recipient
+ var giftVoucherFor = product.GiftVoucherTypeId == GiftVoucherType.Virtual
+ ? $"{giftVoucherRecipientName} <{giftVoucherRecipientEmail}>"
+ : $"{giftVoucherRecipientName}";
- if (!string.IsNullOrEmpty(result.ToString()))
- {
- result.Append(separator);
- }
- result.Append(giftVoucherFrom);
- result.Append(separator);
- result.Append(giftVoucherFor);
- return result.ToString();
+ //encode (if required)
+ if (htmlEncode)
+ {
+ giftVoucherFrom = WebUtility.HtmlEncode(giftVoucherFrom);
+ giftVoucherFor = WebUtility.HtmlEncode(giftVoucherFor);
}
- private async Task<StringBuilder> PrepareFormattedAttribute(Product product, IList<CustomAttribute> customAttributes, string langId,
- string separator, bool htmlEncode, bool renderPrices,
- bool allowHyperlinks, bool showInAdmin)
+ if (!string.IsNullOrEmpty(result.ToString())) result.Append(separator);
+ result.Append(giftVoucherFrom);
+ result.Append(separator);
+ result.Append(giftVoucherFor);
+ return result.ToString();
+ }
+
+ private async Task<StringBuilder> PrepareFormattedAttribute(Product product,
+ IList<CustomAttribute> customAttributes, string langId,
+ string separator, bool htmlEncode, bool renderPrices,
+ bool allowHyperlinks, bool showInAdmin)
+ {
+ var result = new StringBuilder();
+ var attributes = product.ParseProductAttributeMappings(customAttributes);
+ for (var i = 0; i < attributes.Count; i++)
{
- var result = new StringBuilder();
- var attributes = product.ParseProductAttributeMappings(customAttributes);
- for (var i = 0; i < attributes.Count; i++)
- {
- var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);
- if (productAttribute == null)
- continue;
+ var productAttribute =
+ await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);
+ if (productAttribute == null)
+ continue;
- var attribute = attributes[i];
- var valuesStr = ProductExtensions.ParseValues(customAttributes, attribute.Id);
- for (var j = 0; j < valuesStr.Count; j++)
+ var attribute = attributes[i];
+ var valuesStr = ProductExtensions.ParseValues(customAttributes, attribute.Id);
+ for (var j = 0; j < valuesStr.Count; j++)
+ {
+ var valueStr = valuesStr[j];
+ var formattedAttribute = string.Empty;
+ if (!attribute.ShouldHaveValues())
{
- var valueStr = valuesStr[j];
- var formattedAttribute = string.Empty;
- if (!attribute.ShouldHaveValues())
+ switch (attribute.AttributeControlTypeId)
{
- switch (attribute.AttributeControlTypeId)
+ //no values
+ case AttributeControlType.MultilineTextbox:
{
- //no values
- case AttributeControlType.MultilineTextbox:
+ //multiline text
+ var attributeName = productAttribute.GetTranslation(a => a.Name, langId);
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ //we never encode multiline text box input
+ break;
+ }
+ case AttributeControlType.FileUpload:
+ {
+ //file upload
+ if (Guid.TryParse(valueStr, out var downloadGuid))
{
- //multiline text
+ var attributeText = string.Empty;
var attributeName = productAttribute.GetTranslation(a => a.Name, langId);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- //we never encode multiline text box input
- break;
- }
- case AttributeControlType.FileUpload:
- {
- //file upload
- if (Guid.TryParse(valueStr, out var downloadGuid))
+ if (allowHyperlinks)
{
- var attributeText = string.Empty;
- var attributeName = productAttribute.GetTranslation(a => a.Name, langId);
- if (allowHyperlinks)
- {
- var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
- attributeText =
- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, langId)}</a>";
- }
- formattedAttribute = $"{attributeName}: {attributeText}";
+ var downloadLink =
+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ attributeText =
+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, langId)}</a>";
}
- break;
- }
- default:
- {
- //other attributes (text box, datepicker)
- formattedAttribute =
- $"{productAttribute.GetTranslation(a => a.Name, langId)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
- break;
+ formattedAttribute = $"{attributeName}: {attributeText}";
}
+
+ break;
+ }
+ default:
+ {
+ //other attributes (text box, datepicker)
+ formattedAttribute =
+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
}
}
- else
+ }
+ else
+ {
+ //attributes with values
+ if (product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id) != null)
{
- //attributes with values
- if (product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id) != null)
+ var attributeValue = product.ProductAttributeMappings
+ .FirstOrDefault(x => x.Id == attributes[i].Id).ProductAttributeValues
+ .FirstOrDefault(x => x.Id == valueStr);
+ if (attributeValue != null)
{
+ formattedAttribute =
+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: {attributeValue.GetTranslation(a => a.Name, langId)}";
- var attributeValue = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id).ProductAttributeValues.FirstOrDefault(x => x.Id == valueStr);
- if (attributeValue != null)
+ if (renderPrices)
{
- formattedAttribute =
- $"{productAttribute.GetTranslation(a => a.Name, langId)}: {attributeValue.GetTranslation(a => a.Name, langId)}";
-
- if (renderPrices)
+ var attributeValuePriceAdjustment =
+ await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);
+ var (priceAdjustmentBase, _) = await _taxService.GetProductPrice(product,
+ attributeValuePriceAdjustment, _workContext.CurrentCustomer);
+ switch (priceAdjustmentBase)
{
- var attributeValuePriceAdjustment = await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);
- var (priceAdjustmentBase, _) = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);
- switch (priceAdjustmentBase)
+ case > 0:
+ {
+ var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase,
+ _workContext.WorkingCurrency);
+ formattedAttribute += $" [+{priceAdjustmentStr}]";
+ break;
+ }
+ case < 0:
{
- case > 0:
- {
- var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase, _workContext.WorkingCurrency);
- formattedAttribute += $" [+{priceAdjustmentStr}]";
- break;
- }
- case < 0:
- {
- var priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase, _workContext.WorkingCurrency);
- formattedAttribute += $" [-{priceAdjustmentStr}]";
- break;
- }
+ var priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase,
+ _workContext.WorkingCurrency);
+ formattedAttribute += $" [-{priceAdjustmentStr}]";
+ break;
}
}
-
- }
- else
- {
- if (showInAdmin)
- formattedAttribute +=
- $"{productAttribute.GetTranslation(a => a.Name, langId)}: ";
}
-
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
}
- }
+ else
+ {
+ if (showInAdmin)
+ formattedAttribute +=
+ $"{productAttribute.GetTranslation(a => a.Name, langId)}: ";
+ }
- if (string.IsNullOrEmpty(formattedAttribute)) continue;
- if (i != 0 || j != 0)
- result.Append(separator);
- result.Append(formattedAttribute);
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ }
}
+
+ if (string.IsNullOrEmpty(formattedAttribute)) continue;
+ if (i != 0 || j != 0)
+ result.Append(separator);
+ result.Append(formattedAttribute);
}
- return result;
}
+
+ return result;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs
index 087bebee6..7378fcce6 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs
@@ -1,368 +1,383 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
+using Grand.Domain;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain;
-using Grand.Domain.Catalog;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product attribute service
+/// </summary>
+public class ProductAttributeService : IProductAttributeService
{
+ #region Ctor
+
/// <summary>
- /// Product attribute service
+ /// Ctor
/// </summary>
- public class ProductAttributeService : IProductAttributeService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="productAttributeRepository">Product attribute repository</param>
+ /// <param name="productRepository">Product repository</param>
+ /// <param name="mediator">Mediator</param>
+ public ProductAttributeService(ICacheBase cacheBase,
+ IRepository<ProductAttribute> productAttributeRepository,
+ IRepository<Product> productRepository,
+ IMediator mediator)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _productAttributeRepository = productAttributeRepository;
+ _productRepository = productRepository;
+ _mediator = mediator;
+ }
- private readonly IRepository<ProductAttribute> _productAttributeRepository;
- private readonly IRepository<Product> _productRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ #endregion
+ #region Fields
- #endregion
+ private readonly IRepository<ProductAttribute> _productAttributeRepository;
+ private readonly IRepository<Product> _productRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- #region Ctor
+ #endregion
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="productAttributeRepository">Product attribute repository</param>
- /// <param name="productRepository">Product repository</param>
- /// <param name="mediator">Mediator</param>
- public ProductAttributeService(ICacheBase cacheBase,
- IRepository<ProductAttribute> productAttributeRepository,
- IRepository<Product> productRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _productAttributeRepository = productAttributeRepository;
- _productRepository = productRepository;
- _mediator = mediator;
- }
+ #region Methods
- #endregion
+ #region Product attributes
- #region Methods
-
- #region Product attributes
-
- /// <summary>
- /// Gets all product attributes
- /// </summary>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Product attributes</returns>
- public virtual async Task<IPagedList<ProductAttribute>> GetAllProductAttributes(int pageIndex = 0, int pageSize = int.MaxValue)
+ /// <summary>
+ /// Gets all product attributes
+ /// </summary>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Product attributes</returns>
+ public virtual async Task<IPagedList<ProductAttribute>> GetAllProductAttributes(int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var key = string.Format(CacheKey.PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize);
+ return await _cacheBase.GetAsync(key, () =>
{
- var key = string.Format(CacheKey.PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize);
- return await _cacheBase.GetAsync(key, () =>
- {
- var query = from pa in _productAttributeRepository.Table
- orderby pa.Name
- select pa;
- return Task.FromResult(new PagedList<ProductAttribute>(query, pageIndex, pageSize));
- });
- }
+ var query = from pa in _productAttributeRepository.Table
+ orderby pa.Name
+ select pa;
+ return Task.FromResult(new PagedList<ProductAttribute>(query, pageIndex, pageSize));
+ });
+ }
- /// <summary>
- /// Gets a product attribute
- /// </summary>
- /// <param name="productAttributeId">Product attribute identifier</param>
- /// <returns>Product attribute </returns>
- public virtual Task<ProductAttribute> GetProductAttributeById(string productAttributeId)
- {
- var key = string.Format(CacheKey.PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId);
- return _cacheBase.GetAsync(key, () => _productAttributeRepository.GetByIdAsync(productAttributeId));
- }
+ /// <summary>
+ /// Gets a product attribute
+ /// </summary>
+ /// <param name="productAttributeId">Product attribute identifier</param>
+ /// <returns>Product attribute </returns>
+ public virtual Task<ProductAttribute> GetProductAttributeById(string productAttributeId)
+ {
+ var key = string.Format(CacheKey.PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId);
+ return _cacheBase.GetAsync(key, () => _productAttributeRepository.GetByIdAsync(productAttributeId));
+ }
- /// <summary>
- /// Inserts a product attribute
- /// </summary>
- /// <param name="productAttribute">Product attribute</param>
- public virtual async Task InsertProductAttribute(ProductAttribute productAttribute)
- {
- ArgumentNullException.ThrowIfNull(productAttribute);
+ /// <summary>
+ /// Inserts a product attribute
+ /// </summary>
+ /// <param name="productAttribute">Product attribute</param>
+ public virtual async Task InsertProductAttribute(ProductAttribute productAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(productAttribute);
- await _productAttributeRepository.InsertAsync(productAttribute);
+ await _productAttributeRepository.InsertAsync(productAttribute);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
- //event notification
- await _mediator.EntityInserted(productAttribute);
- }
+ //event notification
+ await _mediator.EntityInserted(productAttribute);
+ }
- /// <summary>
- /// Updates the product attribute
- /// </summary>
- /// <param name="productAttribute">Product attribute</param>
- public virtual async Task UpdateProductAttribute(ProductAttribute productAttribute)
- {
- ArgumentNullException.ThrowIfNull(productAttribute);
+ /// <summary>
+ /// Updates the product attribute
+ /// </summary>
+ /// <param name="productAttribute">Product attribute</param>
+ public virtual async Task UpdateProductAttribute(ProductAttribute productAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(productAttribute);
- await _productAttributeRepository.UpdateAsync(productAttribute);
+ await _productAttributeRepository.UpdateAsync(productAttribute);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
- //event notification
- await _mediator.EntityUpdated(productAttribute);
- }
+ //event notification
+ await _mediator.EntityUpdated(productAttribute);
+ }
- /// <summary>
- /// Deletes a product attribute
- /// </summary>
- /// <param name="productAttribute">Product attribute</param>
- public virtual async Task DeleteProductAttribute(ProductAttribute productAttribute)
- {
- ArgumentNullException.ThrowIfNull(productAttribute);
+ /// <summary>
+ /// Deletes a product attribute
+ /// </summary>
+ /// <param name="productAttribute">Product attribute</param>
+ public virtual async Task DeleteProductAttribute(ProductAttribute productAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(productAttribute);
- //delete from all product collections
- await _productRepository.PullFilter(string.Empty, x => x.ProductAttributeMappings, z => z.ProductAttributeId, productAttribute.Id);
+ //delete from all product collections
+ await _productRepository.PullFilter(string.Empty, x => x.ProductAttributeMappings, z => z.ProductAttributeId,
+ productAttribute.Id);
- //delete from productAttribute collection
- await _productAttributeRepository.DeleteAsync(productAttribute);
+ //delete from productAttribute collection
+ await _productAttributeRepository.DeleteAsync(productAttribute);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTEVALUES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(productAttribute);
- }
+ //event notification
+ await _mediator.EntityDeleted(productAttribute);
+ }
- #endregion
+ #endregion
- #region Product attributes mappings
+ #region Product attributes mappings
- /// <summary>
- /// Deletes a product attribute mapping
- /// </summary>
- /// <param name="productAttributeMapping">Product attribute mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId)
- {
- ArgumentNullException.ThrowIfNull(productAttributeMapping);
+ /// <summary>
+ /// Deletes a product attribute mapping
+ /// </summary>
+ /// <param name="productAttributeMapping">Product attribute mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductAttributeMapping(ProductAttributeMapping productAttributeMapping,
+ string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeMapping);
- await _productRepository.PullFilter(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMapping.Id);
+ await _productRepository.PullFilter(productId, x => x.ProductAttributeMappings, z => z.Id,
+ productAttributeMapping.Id);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityDeleted(productAttributeMapping);
- }
+ //event notification
+ await _mediator.EntityDeleted(productAttributeMapping);
+ }
- /// <summary>
- /// Inserts a product attribute mapping
- /// </summary>
- /// <param name="productAttributeMapping">The product attribute mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId)
- {
- ArgumentNullException.ThrowIfNull(productAttributeMapping);
+ /// <summary>
+ /// Inserts a product attribute mapping
+ /// </summary>
+ /// <param name="productAttributeMapping">The product attribute mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductAttributeMapping(ProductAttributeMapping productAttributeMapping,
+ string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeMapping);
- await _productRepository.AddToSet(productId, x => x.ProductAttributeMappings, productAttributeMapping);
+ await _productRepository.AddToSet(productId, x => x.ProductAttributeMappings, productAttributeMapping);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityInserted(productAttributeMapping);
- }
+ //event notification
+ await _mediator.EntityInserted(productAttributeMapping);
+ }
- /// <summary>
- /// Updates the product attribute mapping
- /// </summary>
- /// <param name="productAttributeMapping">The product attribute mapping</param>
- /// <param name="productId">Product ident</param>
- /// <param name="values">Update values</param>
- public virtual async Task UpdateProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId, bool values = false)
- {
- ArgumentNullException.ThrowIfNull(productAttributeMapping);
+ /// <summary>
+ /// Updates the product attribute mapping
+ /// </summary>
+ /// <param name="productAttributeMapping">The product attribute mapping</param>
+ /// <param name="productId">Product ident</param>
+ /// <param name="values">Update values</param>
+ public virtual async Task UpdateProductAttributeMapping(ProductAttributeMapping productAttributeMapping,
+ string productId, bool values = false)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeMapping);
- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMapping.Id, productAttributeMapping);
+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id,
+ productAttributeMapping.Id, productAttributeMapping);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityUpdated(productAttributeMapping);
- }
+ //event notification
+ await _mediator.EntityUpdated(productAttributeMapping);
+ }
- #endregion
+ #endregion
- #region Product attribute values
+ #region Product attribute values
- /// <summary>
- /// Deletes a product attribute value
- /// </summary>
- /// <param name="productAttributeValue">Product attribute value</param>
- /// <param name="productId">Product ident</param>
- /// <param name="productAttributeMappingId">Product attr mapping ident</param>
- public virtual async Task DeleteProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId)
- {
- ArgumentNullException.ThrowIfNull(productAttributeValue);
+ /// <summary>
+ /// Deletes a product attribute value
+ /// </summary>
+ /// <param name="productAttributeValue">Product attribute value</param>
+ /// <param name="productId">Product ident</param>
+ /// <param name="productAttributeMappingId">Product attr mapping ident</param>
+ public virtual async Task DeleteProductAttributeValue(ProductAttributeValue productAttributeValue, string productId,
+ string productAttributeMappingId)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeValue);
- var p = await _productRepository.GetByIdAsync(productId);
- if (p != null)
+ var p = await _productRepository.GetByIdAsync(productId);
+ if (p != null)
+ {
+ var pavs = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
+ var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);
+ if (pav != null)
{
- var pavs = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
- var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);
- if (pav != null)
- {
- pavs.ProductAttributeValues.Remove(pav);
- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);
- }
+ pavs.ProductAttributeValues.Remove(pav);
+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id,
+ productAttributeMappingId, pavs);
}
-
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
-
- //event notification
- await _mediator.EntityDeleted(productAttributeValue);
}
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- /// <summary>
- /// Inserts a product attribute value
- /// </summary>
- /// <param name="productAttributeValue">The product attribute value</param>
- /// <param name="productId">Product ident</param>
- /// <param name="productAttributeMappingId">Product attr mapping ident</param>
- public virtual async Task InsertProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId)
- {
- ArgumentNullException.ThrowIfNull(productAttributeValue);
+ //event notification
+ await _mediator.EntityDeleted(productAttributeValue);
+ }
- var p = await _productRepository.GetByIdAsync(productId);
- if (p == null)
- throw new ArgumentNullException(nameof(p));
- var pam = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
- if (pam == null)
- throw new ArgumentNullException(nameof(pam));
+ /// <summary>
+ /// Inserts a product attribute value
+ /// </summary>
+ /// <param name="productAttributeValue">The product attribute value</param>
+ /// <param name="productId">Product ident</param>
+ /// <param name="productAttributeMappingId">Product attr mapping ident</param>
+ public virtual async Task InsertProductAttributeValue(ProductAttributeValue productAttributeValue, string productId,
+ string productAttributeMappingId)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeValue);
- pam.ProductAttributeValues.Add(productAttributeValue);
- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pam);
+ var p = await _productRepository.GetByIdAsync(productId);
+ if (p == null)
+ throw new ArgumentNullException(nameof(p));
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ var pam = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
+ if (pam == null)
+ throw new ArgumentNullException(nameof(pam));
- //event notification
- await _mediator.EntityInserted(productAttributeValue);
- }
+ pam.ProductAttributeValues.Add(productAttributeValue);
+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id,
+ productAttributeMappingId, pam);
- /// <summary>
- /// Updates the product attribute value
- /// </summary>
- /// <param name="productAttributeValue">The product attribute value</param>
- /// <param name="productId">Product ident</param>
- /// <param name="productAttributeMappingId">Product attr mapping ident</param>
- public virtual async Task UpdateProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId)
- {
- ArgumentNullException.ThrowIfNull(productAttributeValue);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- var p = await _productRepository.GetByIdAsync(productId);
- var pavs = p?.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
- var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);
- if (pav != null)
- {
- pav.AttributeValueTypeId = productAttributeValue.AttributeValueTypeId;
- pav.AssociatedProductId = productAttributeValue.AssociatedProductId;
- pav.Name = productAttributeValue.Name;
- pav.ColorSquaresRgb = productAttributeValue.ColorSquaresRgb;
- pav.ImageSquaresPictureId = productAttributeValue.ImageSquaresPictureId;
- pav.PriceAdjustment = productAttributeValue.PriceAdjustment;
- pav.WeightAdjustment = productAttributeValue.WeightAdjustment;
- pav.Cost = productAttributeValue.Cost;
- pav.Quantity = productAttributeValue.Quantity;
- pav.IsPreSelected = productAttributeValue.IsPreSelected;
- pav.DisplayOrder = productAttributeValue.DisplayOrder;
- pav.PictureId = productAttributeValue.PictureId;
- pav.Locales = productAttributeValue.Locales;
-
- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMappingId, pavs);
- }
+ //event notification
+ await _mediator.EntityInserted(productAttributeValue);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ /// <summary>
+ /// Updates the product attribute value
+ /// </summary>
+ /// <param name="productAttributeValue">The product attribute value</param>
+ /// <param name="productId">Product ident</param>
+ /// <param name="productAttributeMappingId">Product attr mapping ident</param>
+ public virtual async Task UpdateProductAttributeValue(ProductAttributeValue productAttributeValue, string productId,
+ string productAttributeMappingId)
+ {
+ ArgumentNullException.ThrowIfNull(productAttributeValue);
- //event notification
- await _mediator.EntityUpdated(productAttributeValue);
+ var p = await _productRepository.GetByIdAsync(productId);
+ var pavs = p?.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);
+ var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id);
+ if (pav != null)
+ {
+ pav.AttributeValueTypeId = productAttributeValue.AttributeValueTypeId;
+ pav.AssociatedProductId = productAttributeValue.AssociatedProductId;
+ pav.Name = productAttributeValue.Name;
+ pav.ColorSquaresRgb = productAttributeValue.ColorSquaresRgb;
+ pav.ImageSquaresPictureId = productAttributeValue.ImageSquaresPictureId;
+ pav.PriceAdjustment = productAttributeValue.PriceAdjustment;
+ pav.WeightAdjustment = productAttributeValue.WeightAdjustment;
+ pav.Cost = productAttributeValue.Cost;
+ pav.Quantity = productAttributeValue.Quantity;
+ pav.IsPreSelected = productAttributeValue.IsPreSelected;
+ pav.DisplayOrder = productAttributeValue.DisplayOrder;
+ pav.PictureId = productAttributeValue.PictureId;
+ pav.Locales = productAttributeValue.Locales;
+
+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id,
+ productAttributeMappingId, pavs);
}
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #region Product attribute combinations
+ //event notification
+ await _mediator.EntityUpdated(productAttributeValue);
+ }
- /// <summary>
- /// Deletes a product attribute combination
- /// </summary>
- /// <param name="combination">Product attribute combination</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductAttributeCombination(ProductAttributeCombination combination, string productId)
- {
- ArgumentNullException.ThrowIfNull(combination);
+ #endregion
- await _productRepository.PullFilter(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ #region Product attribute combinations
- //event notification
- await _mediator.EntityDeleted(combination);
- }
+ /// <summary>
+ /// Deletes a product attribute combination
+ /// </summary>
+ /// <param name="combination">Product attribute combination</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductAttributeCombination(ProductAttributeCombination combination,
+ string productId)
+ {
+ ArgumentNullException.ThrowIfNull(combination);
- /// <summary>
- /// Inserts a product attribute combination
- /// </summary>
- /// <param name="combination">Product attribute combination</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductAttributeCombination(ProductAttributeCombination combination, string productId)
- {
- ArgumentNullException.ThrowIfNull(combination);
+ await _productRepository.PullFilter(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- await _productRepository.AddToSet(productId, x => x.ProductAttributeCombinations, combination);
+ //event notification
+ await _mediator.EntityDeleted(combination);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ /// <summary>
+ /// Inserts a product attribute combination
+ /// </summary>
+ /// <param name="combination">Product attribute combination</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductAttributeCombination(ProductAttributeCombination combination,
+ string productId)
+ {
+ ArgumentNullException.ThrowIfNull(combination);
- //event notification
- await _mediator.EntityInserted(combination);
- }
+ await _productRepository.AddToSet(productId, x => x.ProductAttributeCombinations, combination);
- /// <summary>
- /// Updates a product attribute combination
- /// </summary>
- /// <param name="combination">Product attribute combination</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateProductAttributeCombination(ProductAttributeCombination combination, string productId)
- {
- ArgumentNullException.ThrowIfNull(combination);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- await _productRepository.UpdateToSet(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
+ //event notification
+ await _mediator.EntityInserted(combination);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ /// <summary>
+ /// Updates a product attribute combination
+ /// </summary>
+ /// <param name="combination">Product attribute combination</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateProductAttributeCombination(ProductAttributeCombination combination,
+ string productId)
+ {
+ ArgumentNullException.ThrowIfNull(combination);
- //event notification
- await _mediator.EntityUpdated(combination);
- }
+ await _productRepository.UpdateToSet(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id,
+ combination);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #endregion
+ //event notification
+ await _mediator.EntityUpdated(combination);
}
-}
+
+ #endregion
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs
index 9f8083797..59f87272a 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs
@@ -1,38 +1,37 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Courses;
-using Grand.Data;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+public class ProductCourseService : IProductCourseService
{
- public class ProductCourseService : IProductCourseService
- {
- private readonly IRepository<Product> _productRepository;
- private readonly IRepository<Course> _courseRepository;
+ private readonly IRepository<Course> _courseRepository;
+ private readonly IRepository<Product> _productRepository;
- public ProductCourseService(IRepository<Product> productRepository, IRepository<Course> courseRepository)
- {
- _productRepository = productRepository;
- _courseRepository = courseRepository;
- }
+ public ProductCourseService(IRepository<Product> productRepository, IRepository<Course> courseRepository)
+ {
+ _productRepository = productRepository;
+ _courseRepository = courseRepository;
+ }
- public virtual async Task<Course> GetCourseByProductId(string productId)
- {
- return await _courseRepository.GetOneAsync(p => p.ProductId == productId);
- }
+ public virtual async Task<Course> GetCourseByProductId(string productId)
+ {
+ return await _courseRepository.GetOneAsync(p => p.ProductId == productId);
+ }
- public virtual async Task<Product> GetProductByCourseId(string courseId)
- {
- return await _productRepository.GetOneAsync(p => p.CourseId == courseId);
- }
+ public virtual async Task<Product> GetProductByCourseId(string courseId)
+ {
+ return await _productRepository.GetOneAsync(p => p.CourseId == courseId);
+ }
- public virtual async Task UpdateCourseOnProduct(string productId, string courseId)
- {
- if (string.IsNullOrEmpty(productId))
- throw new ArgumentNullException(nameof(productId));
+ public virtual async Task UpdateCourseOnProduct(string productId, string courseId)
+ {
+ if (string.IsNullOrEmpty(productId))
+ throw new ArgumentNullException(nameof(productId));
- await _productRepository.UpdateField(productId, x => x.CourseId, courseId);
- await _productRepository.UpdateField(productId, x => x.UpdatedOnUtc, DateTime.UtcNow);
- }
+ await _productRepository.UpdateField(productId, x => x.CourseId, courseId);
+ await _productRepository.UpdateField(productId, x => x.UpdatedOnUtc, DateTime.UtcNow);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs
index 9fb4cf98a..9908147c2 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs
@@ -1,125 +1,123 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Extensions;
-using Grand.Domain.Catalog;
using Grand.Data;
-using MediatR;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
+using Grand.Infrastructure.Extensions;
+using MediatR;
+
+namespace Grand.Business.Catalog.Services.Products;
-namespace Grand.Business.Catalog.Services.Products
+/// <summary>
+/// Product layout service
+/// </summary>
+public class ProductLayoutService : IProductLayoutService
{
+ #region Ctor
+
/// <summary>
- /// Product layout service
+ /// Ctor
/// </summary>
- public class ProductLayoutService : IProductLayoutService
+ /// <param name="productLayoutRepository">Product layout repository</param>
+ /// <param name="cacheBase">Cache base</param>
+ /// <param name="mediator">Mediator</param>
+ public ProductLayoutService(IRepository<ProductLayout> productLayoutRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<ProductLayout> _productLayoutRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _productLayoutRepository = productLayoutRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="productLayoutRepository">Product layout repository</param>
- /// <param name="cacheBase">Cache base</param>
- /// <param name="mediator">Mediator</param>
- public ProductLayoutService(IRepository<ProductLayout> productLayoutRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _productLayoutRepository = productLayoutRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
+ private readonly IRepository<ProductLayout> _productLayoutRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
-
- /// <summary>
- /// Gets all product layouts
- /// </summary>
- /// <returns>Product layouts</returns>
- public virtual async Task<IList<ProductLayout>> GetAllProductLayouts()
- {
- return await _cacheBase.GetAsync(CacheKey.PRODUCT_LAYOUT_ALL, async () =>
- {
- var query = from pt in _productLayoutRepository.Table
- orderby pt.DisplayOrder
- select pt;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a product layout
- /// </summary>
- /// <param name="productLayoutId">Product layout identifier</param>
- /// <returns>Product layout</returns>
- public virtual Task<ProductLayout> GetProductLayoutById(string productLayoutId)
- {
- var key = string.Format(CacheKey.PRODUCT_LAYOUT_BY_ID_KEY, productLayoutId);
- return _cacheBase.GetAsync(key, () => _productLayoutRepository.GetByIdAsync(productLayoutId));
- }
-
- /// <summary>
- /// Inserts product layout
- /// </summary>
- /// <param name="productLayout">Product layout</param>
- public virtual async Task InsertProductLayout(ProductLayout productLayout)
+ /// <summary>
+ /// Gets all product layouts
+ /// </summary>
+ /// <returns>Product layouts</returns>
+ public virtual async Task<IList<ProductLayout>> GetAllProductLayouts()
+ {
+ return await _cacheBase.GetAsync(CacheKey.PRODUCT_LAYOUT_ALL, async () =>
{
- ArgumentNullException.ThrowIfNull(productLayout);
+ var query = from pt in _productLayoutRepository.Table
+ orderby pt.DisplayOrder
+ select pt;
+ return await Task.FromResult(query.ToList());
+ });
+ }
+
+ /// <summary>
+ /// Gets a product layout
+ /// </summary>
+ /// <param name="productLayoutId">Product layout identifier</param>
+ /// <returns>Product layout</returns>
+ public virtual Task<ProductLayout> GetProductLayoutById(string productLayoutId)
+ {
+ var key = string.Format(CacheKey.PRODUCT_LAYOUT_BY_ID_KEY, productLayoutId);
+ return _cacheBase.GetAsync(key, () => _productLayoutRepository.GetByIdAsync(productLayoutId));
+ }
- await _productLayoutRepository.InsertAsync(productLayout);
+ /// <summary>
+ /// Inserts product layout
+ /// </summary>
+ /// <param name="productLayout">Product layout</param>
+ public virtual async Task InsertProductLayout(ProductLayout productLayout)
+ {
+ ArgumentNullException.ThrowIfNull(productLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
+ await _productLayoutRepository.InsertAsync(productLayout);
- //event notification
- await _mediator.EntityInserted(productLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
- /// <summary>
- /// Updates the product layout
- /// </summary>
- /// <param name="productLayout">Product layout</param>
- public virtual async Task UpdateProductLayout(ProductLayout productLayout)
- {
- ArgumentNullException.ThrowIfNull(productLayout);
+ //event notification
+ await _mediator.EntityInserted(productLayout);
+ }
- await _productLayoutRepository.UpdateAsync(productLayout);
+ /// <summary>
+ /// Updates the product layout
+ /// </summary>
+ /// <param name="productLayout">Product layout</param>
+ public virtual async Task UpdateProductLayout(ProductLayout productLayout)
+ {
+ ArgumentNullException.ThrowIfNull(productLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
+ await _productLayoutRepository.UpdateAsync(productLayout);
- //event notification
- await _mediator.EntityUpdated(productLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
- /// <summary>
- /// Delete product layout
- /// </summary>
- /// <param name="productLayout">Product layout</param>
- public virtual async Task DeleteProductLayout(ProductLayout productLayout)
- {
- ArgumentNullException.ThrowIfNull(productLayout);
+ //event notification
+ await _mediator.EntityUpdated(productLayout);
+ }
- await _productLayoutRepository.DeleteAsync(productLayout);
+ /// <summary>
+ /// Delete product layout
+ /// </summary>
+ /// <param name="productLayout">Product layout</param>
+ public virtual async Task DeleteProductLayout(ProductLayout productLayout)
+ {
+ ArgumentNullException.ThrowIfNull(productLayout);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
+ await _productLayoutRepository.DeleteAsync(productLayout);
- //event notification
- await _mediator.EntityDeleted(productLayout);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCT_LAYOUT_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(productLayout);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs
index 8df95601f..09cd45aa6 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs
@@ -1,186 +1,188 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product reservation service
+/// </summary>
+public class ProductReservationService : IProductReservationService
{
+ private readonly IRepository<CustomerReservationsHelper> _customerReservationsHelperRepository;
+ private readonly IMediator _mediator;
+ private readonly IRepository<ProductReservation> _productReservationRepository;
+
+ public ProductReservationService(
+ IRepository<ProductReservation> productReservationRepository,
+ IRepository<CustomerReservationsHelper> customerReservationsHelperRepository,
+ IMediator mediator)
+ {
+ _productReservationRepository = productReservationRepository;
+ _customerReservationsHelperRepository = customerReservationsHelperRepository;
+ _mediator = mediator;
+ }
+
+
/// <summary>
- /// Product reservation service
+ /// Gets product reservations for product Id
/// </summary>
- public class ProductReservationService : IProductReservationService
+ /// <param name="productId">Product Id</param>
+ /// <param name="showVacant">Show vacant</param>
+ /// <param name="date">Date</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Product reservations</returns>
+ public virtual async Task<IPagedList<ProductReservation>> GetProductReservationsByProductId(string productId,
+ bool? showVacant, DateTime? date,
+ int pageIndex = 0, int pageSize = int.MaxValue)
{
- private readonly IRepository<ProductReservation> _productReservationRepository;
- private readonly IRepository<CustomerReservationsHelper> _customerReservationsHelperRepository;
- private readonly IMediator _mediator;
-
- public ProductReservationService(
- IRepository<ProductReservation> productReservationRepository,
- IRepository<CustomerReservationsHelper> customerReservationsHelperRepository,
- IMediator mediator)
- {
- _productReservationRepository = productReservationRepository;
- _customerReservationsHelperRepository = customerReservationsHelperRepository;
- _mediator = mediator;
- }
+ var query = _productReservationRepository.Table.Where(x => x.ProductId == productId);
+ if (showVacant.HasValue)
+ query = showVacant.Value
+ ? query.Where(x => x.OrderId == "" || x.OrderId == null)
+ : query.Where(x => x.OrderId != "" && x.OrderId != null);
- /// <summary>
- /// Gets product reservations for product Id
- /// </summary>
- /// <param name="productId">Product Id</param>
- /// <param name="showVacant">Show vacant</param>
- /// <param name="date">Date</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Product reservations</returns>
- public virtual async Task<IPagedList<ProductReservation>> GetProductReservationsByProductId(string productId, bool? showVacant, DateTime? date,
- int pageIndex = 0, int pageSize = int.MaxValue)
+ if (date.HasValue)
{
- var query = _productReservationRepository.Table.Where(x => x.ProductId == productId);
-
- if (showVacant.HasValue)
- {
- query = showVacant.Value ? query.Where(x => x.OrderId == "" || x.OrderId == null) : query.Where(x => x.OrderId != "" && x.OrderId != null);
- }
-
- if (date.HasValue)
- {
- var min = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, 0, 0, 0, 0);
- var max = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, 23, 59, 59, 999);
+ var min = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, 0, 0, 0, 0);
+ var max = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, 23, 59, 59, 999);
- query = query.Where(x => x.Date >= min && x.Date <= max);
- }
-
- query = query.OrderBy(x => x.Date);
- return await PagedList<ProductReservation>.Create(query, pageIndex, pageSize);
+ query = query.Where(x => x.Date >= min && x.Date <= max);
}
- /// <summary>
- /// Adds product reservation
- /// </summary>
- /// <param name="productReservation">Product reservation</param>
- public virtual async Task InsertProductReservation(ProductReservation productReservation)
- {
- ArgumentNullException.ThrowIfNull(productReservation);
+ query = query.OrderBy(x => x.Date);
+ return await PagedList<ProductReservation>.Create(query, pageIndex, pageSize);
+ }
- await _productReservationRepository.InsertAsync(productReservation);
+ /// <summary>
+ /// Adds product reservation
+ /// </summary>
+ /// <param name="productReservation">Product reservation</param>
+ public virtual async Task InsertProductReservation(ProductReservation productReservation)
+ {
+ ArgumentNullException.ThrowIfNull(productReservation);
- //event
- await _mediator.EntityInserted(productReservation);
- }
+ await _productReservationRepository.InsertAsync(productReservation);
- /// <summary>
- /// Updates product reservation
- /// </summary>
- /// <param name="productReservation">Product reservation</param>
- public virtual async Task UpdateProductReservation(ProductReservation productReservation)
- {
- ArgumentNullException.ThrowIfNull(productReservation);
+ //event
+ await _mediator.EntityInserted(productReservation);
+ }
- await _productReservationRepository.UpdateAsync(productReservation);
+ /// <summary>
+ /// Updates product reservation
+ /// </summary>
+ /// <param name="productReservation">Product reservation</param>
+ public virtual async Task UpdateProductReservation(ProductReservation productReservation)
+ {
+ ArgumentNullException.ThrowIfNull(productReservation);
- //event
- await _mediator.EntityUpdated(productReservation);
- }
+ await _productReservationRepository.UpdateAsync(productReservation);
- /// <summary>
- /// Deletes a product reservation
- /// </summary>
- /// <param name="productReservation">Product reservation</param>
- public virtual async Task DeleteProductReservation(ProductReservation productReservation)
- {
- ArgumentNullException.ThrowIfNull(productReservation);
+ //event
+ await _mediator.EntityUpdated(productReservation);
+ }
- await _productReservationRepository.DeleteAsync(productReservation);
+ /// <summary>
+ /// Deletes a product reservation
+ /// </summary>
+ /// <param name="productReservation">Product reservation</param>
+ public virtual async Task DeleteProductReservation(ProductReservation productReservation)
+ {
+ ArgumentNullException.ThrowIfNull(productReservation);
- //event
- await _mediator.EntityDeleted(productReservation);
- }
+ await _productReservationRepository.DeleteAsync(productReservation);
- /// <summary>
- /// Gets product reservation for specified Id
- /// </summary>
- /// <param name="id">Product ident</param>
- /// <returns>Product reservation</returns>
- public virtual Task<ProductReservation> GetProductReservation(string id)
- {
- return _productReservationRepository.GetByIdAsync(id);
- }
+ //event
+ await _mediator.EntityDeleted(productReservation);
+ }
- /// <summary>
- /// Adds customer reservations helper
- /// </summary>
- /// <param name="crh"></param>
- public virtual async Task InsertCustomerReservationsHelper(CustomerReservationsHelper crh)
- {
- ArgumentNullException.ThrowIfNull(crh);
+ /// <summary>
+ /// Gets product reservation for specified Id
+ /// </summary>
+ /// <param name="id">Product ident</param>
+ /// <returns>Product reservation</returns>
+ public virtual Task<ProductReservation> GetProductReservation(string id)
+ {
+ return _productReservationRepository.GetByIdAsync(id);
+ }
- await _customerReservationsHelperRepository.InsertAsync(crh);
+ /// <summary>
+ /// Adds customer reservations helper
+ /// </summary>
+ /// <param name="crh"></param>
+ public virtual async Task InsertCustomerReservationsHelper(CustomerReservationsHelper crh)
+ {
+ ArgumentNullException.ThrowIfNull(crh);
- //event
- await _mediator.EntityInserted(crh);
- }
+ await _customerReservationsHelperRepository.InsertAsync(crh);
- /// <summary>
- /// Deletes customer reservations helper
- /// </summary>
- /// <param name="crh"></param>
- public virtual async Task DeleteCustomerReservationsHelper(CustomerReservationsHelper crh)
- {
- ArgumentNullException.ThrowIfNull(crh);
+ //event
+ await _mediator.EntityInserted(crh);
+ }
- await _customerReservationsHelperRepository.DeleteAsync(crh);
+ /// <summary>
+ /// Deletes customer reservations helper
+ /// </summary>
+ /// <param name="crh"></param>
+ public virtual async Task DeleteCustomerReservationsHelper(CustomerReservationsHelper crh)
+ {
+ ArgumentNullException.ThrowIfNull(crh);
- //event
- await _mediator.EntityDeleted(crh);
- }
+ await _customerReservationsHelperRepository.DeleteAsync(crh);
+ //event
+ await _mediator.EntityDeleted(crh);
+ }
- /// <summary>
- /// Cancel reservations by orderId
- /// </summary>
- /// <param name="orderId"></param>
- public virtual async Task CancelReservationsByOrderId(string orderId)
- {
- if (!string.IsNullOrEmpty(orderId))
- {
- await _productReservationRepository.UpdateManyAsync(x => x.OrderId == orderId,
+
+ /// <summary>
+ /// Cancel reservations by orderId
+ /// </summary>
+ /// <param name="orderId"></param>
+ public virtual async Task CancelReservationsByOrderId(string orderId)
+ {
+ if (!string.IsNullOrEmpty(orderId))
+ await _productReservationRepository.UpdateManyAsync(x => x.OrderId == orderId,
UpdateBuilder<ProductReservation>.Create().Set(x => x.OrderId, ""));
- }
- }
+ }
- /// <summary>
- /// Gets customer reservations helper by id
- /// </summary>
- /// <param name="id"></param>
- /// <returns>CustomerReservationsHelper</returns>
- public virtual Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string id)
- {
- return _customerReservationsHelperRepository.GetByIdAsync(id);
- }
+ /// <summary>
+ /// Gets customer reservations helper by id
+ /// </summary>
+ /// <param name="id"></param>
+ /// <returns>CustomerReservationsHelper</returns>
+ public virtual Task<CustomerReservationsHelper> GetCustomerReservationsHelperById(string id)
+ {
+ return _customerReservationsHelperRepository.GetByIdAsync(id);
+ }
- /// <summary>
- /// Gets customer reservations helpers
- /// </summary>
- /// <returns>List<CustomerReservationsHelper />
- /// </returns>
- public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelpers(string customerId)
- {
- return await Task.FromResult(_customerReservationsHelperRepository.Table.Where(x => x.CustomerId == customerId).ToList());
- }
+ /// <summary>
+ /// Gets customer reservations helpers
+ /// </summary>
+ /// <returns>
+ /// List<CustomerReservationsHelper />
+ /// </returns>
+ public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelpers(string customerId)
+ {
+ return await Task.FromResult(_customerReservationsHelperRepository.Table.Where(x => x.CustomerId == customerId)
+ .ToList());
+ }
- /// <summary>
- /// Gets customer reservations helper by Shopping Cart Item id
- /// </summary>
- /// <param name="sciId">sci ident</param>
- /// <returns>IList<CustomerReservationsHelper />
- /// </returns>
- public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelperBySciId(string sciId)
- {
- return await Task.FromResult(_customerReservationsHelperRepository.Table.Where(x => x.ShoppingCartItemId == sciId).ToList());
- }
+ /// <summary>
+ /// Gets customer reservations helper by Shopping Cart Item id
+ /// </summary>
+ /// <param name="sciId">sci ident</param>
+ /// <returns>
+ /// IList<CustomerReservationsHelper />
+ /// </returns>
+ public virtual async Task<IList<CustomerReservationsHelper>> GetCustomerReservationsHelperBySciId(string sciId)
+ {
+ return await Task.FromResult(_customerReservationsHelperRepository.Table
+ .Where(x => x.ShoppingCartItemId == sciId).ToList());
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs
index 0f0db8be1..db897ef61 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs
@@ -1,132 +1,131 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product review service
+/// </summary>
+public class ProductReviewService : IProductReviewService
{
+ #region Ctor
+
+ public ProductReviewService(IRepository<ProductReview> productReviewRepository, IMediator mediator)
+ {
+ _productReviewRepository = productReviewRepository;
+ _mediator = mediator;
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets all product reviews
+ /// </summary>
+ /// <param name="customerId">Customer identifier; "" to load all records</param>
+ /// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
+ /// <param name="fromUtc">Item creation from; null to load all records</param>
+ /// <param name="toUtc">Item item creation to; null to load all records</param>
+ /// <param name="message">Search title or review text; null to load all records</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="productId">Product ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Reviews</returns>
+ public virtual async Task<IPagedList<ProductReview>> GetAllProductReviews(string customerId, bool? approved,
+ DateTime? fromUtc = null, DateTime? toUtc = null,
+ string message = null, string storeId = "", string productId = "", int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = from p in _productReviewRepository.Table
+ select p;
+
+ if (approved.HasValue)
+ query = query.Where(c => c.IsApproved == approved.Value);
+ if (!string.IsNullOrEmpty(customerId))
+ query = query.Where(c => c.CustomerId == customerId);
+ if (fromUtc.HasValue)
+ query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);
+ if (toUtc.HasValue)
+ query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);
+ if (!string.IsNullOrEmpty(message))
+ query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));
+ if (!string.IsNullOrEmpty(storeId))
+ query = query.Where(c => c.StoreId == storeId || c.StoreId == "");
+ if (!string.IsNullOrEmpty(productId))
+ query = query.Where(c => c.ProductId == productId);
+
+ query = query.OrderByDescending(c => c.CreatedOnUtc);
+
+ return await PagedList<ProductReview>.Create(query, pageIndex, pageSize);
+ }
+
+ /// <summary>
+ /// Inserts a product review
+ /// </summary>
+ /// <param name="productReview">Product review</param>
+ public virtual async Task InsertProductReview(ProductReview productReview)
+ {
+ ArgumentNullException.ThrowIfNull(productReview);
+
+ await _productReviewRepository.InsertAsync(productReview);
+
+ //event notification
+ await _mediator.EntityInserted(productReview);
+ }
+
+ public virtual async Task UpdateProductReview(ProductReview productReview)
+ {
+ ArgumentNullException.ThrowIfNull(productReview);
+
+ var update = UpdateBuilder<ProductReview>.Create()
+ .Set(x => x.Title, productReview.Title)
+ .Set(x => x.ReviewText, productReview.ReviewText)
+ .Set(x => x.ReplyText, productReview.ReplyText)
+ .Set(x => x.Signature, productReview.Signature)
+ .Set(x => x.IsApproved, productReview.IsApproved)
+ .Set(x => x.HelpfulNoTotal, productReview.HelpfulNoTotal)
+ .Set(x => x.HelpfulYesTotal, productReview.HelpfulYesTotal)
+ .Set(x => x.ProductReviewHelpfulnessEntries, productReview.ProductReviewHelpfulnessEntries);
+
+ await _productReviewRepository.UpdateOneAsync(x => x.Id == productReview.Id, update);
+
+ //event notification
+ await _mediator.EntityUpdated(productReview);
+ }
+
/// <summary>
- /// Product review service
+ /// Deletes a product review
/// </summary>
- public class ProductReviewService : IProductReviewService
+ /// <param name="productReview">Product review</param>
+ public virtual async Task DeleteProductReview(ProductReview productReview)
{
+ ArgumentNullException.ThrowIfNull(productReview);
- #region Fields
-
- private readonly IRepository<ProductReview> _productReviewRepository;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- public ProductReviewService(IRepository<ProductReview> productReviewRepository, IMediator mediator)
- {
- _productReviewRepository = productReviewRepository;
- _mediator = mediator;
- }
-
- #endregion
-
- /// <summary>
- /// Gets all product reviews
- /// </summary>
- /// <param name="customerId">Customer identifier; "" to load all records</param>
- /// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
- /// <param name="fromUtc">Item creation from; null to load all records</param>
- /// <param name="toUtc">Item item creation to; null to load all records</param>
- /// <param name="message">Search title or review text; null to load all records</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="productId">Product ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Reviews</returns>
- public virtual async Task<IPagedList<ProductReview>> GetAllProductReviews(string customerId, bool? approved,
- DateTime? fromUtc = null, DateTime? toUtc = null,
- string message = null, string storeId = "", string productId = "", int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _productReviewRepository.Table
- select p;
-
- if (approved.HasValue)
- query = query.Where(c => c.IsApproved == approved.Value);
- if (!string.IsNullOrEmpty(customerId))
- query = query.Where(c => c.CustomerId == customerId);
- if (fromUtc.HasValue)
- query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);
- if (toUtc.HasValue)
- query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);
- if (!string.IsNullOrEmpty(message))
- query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));
- if (!string.IsNullOrEmpty(storeId))
- query = query.Where(c => c.StoreId == storeId || c.StoreId == "");
- if (!string.IsNullOrEmpty(productId))
- query = query.Where(c => c.ProductId == productId);
-
- query = query.OrderByDescending(c => c.CreatedOnUtc);
-
- return await PagedList<ProductReview>.Create(query, pageIndex, pageSize);
- }
-
- /// <summary>
- /// Inserts a product review
- /// </summary>
- /// <param name="productReview">Product review</param>
- public virtual async Task InsertProductReview(ProductReview productReview)
- {
- ArgumentNullException.ThrowIfNull(productReview);
-
- await _productReviewRepository.InsertAsync(productReview);
-
- //event notification
- await _mediator.EntityInserted(productReview);
- }
- public virtual async Task UpdateProductReview(ProductReview productReview)
- {
- ArgumentNullException.ThrowIfNull(productReview);
-
- var update = UpdateBuilder<ProductReview>.Create()
- .Set(x => x.Title, productReview.Title)
- .Set(x => x.ReviewText, productReview.ReviewText)
- .Set(x => x.ReplyText, productReview.ReplyText)
- .Set(x => x.Signature, productReview.Signature)
- .Set(x => x.IsApproved, productReview.IsApproved)
- .Set(x => x.HelpfulNoTotal, productReview.HelpfulNoTotal)
- .Set(x => x.HelpfulYesTotal, productReview.HelpfulYesTotal)
- .Set(x => x.ProductReviewHelpfulnessEntries, productReview.ProductReviewHelpfulnessEntries);
-
- await _productReviewRepository.UpdateOneAsync(x => x.Id == productReview.Id, update);
-
- //event notification
- await _mediator.EntityUpdated(productReview);
- }
-
- /// <summary>
- /// Deletes a product review
- /// </summary>
- /// <param name="productReview">Product review</param>
- public virtual async Task DeleteProductReview(ProductReview productReview)
- {
- ArgumentNullException.ThrowIfNull(productReview);
-
- await _productReviewRepository.DeleteAsync(productReview);
-
- //event notification
- await _mediator.EntityDeleted(productReview);
- }
-
-
- /// <summary>
- /// Gets product review
- /// </summary>
- /// <param name="productReviewId">Product review identifier</param>
- /// <returns>Product review</returns>
- public virtual Task<ProductReview> GetProductReviewById(string productReviewId)
- {
- return _productReviewRepository.GetByIdAsync(productReviewId);
- }
+ await _productReviewRepository.DeleteAsync(productReview);
+ //event notification
+ await _mediator.EntityDeleted(productReview);
}
-}
+
+
+ /// <summary>
+ /// Gets product review
+ /// </summary>
+ /// <param name="productReviewId">Product review identifier</param>
+ /// <returns>Product review</returns>
+ public virtual Task<ProductReview> GetProductReviewById(string productReviewId)
+ {
+ return _productReviewRepository.GetByIdAsync(productReviewId);
+ }
+
+ #region Fields
+
+ private readonly IRepository<ProductReview> _productReviewRepository;
+ private readonly IMediator _mediator;
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
index c56a5fce3..ed22bb8d4 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
@@ -1,11 +1,11 @@
using Grand.Business.Core.Events.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Business.Core.Queries.Catalog;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
@@ -14,473 +14,486 @@ using Grand.Infrastructure.Extensions;
using MediatR;
using System.Linq.Expressions;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product service
+/// </summary>
+public class ProductService : IProductService
{
+ #region Ctor
+
/// <summary>
- /// Product service
+ /// Ctor
/// </summary>
- public class ProductService : IProductService
+ public ProductService(ICacheBase cacheBase,
+ IRepository<Product> productRepository,
+ IWorkContext workContext,
+ IMediator mediator,
+ IAclService aclService
+ )
{
- #region Fields
-
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
- private readonly IAclService _aclService;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public ProductService(ICacheBase cacheBase,
- IRepository<Product> productRepository,
- IWorkContext workContext,
- IMediator mediator,
- IAclService aclService
- )
- {
- _cacheBase = cacheBase;
- _productRepository = productRepository;
- _workContext = workContext;
- _mediator = mediator;
- _aclService = aclService;
- }
+ _cacheBase = cacheBase;
+ _productRepository = productRepository;
+ _workContext = workContext;
+ _mediator = mediator;
+ _aclService = aclService;
+ }
- #endregion
+ #endregion
- #region Methods
+ #region Fields
- #region Products
+ private readonly IRepository<Product> _productRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IWorkContext _workContext;
+ private readonly IAclService _aclService;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Gets all products displayed on the home page
- /// </summary>
- /// <returns>Products</returns>
- public virtual async Task<IList<string>> GetAllProductsDisplayedOnHomePage()
- {
- var query = _productRepository.Table.Where(x => x.Published && x.ShowOnHomePage && x.VisibleIndividually)
- .OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name).Select(x => x.Id);
+ #endregion
- return await Task.FromResult(query.ToList());
- }
+ #region Methods
- /// <summary>
- /// Gets all products displayed on the best seller
- /// </summary>
- /// <returns>Products</returns>
- public virtual async Task<IList<string>> GetAllProductsDisplayedOnBestSeller()
- {
- var query = _productRepository.Table.Where(x => x.Published && x.BestSeller && x.VisibleIndividually)
- .OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name)
- .Select(x => x.Id);
+ #region Products
- var products = await Task.FromResult(query.ToList());
+ /// <summary>
+ /// Gets all products displayed on the home page
+ /// </summary>
+ /// <returns>Products</returns>
+ public virtual async Task<IList<string>> GetAllProductsDisplayedOnHomePage()
+ {
+ var query = _productRepository.Table.Where(x => x.Published && x.ShowOnHomePage && x.VisibleIndividually)
+ .OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name).Select(x => x.Id);
- return products;
- }
+ return await Task.FromResult(query.ToList());
+ }
- /// <summary>
- /// Gets product
- /// </summary>
- /// <param name="productId">Product identifier</param>
- /// <param name="fromDb">get data from db (not from cache)</param>
- /// <returns>Product</returns>
- public virtual async Task<Product> GetProductById(string productId, bool fromDb = false)
- {
- if (string.IsNullOrEmpty(productId))
- return null;
+ /// <summary>
+ /// Gets all products displayed on the best seller
+ /// </summary>
+ /// <returns>Products</returns>
+ public virtual async Task<IList<string>> GetAllProductsDisplayedOnBestSeller()
+ {
+ var query = _productRepository.Table.Where(x => x.Published && x.BestSeller && x.VisibleIndividually)
+ .OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name)
+ .Select(x => x.Id);
- if (fromDb)
- return await _productRepository.GetByIdAsync(productId);
+ var products = await Task.FromResult(query.ToList());
- var key = string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId);
- return await _cacheBase.GetAsync(key, () => _productRepository.GetByIdAsync(productId));
- }
+ return products;
+ }
- /// <summary>
- /// Gets product for order
- /// </summary>
- /// <param name="productId">Product identifier</param>
- /// <returns>Product</returns>
- public virtual async Task<Product> GetProductByIdIncludeArch(string productId)
- {
- if (string.IsNullOrEmpty(productId))
- return null;
- var product = await GetProductById(productId) ?? await _mediator.Send(new GetProductArchByIdQuery { Id = productId });
- return product;
- }
- /// <summary>
- /// Get products by identifiers
- /// </summary>
- /// <param name="productIds">Product identifiers</param>
- /// <param name="showHidden">Show hidden</param>
- /// <returns>Products</returns>
- public virtual async Task<IList<Product>> GetProductsByIds(string[] productIds, bool showHidden = false)
- {
- if (productIds == null || productIds.Length == 0)
- return new List<Product>();
+ /// <summary>
+ /// Gets product
+ /// </summary>
+ /// <param name="productId">Product identifier</param>
+ /// <param name="fromDb">get data from db (not from cache)</param>
+ /// <returns>Product</returns>
+ public virtual async Task<Product> GetProductById(string productId, bool fromDb = false)
+ {
+ if (string.IsNullOrEmpty(productId))
+ return null;
- var products = new List<Product>();
- foreach (var id in productIds)
- {
- var product = await GetProductById(id);
- if (product != null && (showHidden || (_aclService.Authorize(product, _workContext.CurrentCustomer) && _aclService.Authorize(product, _workContext.CurrentStore.Id) && product.IsAvailable())))
- products.Add(product);
- }
- return products;
- }
+ if (fromDb)
+ return await _productRepository.GetByIdAsync(productId);
- /// <summary>
- /// Gets products by discount
- /// </summary>
- /// <param name="discountId">Product identifiers</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Products</returns>
- public virtual async Task<IPagedList<Product>> GetProductsByDiscount(string discountId, int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from c in _productRepository.Table
- where c.AppliedDiscounts.Any(x => x == discountId)
- select c;
+ var key = string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId);
+ return await _cacheBase.GetAsync(key, () => _productRepository.GetByIdAsync(productId));
+ }
- return await PagedList<Product>.Create(query, pageIndex, pageSize);
- }
+ /// <summary>
+ /// Gets product for order
+ /// </summary>
+ /// <param name="productId">Product identifier</param>
+ /// <returns>Product</returns>
+ public virtual async Task<Product> GetProductByIdIncludeArch(string productId)
+ {
+ if (string.IsNullOrEmpty(productId))
+ return null;
+ var product = await GetProductById(productId) ??
+ await _mediator.Send(new GetProductArchByIdQuery { Id = productId });
+ return product;
+ }
+ /// <summary>
+ /// Get products by identifiers
+ /// </summary>
+ /// <param name="productIds">Product identifiers</param>
+ /// <param name="showHidden">Show hidden</param>
+ /// <returns>Products</returns>
+ public virtual async Task<IList<Product>> GetProductsByIds(string[] productIds, bool showHidden = false)
+ {
+ if (productIds == null || productIds.Length == 0)
+ return new List<Product>();
- /// <summary>
- /// Inserts a product
- /// </summary>
- /// <param name="product">Product</param>
- public virtual async Task InsertProduct(Product product)
+ var products = new List<Product>();
+ foreach (var id in productIds)
{
- ArgumentNullException.ThrowIfNull(product);
+ var product = await GetProductById(id);
+ if (product != null && (showHidden || (_aclService.Authorize(product, _workContext.CurrentCustomer) &&
+ _aclService.Authorize(product, _workContext.CurrentStore.Id) &&
+ product.IsAvailable())))
+ products.Add(product);
+ }
- //insert
- await _productRepository.InsertAsync(product);
+ return products;
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ /// <summary>
+ /// Gets products by discount
+ /// </summary>
+ /// <param name="discountId">Product identifiers</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Products</returns>
+ public virtual async Task<IPagedList<Product>> GetProductsByDiscount(string discountId, int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = from c in _productRepository.Table
+ where c.AppliedDiscounts.Any(x => x == discountId)
+ select c;
- //event notification
- await _mediator.EntityInserted(product);
- }
+ return await PagedList<Product>.Create(query, pageIndex, pageSize);
+ }
- /// <summary>
- /// Updates the product
- /// </summary>
- /// <param name="product">Product</param>
- public virtual async Task UpdateProduct(Product product)
- {
- ArgumentNullException.ThrowIfNull(product);
-
- var oldProduct = await _productRepository.GetByIdAsync(product.Id);
- //update
- var update = UpdateBuilder<Product>.Create()
- .Set(x => x.AdditionalShippingCharge, product.AdditionalShippingCharge)
- .Set(x => x.AdminComment, product.AdminComment)
- .Set(x => x.AllowOutOfStockSubscriptions, product.AllowOutOfStockSubscriptions)
- .Set(x => x.AllowCustomerReviews, product.AllowCustomerReviews)
- .Set(x => x.AllowedQuantities, product.AllowedQuantities)
- .Set(x => x.ApprovedRatingSum, product.ApprovedRatingSum)
- .Set(x => x.ApprovedTotalReviews, product.ApprovedTotalReviews)
- .Set(x => x.AutoAddRequiredProducts, product.AutoAddRequiredProducts)
- .Set(x => x.AvailableEndDateTimeUtc, product.AvailableEndDateTimeUtc)
- .Set(x => x.AvailableForPreOrder, product.AvailableForPreOrder)
- .Set(x => x.AvailableStartDateTimeUtc, product.AvailableStartDateTimeUtc)
- .Set(x => x.BackorderModeId, product.BackorderModeId)
- .Set(x => x.BasepriceAmount, product.BasepriceAmount)
- .Set(x => x.BasepriceBaseAmount, product.BasepriceBaseAmount)
- .Set(x => x.BasepriceBaseUnitId, product.BasepriceBaseUnitId)
- .Set(x => x.BasepriceEnabled, product.BasepriceEnabled)
- .Set(x => x.BasepriceUnitId, product.BasepriceUnitId)
- .Set(x => x.CallForPrice, product.CallForPrice)
- .Set(x => x.CatalogPrice, product.CatalogPrice)
- .Set(x => x.EnteredPrice, product.EnteredPrice)
- .Set(x => x.CustomerGroups, product.CustomerGroups)
- .Set(x => x.DeliveryDateId, product.DeliveryDateId)
- .Set(x => x.DisableBuyButton, product.DisableBuyButton)
- .Set(x => x.DisableWishlistButton, product.DisableWishlistButton)
- .Set(x => x.DisplayOrder, product.DisplayOrder)
- .Set(x => x.DisplayOrderCategory, product.DisplayOrderCategory)
- .Set(x => x.DisplayOrderBrand, product.DisplayOrderBrand)
- .Set(x => x.DisplayOrderCollection, product.DisplayOrderCollection)
- .Set(x => x.StockAvailability, product.StockAvailability)
- .Set(x => x.DisplayStockQuantity, product.DisplayStockQuantity)
- .Set(x => x.DownloadActivationTypeId, product.DownloadActivationTypeId)
- .Set(x => x.DownloadExpirationDays, product.DownloadExpirationDays)
- .Set(x => x.DownloadId, product.DownloadId)
- .Set(x => x.Flag, product.Flag)
- .Set(x => x.FullDescription, product.FullDescription)
- .Set(x => x.GiftVoucherTypeId, product.GiftVoucherTypeId)
- .Set(x => x.Gtin, product.Gtin)
- .Set(x => x.HasSampleDownload, product.HasSampleDownload)
- .Set(x => x.HasUserAgreement, product.HasUserAgreement)
- .Set(x => x.Height, product.Height)
- .Set(x => x.IncBothDate, product.IncBothDate)
- .Set(x => x.IsDownload, product.IsDownload)
- .Set(x => x.IsFreeShipping, product.IsFreeShipping)
- .Set(x => x.IsGiftVoucher, product.IsGiftVoucher)
- .Set(x => x.IsRecurring, product.IsRecurring)
- .Set(x => x.IsShipEnabled, product.IsShipEnabled)
- .Set(x => x.IsTaxExempt, product.IsTaxExempt)
- .Set(x => x.IsTele, product.IsTele)
- .Set(x => x.Length, product.Length)
- .Set(x => x.LimitedToStores, product.LimitedToStores)
- .Set(x => x.Locales, product.Locales)
- .Set(x => x.LowStockActivityId, product.LowStockActivityId)
- .Set(x => x.ManageInventoryMethodId, product.ManageInventoryMethodId)
- .Set(x => x.Mpn, product.Mpn)
- .Set(x => x.MarkAsNew, product.MarkAsNew)
- .Set(x => x.MarkAsNewStartDateTimeUtc, product.MarkAsNewStartDateTimeUtc)
- .Set(x => x.MarkAsNewEndDateTimeUtc, product.MarkAsNewEndDateTimeUtc)
- .Set(x => x.MaxEnteredPrice, product.MaxEnteredPrice)
- .Set(x => x.MaxNumberOfDownloads, product.MaxNumberOfDownloads)
- .Set(x => x.MetaDescription, product.MetaDescription)
- .Set(x => x.MetaKeywords, product.MetaKeywords)
- .Set(x => x.MetaTitle, product.MetaTitle)
- .Set(x => x.MinEnteredPrice, product.MinEnteredPrice)
- .Set(x => x.MinStockQuantity, product.MinStockQuantity)
- .Set(x => x.LowStock, (product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) || product.StockQuantity - product.ReservedQuantity <= 0)
- .Set(x => x.Name, product.Name)
- .Set(x => x.NotApprovedRatingSum, product.NotApprovedRatingSum)
- .Set(x => x.NotApprovedTotalReviews, product.NotApprovedTotalReviews)
- .Set(x => x.NotifyAdminForQuantityBelow, product.NotifyAdminForQuantityBelow)
- .Set(x => x.NotReturnable, product.NotReturnable)
- .Set(x => x.OnSale, product.OnSale)
- .Set(x => x.OldPrice, product.OldPrice)
- .Set(x => x.OrderMaximumQuantity, product.OrderMaximumQuantity)
- .Set(x => x.OrderMinimumQuantity, product.OrderMinimumQuantity)
- .Set(x => x.OverGiftAmount, product.OverGiftAmount)
- .Set(x => x.ParentGroupedProductId, product.ParentGroupedProductId)
- .Set(x => x.PreOrderDateTimeUtc, product.PreOrderDateTimeUtc)
- .Set(x => x.Price, product.Price)
- .Set(x => x.ProductCost, product.ProductCost)
- .Set(x => x.ProductLayoutId, product.ProductLayoutId)
- .Set(x => x.ProductTypeId, product.ProductTypeId)
- .Set(x => x.Published, product.Published)
- .Set(x => x.RecurringCycleLength, product.RecurringCycleLength)
- .Set(x => x.RecurringCyclePeriodId, product.RecurringCyclePeriodId)
- .Set(x => x.RecurringTotalCycles, product.RecurringTotalCycles)
- .Set(x => x.RequiredProductIds, product.RequiredProductIds)
- .Set(x => x.RequireOtherProducts, product.RequireOtherProducts)
- .Set(x => x.SampleDownloadId, product.SampleDownloadId)
- .Set(x => x.SeName, product.SeName)
- .Set(x => x.ShipSeparately, product.ShipSeparately)
- .Set(x => x.ShortDescription, product.ShortDescription)
- .Set(x => x.ShowOnHomePage, product.ShowOnHomePage)
- .Set(x => x.BestSeller, product.BestSeller)
- .Set(x => x.Sku, product.Sku)
- .Set(x => x.StartPrice, product.StartPrice)
- .Set(x => x.StockQuantity, product.StockQuantity)
- .Set(x => x.ReservedQuantity, product.ReservedQuantity)
- .Set(x => x.Stores, product.Stores)
- .Set(x => x.LimitedToGroups, product.LimitedToGroups)
- .Set(x => x.TaxCategoryId, product.TaxCategoryId)
- .Set(x => x.UnitId, product.UnitId)
- .Set(x => x.UnlimitedDownloads, product.UnlimitedDownloads)
- .Set(x => x.UseMultipleWarehouses, product.UseMultipleWarehouses)
- .Set(x => x.UserAgreementText, product.UserAgreementText)
- .Set(x => x.BrandId, product.BrandId)
- .Set(x => x.VendorId, product.VendorId)
- .Set(x => x.VisibleIndividually, product.VisibleIndividually)
- .Set(x => x.WarehouseId, product.WarehouseId)
- .Set(x => x.Weight, product.Weight)
- .Set(x => x.Width, product.Width)
- .Set(x => x.UserFields, product.UserFields)
- .Set(x => x.Ticks, DateTime.UtcNow.Ticks);
-
- await _productRepository.UpdateOneAsync(x => x.Id == product.Id, update);
-
- if (!oldProduct.AdditionalShippingCharge.Equals(product.AdditionalShippingCharge) ||
- oldProduct.IsFreeShipping != product.IsFreeShipping ||
- oldProduct.IsGiftVoucher != product.IsGiftVoucher ||
- oldProduct.IsShipEnabled != product.IsShipEnabled ||
- oldProduct.IsTaxExempt != product.IsTaxExempt ||
- oldProduct.IsRecurring != product.IsRecurring
- )
- {
- await _mediator.Publish(new UpdateProductOnCartEvent(product));
- }
+ /// <summary>
+ /// Inserts a product
+ /// </summary>
+ /// <param name="product">Product</param>
+ public virtual async Task InsertProduct(Product product)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- switch (oldProduct.Published)
- {
- //raise event
- case false when product.Published:
- await _mediator.Publish(new ProductPublishEvent(product));
- break;
- case true when !product.Published:
- await _mediator.Publish(new ProductUnPublishEvent(product));
- break;
- }
+ //insert
+ await _productRepository.InsertAsync(product);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_PATTERN);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_HOMEPAGE_PATTERN);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);
+ //event notification
+ await _mediator.EntityInserted(product);
+ }
- //event notification
- await _mediator.EntityUpdated(product);
+ /// <summary>
+ /// Updates the product
+ /// </summary>
+ /// <param name="product">Product</param>
+ public virtual async Task UpdateProduct(Product product)
+ {
+ ArgumentNullException.ThrowIfNull(product);
+
+ var oldProduct = await _productRepository.GetByIdAsync(product.Id);
+ //update
+ var update = UpdateBuilder<Product>.Create()
+ .Set(x => x.AdditionalShippingCharge, product.AdditionalShippingCharge)
+ .Set(x => x.AdminComment, product.AdminComment)
+ .Set(x => x.AllowOutOfStockSubscriptions, product.AllowOutOfStockSubscriptions)
+ .Set(x => x.AllowCustomerReviews, product.AllowCustomerReviews)
+ .Set(x => x.AllowedQuantities, product.AllowedQuantities)
+ .Set(x => x.ApprovedRatingSum, product.ApprovedRatingSum)
+ .Set(x => x.ApprovedTotalReviews, product.ApprovedTotalReviews)
+ .Set(x => x.AutoAddRequiredProducts, product.AutoAddRequiredProducts)
+ .Set(x => x.AvailableEndDateTimeUtc, product.AvailableEndDateTimeUtc)
+ .Set(x => x.AvailableForPreOrder, product.AvailableForPreOrder)
+ .Set(x => x.AvailableStartDateTimeUtc, product.AvailableStartDateTimeUtc)
+ .Set(x => x.BackorderModeId, product.BackorderModeId)
+ .Set(x => x.BasepriceAmount, product.BasepriceAmount)
+ .Set(x => x.BasepriceBaseAmount, product.BasepriceBaseAmount)
+ .Set(x => x.BasepriceBaseUnitId, product.BasepriceBaseUnitId)
+ .Set(x => x.BasepriceEnabled, product.BasepriceEnabled)
+ .Set(x => x.BasepriceUnitId, product.BasepriceUnitId)
+ .Set(x => x.CallForPrice, product.CallForPrice)
+ .Set(x => x.CatalogPrice, product.CatalogPrice)
+ .Set(x => x.EnteredPrice, product.EnteredPrice)
+ .Set(x => x.CustomerGroups, product.CustomerGroups)
+ .Set(x => x.DeliveryDateId, product.DeliveryDateId)
+ .Set(x => x.DisableBuyButton, product.DisableBuyButton)
+ .Set(x => x.DisableWishlistButton, product.DisableWishlistButton)
+ .Set(x => x.DisplayOrder, product.DisplayOrder)
+ .Set(x => x.DisplayOrderCategory, product.DisplayOrderCategory)
+ .Set(x => x.DisplayOrderBrand, product.DisplayOrderBrand)
+ .Set(x => x.DisplayOrderCollection, product.DisplayOrderCollection)
+ .Set(x => x.StockAvailability, product.StockAvailability)
+ .Set(x => x.DisplayStockQuantity, product.DisplayStockQuantity)
+ .Set(x => x.DownloadActivationTypeId, product.DownloadActivationTypeId)
+ .Set(x => x.DownloadExpirationDays, product.DownloadExpirationDays)
+ .Set(x => x.DownloadId, product.DownloadId)
+ .Set(x => x.Flag, product.Flag)
+ .Set(x => x.FullDescription, product.FullDescription)
+ .Set(x => x.GiftVoucherTypeId, product.GiftVoucherTypeId)
+ .Set(x => x.Gtin, product.Gtin)
+ .Set(x => x.HasSampleDownload, product.HasSampleDownload)
+ .Set(x => x.HasUserAgreement, product.HasUserAgreement)
+ .Set(x => x.Height, product.Height)
+ .Set(x => x.IncBothDate, product.IncBothDate)
+ .Set(x => x.IsDownload, product.IsDownload)
+ .Set(x => x.IsFreeShipping, product.IsFreeShipping)
+ .Set(x => x.IsGiftVoucher, product.IsGiftVoucher)
+ .Set(x => x.IsRecurring, product.IsRecurring)
+ .Set(x => x.IsShipEnabled, product.IsShipEnabled)
+ .Set(x => x.IsTaxExempt, product.IsTaxExempt)
+ .Set(x => x.IsTele, product.IsTele)
+ .Set(x => x.Length, product.Length)
+ .Set(x => x.LimitedToStores, product.LimitedToStores)
+ .Set(x => x.Locales, product.Locales)
+ .Set(x => x.LowStockActivityId, product.LowStockActivityId)
+ .Set(x => x.ManageInventoryMethodId, product.ManageInventoryMethodId)
+ .Set(x => x.Mpn, product.Mpn)
+ .Set(x => x.MarkAsNew, product.MarkAsNew)
+ .Set(x => x.MarkAsNewStartDateTimeUtc, product.MarkAsNewStartDateTimeUtc)
+ .Set(x => x.MarkAsNewEndDateTimeUtc, product.MarkAsNewEndDateTimeUtc)
+ .Set(x => x.MaxEnteredPrice, product.MaxEnteredPrice)
+ .Set(x => x.MaxNumberOfDownloads, product.MaxNumberOfDownloads)
+ .Set(x => x.MetaDescription, product.MetaDescription)
+ .Set(x => x.MetaKeywords, product.MetaKeywords)
+ .Set(x => x.MetaTitle, product.MetaTitle)
+ .Set(x => x.MinEnteredPrice, product.MinEnteredPrice)
+ .Set(x => x.MinStockQuantity, product.MinStockQuantity)
+ .Set(x => x.LowStock,
+ (product.MinStockQuantity > 0 &&
+ product.MinStockQuantity >= product.StockQuantity - product.ReservedQuantity) ||
+ product.StockQuantity - product.ReservedQuantity <= 0)
+ .Set(x => x.Name, product.Name)
+ .Set(x => x.NotApprovedRatingSum, product.NotApprovedRatingSum)
+ .Set(x => x.NotApprovedTotalReviews, product.NotApprovedTotalReviews)
+ .Set(x => x.NotifyAdminForQuantityBelow, product.NotifyAdminForQuantityBelow)
+ .Set(x => x.NotReturnable, product.NotReturnable)
+ .Set(x => x.OnSale, product.OnSale)
+ .Set(x => x.OldPrice, product.OldPrice)
+ .Set(x => x.OrderMaximumQuantity, product.OrderMaximumQuantity)
+ .Set(x => x.OrderMinimumQuantity, product.OrderMinimumQuantity)
+ .Set(x => x.OverGiftAmount, product.OverGiftAmount)
+ .Set(x => x.ParentGroupedProductId, product.ParentGroupedProductId)
+ .Set(x => x.PreOrderDateTimeUtc, product.PreOrderDateTimeUtc)
+ .Set(x => x.Price, product.Price)
+ .Set(x => x.ProductCost, product.ProductCost)
+ .Set(x => x.ProductLayoutId, product.ProductLayoutId)
+ .Set(x => x.ProductTypeId, product.ProductTypeId)
+ .Set(x => x.Published, product.Published)
+ .Set(x => x.RecurringCycleLength, product.RecurringCycleLength)
+ .Set(x => x.RecurringCyclePeriodId, product.RecurringCyclePeriodId)
+ .Set(x => x.RecurringTotalCycles, product.RecurringTotalCycles)
+ .Set(x => x.RequiredProductIds, product.RequiredProductIds)
+ .Set(x => x.RequireOtherProducts, product.RequireOtherProducts)
+ .Set(x => x.SampleDownloadId, product.SampleDownloadId)
+ .Set(x => x.SeName, product.SeName)
+ .Set(x => x.ShipSeparately, product.ShipSeparately)
+ .Set(x => x.ShortDescription, product.ShortDescription)
+ .Set(x => x.ShowOnHomePage, product.ShowOnHomePage)
+ .Set(x => x.BestSeller, product.BestSeller)
+ .Set(x => x.Sku, product.Sku)
+ .Set(x => x.StartPrice, product.StartPrice)
+ .Set(x => x.StockQuantity, product.StockQuantity)
+ .Set(x => x.ReservedQuantity, product.ReservedQuantity)
+ .Set(x => x.Stores, product.Stores)
+ .Set(x => x.LimitedToGroups, product.LimitedToGroups)
+ .Set(x => x.TaxCategoryId, product.TaxCategoryId)
+ .Set(x => x.UnitId, product.UnitId)
+ .Set(x => x.UnlimitedDownloads, product.UnlimitedDownloads)
+ .Set(x => x.UseMultipleWarehouses, product.UseMultipleWarehouses)
+ .Set(x => x.UserAgreementText, product.UserAgreementText)
+ .Set(x => x.BrandId, product.BrandId)
+ .Set(x => x.VendorId, product.VendorId)
+ .Set(x => x.VisibleIndividually, product.VisibleIndividually)
+ .Set(x => x.WarehouseId, product.WarehouseId)
+ .Set(x => x.Weight, product.Weight)
+ .Set(x => x.Width, product.Width)
+ .Set(x => x.UserFields, product.UserFields)
+ .Set(x => x.Ticks, DateTime.UtcNow.Ticks);
+
+ await _productRepository.UpdateOneAsync(x => x.Id == product.Id, update);
+
+ if (!oldProduct.AdditionalShippingCharge.Equals(product.AdditionalShippingCharge) ||
+ oldProduct.IsFreeShipping != product.IsFreeShipping ||
+ oldProduct.IsGiftVoucher != product.IsGiftVoucher ||
+ oldProduct.IsShipEnabled != product.IsShipEnabled ||
+ oldProduct.IsTaxExempt != product.IsTaxExempt ||
+ oldProduct.IsRecurring != product.IsRecurring
+ )
+ await _mediator.Publish(new UpdateProductOnCartEvent(product));
+
+ switch (oldProduct.Published)
+ {
+ //raise event
+ case false when product.Published:
+ await _mediator.Publish(new ProductPublishEvent(product));
+ break;
+ case true when !product.Published:
+ await _mediator.Publish(new ProductUnPublishEvent(product));
+ break;
}
- public virtual async Task UpdateProductField<T>(Product product,
- Expression<Func<Product, T>> expression, T value)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- //update field
- await _productRepository.UpdateField(product.Id, expression, value);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_PATTERN);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_GROUP_PATTERN);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_HOMEPAGE_PATTERN);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- //event notification
- await _mediator.EntityUpdated(product);
+ public virtual async Task UpdateProductField<T>(Product product,
+ Expression<Func<Product, T>> expression, T value)
+ {
+ ArgumentNullException.ThrowIfNull(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)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //update field
+ await _productRepository.UpdateField(product.Id, expression, value);
- //inc field
- await _productRepository.IncField(product.Id, expression, value);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- /// <summary>
- /// Delete a product
- /// </summary>
- /// <param name="product">Product</param>
- public virtual async Task DeleteProduct(Product product)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- //deleted product
- await _productRepository.DeleteAsync(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)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //inc field
+ await _productRepository.IncField(product.Id, expression, value);
+ }
- //event notification
- await _mediator.EntityDeleted(product);
- }
+ /// <summary>
+ /// Delete a product
+ /// </summary>
+ /// <param name="product">Product</param>
+ public virtual async Task DeleteProduct(Product product)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- public virtual async Task UnPublishProduct(Product product)
- {
- var update = UpdateBuilder<Product>.Create()
- .Set(x => x.Published, false)
- .Set(x => x.UpdatedOnUtc, DateTime.UtcNow);
+ //deleted product
+ await _productRepository.DeleteAsync(product);
- await _productRepository.UpdateOneAsync(x => x.Id == product.Id, update);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ //event notification
+ await _mediator.EntityDeleted(product);
+ }
- //event
- await _mediator.Publish(new ProductUnPublishEvent(product));
+ public virtual async Task UnPublishProduct(Product product)
+ {
+ var update = UpdateBuilder<Product>.Create()
+ .Set(x => x.Published, false)
+ .Set(x => x.UpdatedOnUtc, DateTime.UtcNow);
- //event notification
- await _mediator.EntityUpdated(product);
- }
+ await _productRepository.UpdateOneAsync(x => x.Id == product.Id, update);
- /// <summary>
- /// Get (visible) product number in certain category
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="categoryIds">Category identifiers</param>
- /// <param name="storeId">Store identifier; "" to load all records</param>
- /// <param name="ignoreAcl">Ignore acl</param>
- /// <param name="ignoreStore">Ignore store</param>
- /// <returns>Product number</returns>
- public virtual int GetCategoryProductNumber(Customer customer, IList<string> categoryIds = null, string storeId = "", bool ignoreAcl = true, bool ignoreStore = true)
- {
- //validate "categoryIds" parameter
- if (categoryIds != null && categoryIds.Contains(""))
- categoryIds.Remove("");
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- var query = from p in _productRepository.Table
- select p;
+ //event
+ await _mediator.Publish(new ProductUnPublishEvent(product));
- query = query.Where(p => p.Published && p.VisibleIndividually);
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- ////category filtering
- if (categoryIds != null && categoryIds.Any())
- {
- query = query.Where(p => p.ProductCategories.Any(x => categoryIds.Contains(x.CategoryId)));
- }
+ /// <summary>
+ /// Get (visible) product number in certain category
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="categoryIds">Category identifiers</param>
+ /// <param name="storeId">Store identifier; "" to load all records</param>
+ /// <param name="ignoreAcl">Ignore acl</param>
+ /// <param name="ignoreStore">Ignore store</param>
+ /// <returns>Product number</returns>
+ public virtual int GetCategoryProductNumber(Customer customer, IList<string> categoryIds = null,
+ string storeId = "", bool ignoreAcl = true, bool ignoreStore = true)
+ {
+ //validate "categoryIds" parameter
+ if (categoryIds != null && categoryIds.Contains(""))
+ categoryIds.Remove("");
- if (!ignoreAcl)
- {
- //ACL (access control list)
- var allowedCustomerGroupsIds = customer.GetCustomerGroupIds();
- query = from p in query
- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
- select p;
- }
+ var query = from p in _productRepository.Table
+ select p;
- if (!string.IsNullOrEmpty(storeId) && !ignoreStore)
- {
- //Limited to stores rules
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
+ query = query.Where(p => p.Published && p.VisibleIndividually);
- return Convert.ToInt32(query.Count());
+ ////category filtering
+ if (categoryIds != null && categoryIds.Any())
+ query = query.Where(p => p.ProductCategories.Any(x => categoryIds.Contains(x.CategoryId)));
+ if (!ignoreAcl)
+ {
+ //ACL (access control list)
+ var allowedCustomerGroupsIds = customer.GetCustomerGroupIds();
+ query = from p in query
+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
+ select p;
}
- /// <summary>
- /// Search products
- /// </summary>
- /// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="categoryIds">Category identifiers</param>
- /// <param name="brandId">Brand ident</param>
- /// <param name="collectionId">Collection identifier; "" to load all records</param>
- /// <param name="storeId">Store identifier; "" to load all records</param>
- /// <param name="vendorId">Vendor identifier; "" to load all records</param>
- /// <param name="warehouseId">Warehouse identifier; "" to load all records</param>
- /// <param name="productType">Product type; "" to load all records</param>
- /// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
- /// <param name="showOnHomePage">Show on home page</param>
- /// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and collections). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>
- /// <param name="priceMin">Minimum price; null to load all records</param>
- /// <param name="priceMax">Maximum price; null to load all records</param>
- /// <param name="productTag">Product tag name; "" to load all records</param>
- /// <param name="keywords">Keywords</param>
- /// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
- /// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
- /// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
- /// <param name="languageId">Language identifier (search for text searching)</param>
- /// <param name="filteredSpecs">Filtered product specification identifiers</param>
- /// <param name="specificationOptions">Specification options identifiers</param>
- /// <param name="orderBy">Order by</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <param name="overridePublished">
- /// null - process "Published" property according to "showHidden" parameter
- /// true - load only "Published" products
- /// false - load only "Unpublished" products
- /// </param>
- /// <param name="markedAsNewOnly">Marked as new</param>
- /// <returns>Products</returns>
- public virtual async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)> SearchProducts(
+ if (!string.IsNullOrEmpty(storeId) && !ignoreStore)
+ //Limited to stores rules
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
+
+ return Convert.ToInt32(query.Count());
+ }
+
+ /// <summary>
+ /// Search products
+ /// </summary>
+ /// <param name="loadFilterableSpecificationAttributeOptionIds">
+ /// A value indicating whether we should load the specification
+ /// attribute option identifiers applied to loaded products (all pages)
+ /// </param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="categoryIds">Category identifiers</param>
+ /// <param name="brandId">Brand ident</param>
+ /// <param name="collectionId">Collection identifier; "" to load all records</param>
+ /// <param name="storeId">Store identifier; "" to load all records</param>
+ /// <param name="vendorId">Vendor identifier; "" to load all records</param>
+ /// <param name="warehouseId">Warehouse identifier; "" to load all records</param>
+ /// <param name="productType">Product type; "" to load all records</param>
+ /// <param name="visibleIndividuallyOnly">
+ /// A values indicating whether to load only products marked as "visible
+ /// individually"; "false" to load all records; "true" to load "visible individually" only
+ /// </param>
+ /// <param name="showOnHomePage">Show on home page</param>
+ /// <param name="featuredProducts">
+ /// A value indicating whether loaded products are marked as featured (relates only to
+ /// categories and collections). 0 to load featured products only, 1 to load not featured products only, null to load
+ /// all products
+ /// </param>
+ /// <param name="priceMin">Minimum price; null to load all records</param>
+ /// <param name="priceMax">Maximum price; null to load all records</param>
+ /// <param name="productTag">Product tag name; "" to load all records</param>
+ /// <param name="keywords">Keywords</param>
+ /// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
+ /// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
+ /// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
+ /// <param name="languageId">Language identifier (search for text searching)</param>
+ /// <param name="filteredSpecs">Filtered product specification identifiers</param>
+ /// <param name="specificationOptions">Specification options identifiers</param>
+ /// <param name="orderBy">Order by</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <param name="overridePublished">
+ /// null - process "Published" property according to "showHidden" parameter
+ /// true - load only "Published" products
+ /// false - load only "Unpublished" products
+ /// </param>
+ /// <param name="markedAsNewOnly">Marked as new</param>
+ /// <returns>Products</returns>
+ public virtual async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)>
+ SearchProducts(
bool loadFilterableSpecificationAttributeOptionIds = false,
int pageIndex = 0,
int pageSize = int.MaxValue,
@@ -508,685 +521,685 @@ namespace Grand.Business.Catalog.Services.Products
ProductSortingEnum orderBy = ProductSortingEnum.Position,
bool showHidden = false,
bool? overridePublished = null)
- {
+ {
+ var model = await _mediator.Send(new GetSearchProductsQuery {
+ Customer = _workContext.CurrentCustomer,
+ LoadFilterableSpecificationAttributeOptionIds = loadFilterableSpecificationAttributeOptionIds,
+ PageIndex = pageIndex,
+ PageSize = pageSize,
+ CategoryIds = categoryIds,
+ BrandId = brandId,
+ CollectionId = collectionId,
+ StoreId = storeId,
+ VendorId = vendorId,
+ WarehouseId = warehouseId,
+ ProductType = productType,
+ VisibleIndividuallyOnly = visibleIndividuallyOnly,
+ MarkedAsNewOnly = markedAsNewOnly,
+ ShowOnHomePage = showOnHomePage,
+ FeaturedProducts = featuredProducts,
+ PriceMin = priceMin,
+ PriceMax = priceMax,
+ ProductTag = productTag,
+ Keywords = keywords,
+ SearchDescriptions = searchDescriptions,
+ SearchSku = searchSku,
+ SearchProductTags = searchProductTags,
+ LanguageId = languageId,
+ FilteredSpecs = filteredSpecs,
+ SpecificationOptions = specificationOptions,
+ OrderBy = orderBy,
+ ShowHidden = showHidden,
+ OverridePublished = overridePublished
+ });
+
+ return model;
+ }
- var model = await _mediator.Send(new GetSearchProductsQuery {
- Customer = _workContext.CurrentCustomer,
- LoadFilterableSpecificationAttributeOptionIds = loadFilterableSpecificationAttributeOptionIds,
- PageIndex = pageIndex,
- PageSize = pageSize,
- CategoryIds = categoryIds,
- BrandId = brandId,
- CollectionId = collectionId,
- StoreId = storeId,
- VendorId = vendorId,
- WarehouseId = warehouseId,
- ProductType = productType,
- VisibleIndividuallyOnly = visibleIndividuallyOnly,
- MarkedAsNewOnly = markedAsNewOnly,
- ShowOnHomePage = showOnHomePage,
- FeaturedProducts = featuredProducts,
- PriceMin = priceMin,
- PriceMax = priceMax,
- ProductTag = productTag,
- Keywords = keywords,
- SearchDescriptions = searchDescriptions,
- SearchSku = searchSku,
- SearchProductTags = searchProductTags,
- LanguageId = languageId,
- FilteredSpecs = filteredSpecs,
- SpecificationOptions = specificationOptions,
- OrderBy = orderBy,
- ShowHidden = showHidden,
- OverridePublished = overridePublished
- });
-
- return model;
- }
+ /// <summary>
+ /// Gets products by product attribute
+ /// </summary>
+ /// <param name="productAttributeId">Product attribute identifier</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Products</returns>
+ public virtual async Task<IPagedList<Product>> GetProductsByProductAttributeId(string productAttributeId,
+ int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = from p in _productRepository.Table
+ select p;
+ query = query.Where(x => x.ProductAttributeMappings.Any(y => y.ProductAttributeId == productAttributeId));
+ query = query.OrderBy(x => x.Name);
- /// <summary>
- /// Gets products by product attribute
- /// </summary>
- /// <param name="productAttributeId">Product attribute identifier</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Products</returns>
- public virtual async Task<IPagedList<Product>> GetProductsByProductAttributeId(string productAttributeId,
- int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _productRepository.Table
- select p;
- query = query.Where(x => x.ProductAttributeMappings.Any(y => y.ProductAttributeId == productAttributeId));
- query = query.OrderBy(x => x.Name);
+ return await PagedList<Product>.Create(query, pageIndex, pageSize);
+ }
- return await PagedList<Product>.Create(query, pageIndex, pageSize);
- }
+ /// <summary>
+ /// Gets associated products
+ /// </summary>
+ /// <param name="parentGroupedProductId">Parent product identifier (used with grouped products)</param>
+ /// <param name="storeId">Store identifier; "" to load all records</param>
+ /// <param name="vendorId">Vendor identifier; "" to load all records</param>
+ /// <param name="showHidden">Show hidden</param>
+ /// <returns>Products</returns>
+ public virtual async Task<IList<Product>> GetAssociatedProducts(string parentGroupedProductId,
+ string storeId = "", string vendorId = "", bool showHidden = false)
+ {
+ var query = from p in _productRepository.Table
+ select p;
+
+ query = query.Where(p => p.ParentGroupedProductId == parentGroupedProductId);
- /// <summary>
- /// Gets associated products
- /// </summary>
- /// <param name="parentGroupedProductId">Parent product identifier (used with grouped products)</param>
- /// <param name="storeId">Store identifier; "" to load all records</param>
- /// <param name="vendorId">Vendor identifier; "" to load all records</param>
- /// <param name="showHidden">Show hidden</param>
- /// <returns>Products</returns>
- public virtual async Task<IList<Product>> GetAssociatedProducts(string parentGroupedProductId,
- string storeId = "", string vendorId = "", bool showHidden = false)
+ if (!showHidden) query = query.Where(p => p.Published);
+ if (!showHidden)
{
+ var nowUtc = DateTime.UtcNow;
+ //available dates
+ query = query.Where(p =>
+ (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&
+ (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));
+ }
- var query = from p in _productRepository.Table
- select p;
+ //vendor filtering
+ if (!string.IsNullOrEmpty(vendorId)) query = query.Where(p => p.VendorId == vendorId);
- query = query.Where(p => p.ParentGroupedProductId == parentGroupedProductId);
+ var products = query.OrderBy(x => x.DisplayOrder).ToList();
- if (!showHidden)
- {
- query = query.Where(p => p.Published);
- }
- if (!showHidden)
- {
- var nowUtc = DateTime.UtcNow;
- //available dates
- query = query.Where(p =>
- (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&
- (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));
+ //ACL mapping
+ if (!showHidden)
+ products = products.Where(x => _aclService.Authorize(x, _workContext.CurrentCustomer)).ToList();
+ //Store acl
+ if (!showHidden && !string.IsNullOrEmpty(storeId))
+ products = products.Where(x => _aclService.Authorize(x, storeId)).ToList();
- }
- //vendor filtering
- if (!string.IsNullOrEmpty(vendorId))
- {
- query = query.Where(p => p.VendorId == vendorId);
- }
+ return await Task.FromResult(products);
+ }
- var products = query.OrderBy(x => x.DisplayOrder).ToList();
+ /// <summary>
+ /// Gets a product by SKU
+ /// </summary>
+ /// <param name="sku">SKU</param>
+ /// <returns>Product</returns>
+ public virtual async Task<Product> GetProductBySku(string sku)
+ {
+ if (string.IsNullOrEmpty(sku))
+ return null;
- //ACL mapping
- if (!showHidden)
- {
- products = products.Where(x => _aclService.Authorize(x, _workContext.CurrentCustomer)).ToList();
- }
- //Store acl
- if (!showHidden && !string.IsNullOrEmpty(storeId))
- {
- products = products.Where(x => _aclService.Authorize(x, storeId)).ToList();
- }
+ sku = sku.Trim();
+ return await _productRepository.GetOneAsync(x => x.Sku == sku);
+ }
- return await Task.FromResult(products);
- }
+ public virtual async Task UpdateAssociatedProduct(Product product)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- /// <summary>
- /// Gets a product by SKU
- /// </summary>
- /// <param name="sku">SKU</param>
- /// <returns>Product</returns>
- public virtual async Task<Product> GetProductBySku(string sku)
- {
- if (string.IsNullOrEmpty(sku))
- return null;
+ var update = UpdateBuilder<Product>.Create()
+ .Set(x => x.DisplayOrder, product.DisplayOrder)
+ .Set(x => x.ParentGroupedProductId, product.ParentGroupedProductId);
- sku = sku.Trim();
- return await _productRepository.GetOneAsync(x => x.Sku == sku);
- }
+ await _productRepository.UpdateManyAsync(x => x.Id == product.Id, update);
- public virtual async Task UpdateAssociatedProduct(Product product)
- {
- ArgumentNullException.ThrowIfNull(product);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
- var update = UpdateBuilder<Product>.Create()
- .Set(x => x.DisplayOrder, product.DisplayOrder)
- .Set(x => x.ParentGroupedProductId, product.ParentGroupedProductId);
+ //event notification
+ await _mediator.EntityUpdated(product);
+ }
- await _productRepository.UpdateManyAsync(x => x.Id == product.Id, update);
+ #endregion
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, product.Id));
+ #region Related products
- //event notification
- await _mediator.EntityUpdated(product);
+ /// <summary>
+ /// Insert a related product
+ /// </summary>
+ /// <param name="relatedProduct">Related product</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertRelatedProduct(RelatedProduct relatedProduct, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(relatedProduct);
- }
+ await _productRepository.AddToSet(productId, x => x.RelatedProducts, relatedProduct);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #region Related products
+ //event notification
+ await _mediator.EntityInserted(relatedProduct);
+ }
- /// <summary>
- /// Insert a related product
- /// </summary>
- /// <param name="relatedProduct">Related product</param>
- /// <param name="productId">Product ident</param>
+ /// <summary>
+ /// Deletes a related product
+ /// </summary>
+ /// <param name="relatedProduct">Related product</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteRelatedProduct(RelatedProduct relatedProduct, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(relatedProduct);
- public virtual async Task InsertRelatedProduct(RelatedProduct relatedProduct, string productId)
- {
- ArgumentNullException.ThrowIfNull(relatedProduct);
+ await _productRepository.PullFilter(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id);
- await _productRepository.AddToSet(productId, x => x.RelatedProducts, relatedProduct);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityDeleted(relatedProduct);
+ }
- //event notification
- await _mediator.EntityInserted(relatedProduct);
- }
- /// <summary>
- /// Deletes a related product
- /// </summary>
- /// <param name="relatedProduct">Related product</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteRelatedProduct(RelatedProduct relatedProduct, string productId)
- {
- ArgumentNullException.ThrowIfNull(relatedProduct);
+ /// <summary>
+ /// Updates a related product
+ /// </summary>
+ /// <param name="relatedProduct">Related product</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateRelatedProduct(RelatedProduct relatedProduct, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(relatedProduct);
- await _productRepository.PullFilter(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id);
+ await _productRepository.UpdateToSet(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id,
+ relatedProduct);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityDeleted(relatedProduct);
- }
+ //event notification
+ await _mediator.EntityUpdated(relatedProduct);
+ }
- /// <summary>
- /// Updates a related product
- /// </summary>
- /// <param name="relatedProduct">Related product</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateRelatedProduct(RelatedProduct relatedProduct, string productId)
- {
- ArgumentNullException.ThrowIfNull(relatedProduct);
+ #endregion
- await _productRepository.UpdateToSet(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id, relatedProduct);
+ #region Similar products
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ public virtual async Task InsertSimilarProduct(SimilarProduct similarProduct)
+ {
+ ArgumentNullException.ThrowIfNull(similarProduct);
- //event notification
- await _mediator.EntityUpdated(relatedProduct);
- }
+ await _productRepository.AddToSet(similarProduct.ProductId1, x => x.SimilarProducts, similarProduct);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
- #region Similar products
+ //event notification
+ await _mediator.EntityInserted(similarProduct);
+ }
- public virtual async Task InsertSimilarProduct(SimilarProduct similarProduct)
- {
- ArgumentNullException.ThrowIfNull(similarProduct);
+ /// <summary>
+ /// Updates a similar product
+ /// </summary>
+ /// <param name="similarProduct">Similar product</param>
+ public virtual async Task UpdateSimilarProduct(SimilarProduct similarProduct)
+ {
+ ArgumentNullException.ThrowIfNull(similarProduct);
- await _productRepository.AddToSet(similarProduct.ProductId1, x => x.SimilarProducts, similarProduct);
+ await _productRepository.UpdateToSet(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id,
+ similarProduct.Id, similarProduct);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
- //event notification
- await _mediator.EntityInserted(similarProduct);
- }
+ //event notification
+ await _mediator.EntityUpdated(similarProduct);
+ }
- /// <summary>
- /// Updates a similar product
- /// </summary>
- /// <param name="similarProduct">Similar product</param>
- public virtual async Task UpdateSimilarProduct(SimilarProduct similarProduct)
- {
- ArgumentNullException.ThrowIfNull(similarProduct);
+ /// <summary>
+ /// Deletes a similar product
+ /// </summary>
+ /// <param name="similarProduct">Similar product</param>
+ public virtual async Task DeleteSimilarProduct(SimilarProduct similarProduct)
+ {
+ ArgumentNullException.ThrowIfNull(similarProduct);
- await _productRepository.UpdateToSet(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id, similarProduct.Id, similarProduct);
+ await _productRepository.PullFilter(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id,
+ similarProduct.Id);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
- //event notification
- await _mediator.EntityUpdated(similarProduct);
- }
- /// <summary>
- /// Deletes a similar product
- /// </summary>
- /// <param name="similarProduct">Similar product</param>
- public virtual async Task DeleteSimilarProduct(SimilarProduct similarProduct)
- {
- ArgumentNullException.ThrowIfNull(similarProduct);
+ //event notification
+ await _mediator.EntityDeleted(similarProduct);
+ }
- await _productRepository.PullFilter(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id, similarProduct.Id);
+ #endregion
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, similarProduct.ProductId1));
+ #region Bundle product
- //event notification
- await _mediator.EntityDeleted(similarProduct);
- }
+ /// <summary>
+ /// Inserts a bundle product
+ /// </summary>
+ /// <param name="bundleProduct">Bundle product</param>
+ /// <param name="productBundleId">Product bundle ident</param>
+ public virtual async Task InsertBundleProduct(BundleProduct bundleProduct, string productBundleId)
+ {
+ ArgumentNullException.ThrowIfNull(bundleProduct);
- #endregion
+ await _productRepository.AddToSet(productBundleId, x => x.BundleProducts, bundleProduct);
- #region Bundle product
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
- /// <summary>
- /// Inserts a bundle product
- /// </summary>
- /// <param name="bundleProduct">Bundle product</param>
- /// <param name="productBundleId">Product bundle ident</param>
- public virtual async Task InsertBundleProduct(BundleProduct bundleProduct, string productBundleId)
- {
- ArgumentNullException.ThrowIfNull(bundleProduct);
+ //event notification
+ await _mediator.EntityInserted(bundleProduct);
+ }
- await _productRepository.AddToSet(productBundleId, x => x.BundleProducts, bundleProduct);
+ /// <summary>
+ /// Updates a bundle product
+ /// </summary>
+ /// <param name="bundleProduct">Bundle product</param>
+ /// <param name="productBundleId">Product bundle ident</param>
+ public virtual async Task UpdateBundleProduct(BundleProduct bundleProduct, string productBundleId)
+ {
+ ArgumentNullException.ThrowIfNull(bundleProduct);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
+ await _productRepository.UpdateToSet(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id,
+ bundleProduct);
- //event notification
- await _mediator.EntityInserted(bundleProduct);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
- }
+ //event notification
+ await _mediator.EntityUpdated(bundleProduct);
+ }
- /// <summary>
- /// Updates a bundle product
- /// </summary>
- /// <param name="bundleProduct">Bundle product</param>
- /// <param name="productBundleId">Product bundle ident</param>
- public virtual async Task UpdateBundleProduct(BundleProduct bundleProduct, string productBundleId)
- {
- ArgumentNullException.ThrowIfNull(bundleProduct);
+ /// <summary>
+ /// Deletes a bundle product
+ /// </summary>
+ /// <param name="bundleProduct">Bundle product</param>
+ /// <param name="productBundleId">Product bundle ident</param>
+ public virtual async Task DeleteBundleProduct(BundleProduct bundleProduct, string productBundleId)
+ {
+ ArgumentNullException.ThrowIfNull(bundleProduct);
- await _productRepository.UpdateToSet(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id, bundleProduct);
+ await _productRepository.PullFilter(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
- //event notification
- await _mediator.EntityUpdated(bundleProduct);
+ //event notification
+ await _mediator.EntityDeleted(bundleProduct);
+ }
- }
- /// <summary>
- /// Deletes a bundle product
- /// </summary>
- /// <param name="bundleProduct">Bundle product</param>
- /// <param name="productBundleId">Product bundle ident</param>
- public virtual async Task DeleteBundleProduct(BundleProduct bundleProduct, string productBundleId)
- {
- ArgumentNullException.ThrowIfNull(bundleProduct);
+ #endregion
- await _productRepository.PullFilter(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id);
+ #region Cross-sell products
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productBundleId));
+ /// <summary>
+ /// Inserts a cross-sell product
+ /// </summary>
+ /// <param name="crossSellProduct">Cross-sell product</param>
+ public virtual async Task InsertCrossSellProduct(CrossSellProduct crossSellProduct)
+ {
+ ArgumentNullException.ThrowIfNull(crossSellProduct);
- //event notification
- await _mediator.EntityDeleted(bundleProduct);
- }
+ await _productRepository.AddToSet(crossSellProduct.ProductId1, x => x.CrossSellProduct,
+ crossSellProduct.ProductId2);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, crossSellProduct.ProductId1));
- #region Cross-sell products
+ //event notification
+ await _mediator.EntityInserted(crossSellProduct);
+ }
- /// <summary>
- /// Inserts a cross-sell product
- /// </summary>
- /// <param name="crossSellProduct">Cross-sell product</param>
- public virtual async Task InsertCrossSellProduct(CrossSellProduct crossSellProduct)
- {
- ArgumentNullException.ThrowIfNull(crossSellProduct);
+ /// <summary>
+ /// Deletes a cross-sell product
+ /// </summary>
+ /// <param name="crossSellProduct">Cross-sell identifier</param>
+ public virtual async Task DeleteCrossSellProduct(CrossSellProduct crossSellProduct)
+ {
+ ArgumentNullException.ThrowIfNull(crossSellProduct);
- await _productRepository.AddToSet(crossSellProduct.ProductId1, x => x.CrossSellProduct, crossSellProduct.ProductId2);
+ await _productRepository.Pull(crossSellProduct.ProductId1, x => x.CrossSellProduct,
+ crossSellProduct.ProductId2);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, crossSellProduct.ProductId1));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, crossSellProduct.ProductId1));
- //event notification
- await _mediator.EntityInserted(crossSellProduct);
- }
+ //event notification
+ await _mediator.EntityDeleted(crossSellProduct);
+ }
- /// <summary>
- /// Deletes a cross-sell product
- /// </summary>
- /// <param name="crossSellProduct">Cross-sell identifier</param>
- public virtual async Task DeleteCrossSellProduct(CrossSellProduct crossSellProduct)
- {
- ArgumentNullException.ThrowIfNull(crossSellProduct);
+ /// <summary>
+ /// Gets a cross-sells
+ /// </summary>
+ /// <param name="cart">Shopping cart</param>
+ /// <param name="numberOfProducts">Number of products to return</param>
+ /// <returns>Cross-sells</returns>
+ public virtual async Task<IList<Product>> GetCrossSellProductsByShoppingCart(IList<ShoppingCartItem> cart,
+ int numberOfProducts)
+ {
+ var result = new List<Product>();
- await _productRepository.Pull(crossSellProduct.ProductId1, x => x.CrossSellProduct, crossSellProduct.ProductId2);
+ if (numberOfProducts == 0)
+ return result;
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, crossSellProduct.ProductId1));
+ if (cart == null || !cart.Any())
+ return result;
- //event notification
- await _mediator.EntityDeleted(crossSellProduct);
- }
+ var cartProductIds = new List<string>();
+ foreach (var sci in cart)
+ if (!cartProductIds.Contains(sci.ProductId))
+ cartProductIds.Add(sci.ProductId);
- /// <summary>
- /// Gets a cross-sells
- /// </summary>
- /// <param name="cart">Shopping cart</param>
- /// <param name="numberOfProducts">Number of products to return</param>
- /// <returns>Cross-sells</returns>
- public virtual async Task<IList<Product>> GetCrossSellProductsByShoppingCart(IList<ShoppingCartItem> cart, int numberOfProducts)
+ foreach (var sci in cart)
{
- var result = new List<Product>();
+ var product = await GetProductById(sci.ProductId);
+ if (product is not { Published: true })
+ continue;
- if (numberOfProducts == 0)
- return result;
-
- if (cart == null || !cart.Any())
- return result;
-
- var cartProductIds = new List<string>();
- foreach (var sci in cart)
- {
- if (!cartProductIds.Contains(sci.ProductId))
- cartProductIds.Add(sci.ProductId);
- }
-
- foreach (var sci in cart)
+ var crossSells = product.CrossSellProduct;
+ foreach (var crossSell in crossSells)
{
- var product = await GetProductById(sci.ProductId);
- if (product is not { Published: true })
+ //validate that this product is not added to result yet
+ if (result.Find(p => p.Id == crossSell) != null ||
+ cartProductIds.Contains(crossSell)) continue;
+ var productToAdd = await GetProductById(crossSell);
+ //validate product
+ if (productToAdd is not { Published: true }
+ || !_aclService.Authorize(productToAdd, _workContext.CurrentCustomer) ||
+ !_aclService.Authorize(productToAdd, _workContext.CurrentStore.Id)
+ || !productToAdd.IsAvailable())
continue;
- var crossSells = product.CrossSellProduct;
- foreach (var crossSell in crossSells)
- {
- //validate that this product is not added to result yet
- if (result.Find(p => p.Id == crossSell) != null ||
- cartProductIds.Contains(crossSell)) continue;
- var productToAdd = await GetProductById(crossSell);
- //validate product
- if (productToAdd is not { Published: true }
- || !_aclService.Authorize(productToAdd, _workContext.CurrentCustomer) || !_aclService.Authorize(productToAdd, _workContext.CurrentStore.Id)
- || !productToAdd.IsAvailable())
- continue;
-
- //add a product to result
- result.Add(productToAdd);
- if (result.Count >= numberOfProducts)
- return result;
- }
+ //add a product to result
+ result.Add(productToAdd);
+ if (result.Count >= numberOfProducts)
+ return result;
}
- return result;
}
- #endregion
+ return result;
+ }
- #region Recommmended products
+ #endregion
- /// <summary>
- /// Inserts a recommended product
- /// </summary>
- /// <param name="productId">Product ident</param>
- /// <param name="recommendedProductId">Recommended product</param>
- public virtual async Task InsertRecommendedProduct(string productId, string recommendedProductId)
- {
- ArgumentNullException.ThrowIfNull(productId);
- ArgumentNullException.ThrowIfNull(recommendedProductId);
+ #region Recommmended products
- await _productRepository.AddToSet(productId, x => x.RecommendedProduct, recommendedProductId);
+ /// <summary>
+ /// Inserts a recommended product
+ /// </summary>
+ /// <param name="productId">Product ident</param>
+ /// <param name="recommendedProductId">Recommended product</param>
+ public virtual async Task InsertRecommendedProduct(string productId, string recommendedProductId)
+ {
+ ArgumentNullException.ThrowIfNull(productId);
+ ArgumentNullException.ThrowIfNull(recommendedProductId);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
-
- }
+ await _productRepository.AddToSet(productId, x => x.RecommendedProduct, recommendedProductId);
- /// <summary>
- /// Deletes a recommended product
- /// </summary>
- /// <param name="productId">Product ident</param>
- /// <param name="recommendedProductId">Recommended identifier</param>
- public virtual async Task DeleteRecommendedProduct(string productId, string recommendedProductId)
- {
- ArgumentNullException.ThrowIfNull(productId);
- ArgumentNullException.ThrowIfNull(recommendedProductId);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ }
- await _productRepository.Pull(productId, x => x.RecommendedProduct, recommendedProductId);
+ /// <summary>
+ /// Deletes a recommended product
+ /// </summary>
+ /// <param name="productId">Product ident</param>
+ /// <param name="recommendedProductId">Recommended identifier</param>
+ public virtual async Task DeleteRecommendedProduct(string productId, string recommendedProductId)
+ {
+ ArgumentNullException.ThrowIfNull(productId);
+ ArgumentNullException.ThrowIfNull(recommendedProductId);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- }
+ await _productRepository.Pull(productId, x => x.RecommendedProduct, recommendedProductId);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ }
- #region Tier prices
+ #endregion
+ #region Tier prices
- /// <summary>
- /// Inserts a tier price
- /// </summary>
- /// <param name="tierPrice">Tier price</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertTierPrice(TierPrice tierPrice, string productId)
- {
- ArgumentNullException.ThrowIfNull(tierPrice);
+ /// <summary>
+ /// Inserts a tier price
+ /// </summary>
+ /// <param name="tierPrice">Tier price</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertTierPrice(TierPrice tierPrice, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(tierPrice);
- await _productRepository.AddToSet(productId, x => x.TierPrices, tierPrice);
+ await _productRepository.AddToSet(productId, x => x.TierPrices, tierPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityInserted(tierPrice);
- }
+ //event notification
+ await _mediator.EntityInserted(tierPrice);
+ }
- /// <summary>
- /// Updates the tier price
- /// </summary>
- /// <param name="tierPrice">Tier price</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateTierPrice(TierPrice tierPrice, string productId)
- {
- ArgumentNullException.ThrowIfNull(tierPrice);
+ /// <summary>
+ /// Updates the tier price
+ /// </summary>
+ /// <param name="tierPrice">Tier price</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateTierPrice(TierPrice tierPrice, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(tierPrice);
- await _productRepository.UpdateToSet(productId, x => x.TierPrices, z => z.Id, tierPrice.Id, tierPrice);
+ await _productRepository.UpdateToSet(productId, x => x.TierPrices, z => z.Id, tierPrice.Id, tierPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityUpdated(tierPrice);
- }
- /// <summary>
- /// Deletes a tier price
- /// </summary>
- /// <param name="tierPrice">Tier price</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteTierPrice(TierPrice tierPrice, string productId)
- {
- ArgumentNullException.ThrowIfNull(tierPrice);
+ //event notification
+ await _mediator.EntityUpdated(tierPrice);
+ }
- await _productRepository.PullFilter(productId, x => x.TierPrices, x => x.Id, tierPrice.Id);
+ /// <summary>
+ /// Deletes a tier price
+ /// </summary>
+ /// <param name="tierPrice">Tier price</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteTierPrice(TierPrice tierPrice, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(tierPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _productRepository.PullFilter(productId, x => x.TierPrices, x => x.Id, tierPrice.Id);
- //event notification
- await _mediator.EntityDeleted(tierPrice);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(tierPrice);
+ }
- #region Product prices
+ #endregion
- /// <summary>
- /// Inserts a product price
- /// </summary>
- /// <param name="productPrice">Product price</param>
- public virtual async Task InsertProductPrice(ProductPrice productPrice)
- {
- ArgumentNullException.ThrowIfNull(productPrice);
+ #region Product prices
- await _productRepository.AddToSet(productPrice.ProductId, x => x.ProductPrices, productPrice);
+ /// <summary>
+ /// Inserts a product price
+ /// </summary>
+ /// <param name="productPrice">Product price</param>
+ public virtual async Task InsertProductPrice(ProductPrice productPrice)
+ {
+ ArgumentNullException.ThrowIfNull(productPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
+ await _productRepository.AddToSet(productPrice.ProductId, x => x.ProductPrices, productPrice);
- //event notification
- await _mediator.EntityInserted(productPrice);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
- /// <summary>
- /// Updates the product price
- /// </summary>
- /// <param name="productPrice">Tier price</param>
- public virtual async Task UpdateProductPrice(ProductPrice productPrice)
- {
- ArgumentNullException.ThrowIfNull(productPrice);
+ //event notification
+ await _mediator.EntityInserted(productPrice);
+ }
- await _productRepository.UpdateToSet(productPrice.ProductId, x => x.ProductPrices, z => z.Id, productPrice.Id, productPrice);
+ /// <summary>
+ /// Updates the product price
+ /// </summary>
+ /// <param name="productPrice">Tier price</param>
+ public virtual async Task UpdateProductPrice(ProductPrice productPrice)
+ {
+ ArgumentNullException.ThrowIfNull(productPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
+ await _productRepository.UpdateToSet(productPrice.ProductId, x => x.ProductPrices, z => z.Id, productPrice.Id,
+ productPrice);
- //event notification
- await _mediator.EntityUpdated(productPrice);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
- /// <summary>
- /// Deletes a product price
- /// </summary>
- /// <param name="productPrice">Product price</param>
- public virtual async Task DeleteProductPrice(ProductPrice productPrice)
- {
- ArgumentNullException.ThrowIfNull(productPrice);
+ //event notification
+ await _mediator.EntityUpdated(productPrice);
+ }
- await _productRepository.PullFilter(productPrice.ProductId, x => x.ProductPrices, x => x.Id, productPrice.Id);
+ /// <summary>
+ /// Deletes a product price
+ /// </summary>
+ /// <param name="productPrice">Product price</param>
+ public virtual async Task DeleteProductPrice(ProductPrice productPrice)
+ {
+ ArgumentNullException.ThrowIfNull(productPrice);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
+ await _productRepository.PullFilter(productPrice.ProductId, x => x.ProductPrices, x => x.Id, productPrice.Id);
- //event notification
- await _mediator.EntityDeleted(productPrice);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productPrice.ProductId));
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(productPrice);
+ }
- #region Product pictures
- /// <summary>
- /// Inserts a product picture
- /// </summary>
- /// <param name="productPicture">Product picture</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductPicture(ProductPicture productPicture, string productId)
- {
- ArgumentNullException.ThrowIfNull(productPicture);
+ #endregion
- await _productRepository.AddToSet(productId, x => x.ProductPictures, productPicture);
+ #region Product pictures
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ /// <summary>
+ /// Inserts a product picture
+ /// </summary>
+ /// <param name="productPicture">Product picture</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductPicture(ProductPicture productPicture, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productPicture);
- //event notification
- await _mediator.EntityInserted(productPicture);
- }
+ await _productRepository.AddToSet(productId, x => x.ProductPictures, productPicture);
- /// <summary>
- /// Updates a product picture
- /// </summary>
- /// <param name="productPicture">Product picture</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateProductPicture(ProductPicture productPicture, string productId)
- {
- ArgumentNullException.ThrowIfNull(productPicture);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- await _productRepository.UpdateToSet(productId, x => x.ProductPictures, z => z.Id, productPicture.Id, productPicture);
+ //event notification
+ await _mediator.EntityInserted(productPicture);
+ }
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ /// <summary>
+ /// Updates a product picture
+ /// </summary>
+ /// <param name="productPicture">Product picture</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateProductPicture(ProductPicture productPicture, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productPicture);
- //event notification
- await _mediator.EntityUpdated(productPicture);
- }
- /// <summary>
- /// Deletes a product picture
- /// </summary>
- /// <param name="productPicture">Product picture</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductPicture(ProductPicture productPicture, string productId)
- {
- ArgumentNullException.ThrowIfNull(productPicture);
+ await _productRepository.UpdateToSet(productId, x => x.ProductPictures, z => z.Id, productPicture.Id,
+ productPicture);
- await _productRepository.PullFilter(productId, x => x.ProductPictures, x => x.Id, productPicture.Id);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityUpdated(productPicture);
+ }
- //event notification
- await _mediator.EntityDeleted(productPicture);
- }
- #endregion
-
- #region Product warehouse inventory
- /// <summary>
- /// Insert product warehouse inventory
- /// </summary>
- /// <param name="pwi"></param>
- /// <param name="productId"></param>
- /// <returns></returns>
- public virtual async Task InsertProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
- {
- ArgumentNullException.ThrowIfNull(pwi);
+ /// <summary>
+ /// Deletes a product picture
+ /// </summary>
+ /// <param name="productPicture">Product picture</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductPicture(ProductPicture productPicture, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productPicture);
- await _productRepository.AddToSet(productId, x => x.ProductWarehouseInventory, pwi);
+ await _productRepository.PullFilter(productId, x => x.ProductPictures, x => x.Id, productPicture.Id);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityInserted(pwi);
- }
- /// <summary>
- /// Update product warehouse inventory
- /// </summary>
- /// <param name="pwi"></param>
- /// <param name="productId"></param>
- /// <returns></returns>
- public virtual async Task UpdateProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
- {
- ArgumentNullException.ThrowIfNull(pwi);
+ //event notification
+ await _mediator.EntityDeleted(productPicture);
+ }
- await _productRepository.UpdateToSet(productId, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
+ #endregion
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityUpdated(pwi);
- }
- /// <summary>
- /// Deletes a ProductWarehouseInventory
- /// </summary>
- /// <param name="pwi">ProductWarehouseInventory</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
- {
- ArgumentNullException.ThrowIfNull(pwi);
+ #region Product warehouse inventory
- await _productRepository.PullFilter(productId, x => x.ProductWarehouseInventory, x => x.Id, pwi.Id);
+ /// <summary>
+ /// Insert product warehouse inventory
+ /// </summary>
+ /// <param name="pwi"></param>
+ /// <param name="productId"></param>
+ /// <returns></returns>
+ public virtual async Task InsertProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(pwi);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _productRepository.AddToSet(productId, x => x.ProductWarehouseInventory, pwi);
- }
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #region Discount
+ //event notification
+ await _mediator.EntityInserted(pwi);
+ }
- public virtual async Task DeleteDiscount(string discountId, string productId)
- {
- if (string.IsNullOrEmpty(discountId))
- throw new ArgumentNullException(nameof(discountId));
+ /// <summary>
+ /// Update product warehouse inventory
+ /// </summary>
+ /// <param name="pwi"></param>
+ /// <param name="productId"></param>
+ /// <returns></returns>
+ public virtual async Task UpdateProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(pwi);
- await _productRepository.Pull(productId, x => x.AppliedDiscounts, discountId);
+ await _productRepository.UpdateToSet(productId, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //event notification
+ await _mediator.EntityUpdated(pwi);
+ }
- public virtual async Task InsertDiscount(string discountId, string productId)
- {
- if (string.IsNullOrEmpty(discountId))
- throw new ArgumentNullException(nameof(discountId));
+ /// <summary>
+ /// Deletes a ProductWarehouseInventory
+ /// </summary>
+ /// <param name="pwi">ProductWarehouseInventory</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductWarehouseInventory(ProductWarehouseInventory pwi, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(pwi);
- await _productRepository.AddToSet(productId, x => x.AppliedDiscounts, discountId);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- }
+ await _productRepository.PullFilter(productId, x => x.ProductWarehouseInventory, x => x.Id, pwi.Id);
+
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ }
+
+ #endregion
- #endregion
+ #region Discount
- #endregion
+ public virtual async Task DeleteDiscount(string discountId, string productId)
+ {
+ if (string.IsNullOrEmpty(discountId))
+ throw new ArgumentNullException(nameof(discountId));
+
+ await _productRepository.Pull(productId, x => x.AppliedDiscounts, discountId);
+
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
}
-}
+
+ public virtual async Task InsertDiscount(string discountId, string productId)
+ {
+ if (string.IsNullOrEmpty(discountId))
+ throw new ArgumentNullException(nameof(discountId));
+
+ await _productRepository.AddToSet(productId, x => x.AppliedDiscounts, discountId);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ }
+
+ #endregion
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs
index 497071bc4..44e04ae18 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs
@@ -1,229 +1,229 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain.Catalog;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Product tag service
+/// </summary>
+public class ProductTagService : IProductTagService
{
+ #region Ctor
+
/// <summary>
- /// Product tag service
+ /// Ctor
/// </summary>
- public class ProductTagService : IProductTagService
+ /// <param name="productTagRepository">Product tag repository</param>
+ /// <param name="productRepository">Product repository</param>
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="mediator">Mediator</param>
+ public ProductTagService(IRepository<ProductTag> productTagRepository,
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase,
+ IMediator mediator
+ )
{
- #region Fields
-
- private readonly IRepository<ProductTag> _productTagRepository;
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="productTagRepository">Product tag repository</param>
- /// <param name="productRepository">Product repository</param>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="mediator">Mediator</param>
- public ProductTagService(IRepository<ProductTag> productTagRepository,
- IRepository<Product> productRepository,
- ICacheBase cacheBase,
- IMediator mediator
- )
- {
- _productTagRepository = productTagRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- _productRepository = productRepository;
- }
-
- #endregion
-
- #region Utilities
-
- /// <summary>
- /// Get product count for each of existing product tag
- /// </summary>
- /// <returns>Dictionary of "product tag ID : product count"</returns>
- private async Task<Dictionary<string, int>> GetProductCount()
+ _productTagRepository = productTagRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ _productRepository = productRepository;
+ }
+
+ #endregion
+
+ #region Utilities
+
+ /// <summary>
+ /// Get product count for each of existing product tag
+ /// </summary>
+ /// <returns>Dictionary of "product tag ID : product count"</returns>
+ private async Task<Dictionary<string, int>> GetProductCount()
+ {
+ return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_COUNT_KEY, async () =>
{
- return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_COUNT_KEY, async () =>
- {
- var query = from pt in _productTagRepository.Table
- select pt;
+ var query = from pt in _productTagRepository.Table
+ select pt;
- var dictionary = query.ToList().ToDictionary(item => item.Id, item => item.Count);
- return await Task.FromResult(dictionary);
- });
- }
+ var dictionary = query.ToList().ToDictionary(item => item.Id, item => item.Count);
+ return await Task.FromResult(dictionary);
+ });
+ }
- #endregion
+ #endregion
- #region Methods
+ #region Fields
+ private readonly IRepository<ProductTag> _productTagRepository;
+ private readonly IRepository<Product> _productRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Gets all product tags
- /// </summary>
- /// <returns>Product tags</returns>
- public virtual async Task<IList<ProductTag>> GetAllProductTags()
- {
- return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_ALL_KEY, async () => await Task.FromResult(_productTagRepository.Table.ToList()));
- }
-
- /// <summary>
- /// Gets product tag
- /// </summary>
- /// <param name="productTagId">Product tag identifier</param>
- /// <returns>Product tag</returns>
- public virtual Task<ProductTag> GetProductTagById(string productTagId)
- {
- return _productTagRepository.GetByIdAsync(productTagId);
- }
-
- /// <summary>
- /// Gets product tag by name
- /// </summary>
- /// <param name="name">Product tag name</param>
- /// <returns>Product tag</returns>
- public virtual Task<ProductTag> GetProductTagByName(string name)
- {
- return _productTagRepository.GetOneAsync(x=>x.Name == name);
- }
-
- /// <summary>
- /// Gets product tag by se-name
- /// </summary>
- /// <param name="sename">Product tag se-name</param>
- /// <returns>Product tag</returns>
- public virtual Task<ProductTag> GetProductTagBySeName(string sename)
- {
- return _productTagRepository.GetOneAsync(x=>x.SeName == sename);
- }
-
- /// <summary>
- /// Inserts a product tag
- /// </summary>
- /// <param name="productTag">Product tag</param>
- public virtual async Task InsertProductTag(ProductTag productTag)
- {
- ArgumentNullException.ThrowIfNull(productTag);
+ #endregion
- await _productTagRepository.InsertAsync(productTag);
+ #region Methods
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+ /// <summary>
+ /// Gets all product tags
+ /// </summary>
+ /// <returns>Product tags</returns>
+ public virtual async Task<IList<ProductTag>> GetAllProductTags()
+ {
+ return await _cacheBase.GetAsync(CacheKey.PRODUCTTAG_ALL_KEY,
+ async () => await Task.FromResult(_productTagRepository.Table.ToList()));
+ }
- //event notification
- await _mediator.EntityInserted(productTag);
- }
+ /// <summary>
+ /// Gets product tag
+ /// </summary>
+ /// <param name="productTagId">Product tag identifier</param>
+ /// <returns>Product tag</returns>
+ public virtual Task<ProductTag> GetProductTagById(string productTagId)
+ {
+ return _productTagRepository.GetByIdAsync(productTagId);
+ }
- /// <summary>
- /// Inserts a product tag
- /// </summary>
- /// <param name="productTag">Product tag</param>
- public virtual async Task UpdateProductTag(ProductTag productTag)
- {
- ArgumentNullException.ThrowIfNull(productTag);
+ /// <summary>
+ /// Gets product tag by name
+ /// </summary>
+ /// <param name="name">Product tag name</param>
+ /// <returns>Product tag</returns>
+ public virtual Task<ProductTag> GetProductTagByName(string name)
+ {
+ return _productTagRepository.GetOneAsync(x => x.Name == name);
+ }
- var previous = await GetProductTagById(productTag.Id);
+ /// <summary>
+ /// Gets product tag by se-name
+ /// </summary>
+ /// <param name="sename">Product tag se-name</param>
+ /// <returns>Product tag</returns>
+ public virtual Task<ProductTag> GetProductTagBySeName(string sename)
+ {
+ return _productTagRepository.GetOneAsync(x => x.SeName == sename);
+ }
- await _productTagRepository.UpdateAsync(productTag);
+ /// <summary>
+ /// Inserts a product tag
+ /// </summary>
+ /// <param name="productTag">Product tag</param>
+ public virtual async Task InsertProductTag(ProductTag productTag)
+ {
+ ArgumentNullException.ThrowIfNull(productTag);
- //update on products
- await _productRepository.UpdateToSet(x => x.ProductTags, previous.Name, productTag.Name);
+ await _productTagRepository.InsertAsync(productTag);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
- //event notification
- await _mediator.EntityUpdated(productTag);
- }
- /// <summary>
- /// Delete a product tag
- /// </summary>
- /// <param name="productTag">Product tag</param>
- public virtual async Task DeleteProductTag(ProductTag productTag)
- {
- ArgumentNullException.ThrowIfNull(productTag);
+ //event notification
+ await _mediator.EntityInserted(productTag);
+ }
- //update product
- await _productRepository.Pull(string.Empty, x => x.ProductTags, productTag.Name);
+ /// <summary>
+ /// Inserts a product tag
+ /// </summary>
+ /// <param name="productTag">Product tag</param>
+ public virtual async Task UpdateProductTag(ProductTag productTag)
+ {
+ ArgumentNullException.ThrowIfNull(productTag);
- //delete tag
- await _productTagRepository.DeleteAsync(productTag);
+ var previous = await GetProductTagById(productTag.Id);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ await _productTagRepository.UpdateAsync(productTag);
- //event notification
- await _mediator.EntityDeleted(productTag);
- }
+ //update on products
+ await _productRepository.UpdateToSet(x => x.ProductTags, previous.Name, productTag.Name);
- /// <summary>
- /// Attach a tag to the product
- /// </summary>
- /// <param name="productTag">Product tag</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task AttachProductTag(ProductTag productTag, string productId)
- {
- ArgumentNullException.ThrowIfNull(productTag);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
- //assign to product
- await _productRepository.AddToSet(productId, x => x.ProductTags, productTag.Name);
+ //event notification
+ await _mediator.EntityUpdated(productTag);
+ }
- //update product tag
- await _productTagRepository.UpdateField(productTag.Id, x => x.Count, productTag.Count+1);
+ /// <summary>
+ /// Delete a product tag
+ /// </summary>
+ /// <param name="productTag">Product tag</param>
+ public virtual async Task DeleteProductTag(ProductTag productTag)
+ {
+ ArgumentNullException.ThrowIfNull(productTag);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+ //update product
+ await _productRepository.Pull(string.Empty, x => x.ProductTags, productTag.Name);
- //event notification
- await _mediator.EntityInserted(productTag);
- }
+ //delete tag
+ await _productTagRepository.DeleteAsync(productTag);
- /// <summary>
- /// Detach a tag from the product
- /// </summary>
- /// <param name="productTag">Product Tag</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DetachProductTag(ProductTag productTag, string productId)
- {
- ArgumentNullException.ThrowIfNull(productTag);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- await _productRepository.Pull(productId, x => x.ProductTags, productTag.Name);
+ //event notification
+ await _mediator.EntityDeleted(productTag);
+ }
- //update product tag
- await _productTagRepository.UpdateField(productTag.Id, x => x.Count, productTag.Count-1);
+ /// <summary>
+ /// Attach a tag to the product
+ /// </summary>
+ /// <param name="productTag">Product tag</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task AttachProductTag(ProductTag productTag, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productTag);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+ //assign to product
+ await _productRepository.AddToSet(productId, x => x.ProductTags, productTag.Name);
- //event notification
- await _mediator.EntityDeleted(productTag);
- }
+ //update product tag
+ await _productTagRepository.UpdateField(productTag.Id, x => x.Count, productTag.Count + 1);
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
- /// <summary>
- /// Get number of products
- /// </summary>
- /// <param name="productTagId">Product tag identifier</param>
- /// <returns>Number of products</returns>
- public virtual async Task<int> GetProductCount(string productTagId)
- {
- var dictionary = await GetProductCount();
- return dictionary.TryGetValue(productTagId, out var value) ? value : 0;
- }
+ //event notification
+ await _mediator.EntityInserted(productTag);
+ }
+
+ /// <summary>
+ /// Detach a tag from the product
+ /// </summary>
+ /// <param name="productTag">Product Tag</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DetachProductTag(ProductTag productTag, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productTag);
+
+ await _productRepository.Pull(productId, x => x.ProductTags, productTag.Name);
+
+ //update product tag
+ await _productTagRepository.UpdateField(productTag.Id, x => x.Count, productTag.Count - 1);
- #endregion
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);
+
+ //event notification
+ await _mediator.EntityDeleted(productTag);
+ }
+
+
+ /// <summary>
+ /// Get number of products
+ /// </summary>
+ /// <param name="productTagId">Product tag identifier</param>
+ /// <returns>Number of products</returns>
+ public virtual async Task<int> GetProductCount(string productTagId)
+ {
+ var dictionary = await GetProductCount();
+ return dictionary.TryGetValue(productTagId, out var value) ? value : 0;
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs b/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs
index db77815e0..171e85f80 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/RecentlyViewedProductsService.cs
@@ -1,130 +1,124 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
-using Grand.Domain.Catalog;
-using Grand.Data;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Recently viewed products service
+/// </summary>
+public class RecentlyViewedProductsService : IRecentlyViewedProductsService
{
+ #region Ctor
+
/// <summary>
- /// Recently viewed products service
+ /// Ctor
/// </summary>
- public class RecentlyViewedProductsService : IRecentlyViewedProductsService
+ /// <param name="productService">Product service</param>
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="catalogSettings">Catalog settings</param>
+ /// <param name="recentlyViewedProducts">Collection recentlyViewedProducts</param>
+ public RecentlyViewedProductsService(
+ IProductService productService,
+ ICacheBase cacheBase,
+ CatalogSettings catalogSettings,
+ IRepository<RecentlyViewedProduct> recentlyViewedProducts)
{
- #region Fields
-
- private readonly IProductService _productService;
- private readonly ICacheBase _cacheBase;
- private readonly CatalogSettings _catalogSettings;
- private readonly IRepository<RecentlyViewedProduct> _recentlyViewedProducts;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="productService">Product service</param>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="catalogSettings">Catalog settings</param>
- /// <param name="recentlyViewedProducts">Collection recentlyViewedProducts</param>
- public RecentlyViewedProductsService(
- IProductService productService,
- ICacheBase cacheBase,
- CatalogSettings catalogSettings,
- IRepository<RecentlyViewedProduct> recentlyViewedProducts)
- {
- _productService = productService;
- _cacheBase = cacheBase;
- _catalogSettings = catalogSettings;
- _recentlyViewedProducts = recentlyViewedProducts;
- }
+ _productService = productService;
+ _cacheBase = cacheBase;
+ _catalogSettings = catalogSettings;
+ _recentlyViewedProducts = recentlyViewedProducts;
+ }
+
+ #endregion
- #endregion
+ #region Fields
- #region Utilities
+ private readonly IProductService _productService;
+ private readonly ICacheBase _cacheBase;
+ private readonly CatalogSettings _catalogSettings;
+ private readonly IRepository<RecentlyViewedProduct> _recentlyViewedProducts;
+ #endregion
- protected IList<RecentlyViewedProduct> GetRecentlyViewedProducts(string customerId)
+ #region Utilities
+
+ protected IList<RecentlyViewedProduct> GetRecentlyViewedProducts(string customerId)
+ {
+ var query = from p in _recentlyViewedProducts.Table
+ where p.CustomerId == customerId
+ orderby p.CreatedOnUtc descending
+ select p;
+
+ return query.ToList();
+ }
+
+ /// <summary>
+ /// Gets a "recently viewed products" identifier list
+ /// </summary>
+ /// <param name="customerId">Customer ident</param>
+ /// <param name="number">Number of products to load</param>
+ /// <returns>"recently viewed products" list</returns>
+ protected async Task<IList<string>> GetRecentlyViewedProductsIds(string customerId, int number)
+ {
+ var key = string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_KEY, customerId, number);
+ return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _recentlyViewedProducts.Table
- where p.CustomerId == customerId
- orderby p.CreatedOnUtc descending
- select p;
-
- return query.ToList();
- }
-
- /// <summary>
- /// Gets a "recently viewed products" identifier list
- /// </summary>
- /// <param name="customerId">Customer ident</param>
- /// <param name="number">Number of products to load</param>
- /// <returns>"recently viewed products" list</returns>
- protected async Task<IList<string>> GetRecentlyViewedProductsIds(string customerId, int number)
- {
- var key = string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_KEY, customerId, number);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from p in _recentlyViewedProducts.Table
- where p.CustomerId == customerId
- orderby p.CreatedOnUtc descending
- select p.ProductId;
- return await Task.FromResult(query.Take(number).ToList());
- });
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets a "recently viewed products" list
- /// </summary>
- /// <param name="customerId">Customer ident</param>
- /// <param name="number">Number of products to load</param>
- /// <returns>"recently viewed products" list</returns>
- public virtual async Task<IList<Product>> GetRecentlyViewedProducts(string customerId, int number)
- {
- var productIds = await GetRecentlyViewedProductsIds(customerId, number);
- return (await _productService.GetProductsByIds(productIds.ToArray())).Where(product => product.Published).ToList();
- }
-
- /// <summary>
- /// Adds a product to a recently viewed products list
- /// </summary>
- /// <param name="customerId">Customer ident</param>
- /// <param name="productId">Product identifier</param>
- public virtual async Task AddProductToRecentlyViewedList(string customerId, string productId)
- {
- if (!_catalogSettings.RecentlyViewedProductsEnabled)
- return;
-
- var recentlyViewedProducts = GetRecentlyViewedProducts(customerId);
- var recentlyViewedProduct = recentlyViewedProducts.FirstOrDefault(x => x.ProductId == productId);
- if (recentlyViewedProduct == null)
- {
- await _recentlyViewedProducts.InsertAsync(new RecentlyViewedProduct { CustomerId = customerId, ProductId = productId });
- }
- else
- {
- await _recentlyViewedProducts.UpdateAsync(recentlyViewedProduct);
- }
- var maxProducts = _catalogSettings.RecentlyViewedProductsNumber;
- if (maxProducts <= 0)
- maxProducts = 10;
-
- if (recentlyViewedProducts.Count > _catalogSettings.RecentlyViewedProductsNumber)
- {
- await _recentlyViewedProducts.DeleteAsync(recentlyViewedProducts.OrderBy(x => x.CreatedOnUtc).Take(recentlyViewedProducts.Count - _catalogSettings.RecentlyViewedProductsNumber));
- }
-
- //Clear cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_PATTERN_KEY, customerId));
-
- }
-
- #endregion
+ where p.CustomerId == customerId
+ orderby p.CreatedOnUtc descending
+ select p.ProductId;
+ return await Task.FromResult(query.Take(number).ToList());
+ });
+ }
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets a "recently viewed products" list
+ /// </summary>
+ /// <param name="customerId">Customer ident</param>
+ /// <param name="number">Number of products to load</param>
+ /// <returns>"recently viewed products" list</returns>
+ public virtual async Task<IList<Product>> GetRecentlyViewedProducts(string customerId, int number)
+ {
+ var productIds = await GetRecentlyViewedProductsIds(customerId, number);
+ return (await _productService.GetProductsByIds(productIds.ToArray())).Where(product => product.Published)
+ .ToList();
+ }
+
+ /// <summary>
+ /// Adds a product to a recently viewed products list
+ /// </summary>
+ /// <param name="customerId">Customer ident</param>
+ /// <param name="productId">Product identifier</param>
+ public virtual async Task AddProductToRecentlyViewedList(string customerId, string productId)
+ {
+ if (!_catalogSettings.RecentlyViewedProductsEnabled)
+ return;
+
+ var recentlyViewedProducts = GetRecentlyViewedProducts(customerId);
+ var recentlyViewedProduct = recentlyViewedProducts.FirstOrDefault(x => x.ProductId == productId);
+ if (recentlyViewedProduct == null)
+ await _recentlyViewedProducts.InsertAsync(new RecentlyViewedProduct
+ { CustomerId = customerId, ProductId = productId });
+ else
+ await _recentlyViewedProducts.UpdateAsync(recentlyViewedProduct);
+ var maxProducts = _catalogSettings.RecentlyViewedProductsNumber;
+ if (maxProducts <= 0)
+ maxProducts = 10;
+
+ if (recentlyViewedProducts.Count > _catalogSettings.RecentlyViewedProductsNumber)
+ await _recentlyViewedProducts.DeleteAsync(recentlyViewedProducts.OrderBy(x => x.CreatedOnUtc)
+ .Take(recentlyViewedProducts.Count - _catalogSettings.RecentlyViewedProductsNumber));
+
+ //Clear cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.RECENTLY_VIEW_PRODUCTS_PATTERN_KEY, customerId));
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs
index 64d05dee5..256b0ac09 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs
@@ -1,280 +1,295 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
+using Grand.Domain;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain;
-using Grand.Domain.Catalog;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+/// <summary>
+/// Specification attribute service
+/// </summary>
+public class SpecificationAttributeService : ISpecificationAttributeService
{
+ #region Ctor
+
/// <summary>
- /// Specification attribute service
+ /// Ctor
/// </summary>
- public class SpecificationAttributeService : ISpecificationAttributeService
+ public SpecificationAttributeService(ICacheBase cacheBase,
+ IRepository<SpecificationAttribute> specificationAttributeRepository,
+ IRepository<Product> productRepository,
+ IMediator mediator)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _specificationAttributeRepository = specificationAttributeRepository;
+ _mediator = mediator;
+ _productRepository = productRepository;
+ }
- private readonly IRepository<Product> _productRepository;
- private readonly IRepository<SpecificationAttribute> _specificationAttributeRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<Product> _productRepository;
+ private readonly IRepository<SpecificationAttribute> _specificationAttributeRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Ctor
- /// </summary>
- public SpecificationAttributeService(ICacheBase cacheBase,
- IRepository<SpecificationAttribute> specificationAttributeRepository,
- IRepository<Product> productRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _specificationAttributeRepository = specificationAttributeRepository;
- _mediator = mediator;
- _productRepository = productRepository;
- }
+ #endregion
- #endregion
+ #region Methods
- #region Methods
+ #region Specification attribute
- #region Specification attribute
+ /// <summary>
+ /// Gets a specification attribute
+ /// </summary>
+ /// <param name="specificationAttributeId">The specification attribute identifier</param>
+ /// <returns>Specification attribute</returns>
+ public virtual async Task<SpecificationAttribute> GetSpecificationAttributeById(string specificationAttributeId)
+ {
+ var key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId);
+ return await _cacheBase.GetAsync(key,
+ () => _specificationAttributeRepository.GetByIdAsync(specificationAttributeId));
+ }
- /// <summary>
- /// Gets a specification attribute
- /// </summary>
- /// <param name="specificationAttributeId">The specification attribute identifier</param>
- /// <returns>Specification attribute</returns>
- public virtual async Task<SpecificationAttribute> GetSpecificationAttributeById(string specificationAttributeId)
- {
- var key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId);
- return await _cacheBase.GetAsync(key, () => _specificationAttributeRepository.GetByIdAsync(specificationAttributeId));
- }
-
- /// <summary>
- /// Gets a specification attribute by se-name
- /// </summary>
- /// <param name="sename">Se-name</param>
- /// <returns>Specification attribute</returns>
- public virtual async Task<SpecificationAttribute> GetSpecificationAttributeBySeName(string sename)
- {
- if (string.IsNullOrEmpty(sename))
- return await Task.FromResult<SpecificationAttribute>(null);
+ /// <summary>
+ /// Gets a specification attribute by se-name
+ /// </summary>
+ /// <param name="sename">Se-name</param>
+ /// <returns>Specification attribute</returns>
+ public virtual async Task<SpecificationAttribute> GetSpecificationAttributeBySeName(string sename)
+ {
+ if (string.IsNullOrEmpty(sename))
+ return await Task.FromResult<SpecificationAttribute>(null);
- sename = sename.ToLowerInvariant();
+ sename = sename.ToLowerInvariant();
- var key = string.Format(CacheKey.SPECIFICATION_BY_SENAME, sename);
- return await _cacheBase.GetAsync(key, async () =>
- await Task.FromResult(_specificationAttributeRepository.Table
- .FirstOrDefault(x => x.SeName == sename)));
- }
+ var key = string.Format(CacheKey.SPECIFICATION_BY_SENAME, sename);
+ return await _cacheBase.GetAsync(key, async () =>
+ await Task.FromResult(_specificationAttributeRepository.Table
+ .FirstOrDefault(x => x.SeName == sename)));
+ }
- /// <summary>
- /// Gets specification attributes
- /// </summary>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Specification attributes</returns>
- public virtual async Task<IPagedList<SpecificationAttribute>> GetSpecificationAttributes(int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from sa in _specificationAttributeRepository.Table
- orderby sa.DisplayOrder
- select sa;
- return await PagedList<SpecificationAttribute>.Create(query, pageIndex, pageSize);
- }
-
-
- /// <summary>
- /// Inserts a specification attribute
- /// </summary>
- /// <param name="specificationAttribute">The specification attribute</param>
- public virtual async Task InsertSpecificationAttribute(SpecificationAttribute specificationAttribute)
- {
- ArgumentNullException.ThrowIfNull(specificationAttribute);
+ /// <summary>
+ /// Gets specification attributes
+ /// </summary>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Specification attributes</returns>
+ public virtual async Task<IPagedList<SpecificationAttribute>> GetSpecificationAttributes(int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = from sa in _specificationAttributeRepository.Table
+ orderby sa.DisplayOrder
+ select sa;
+ return await PagedList<SpecificationAttribute>.Create(query, pageIndex, pageSize);
+ }
- await _specificationAttributeRepository.InsertAsync(specificationAttribute);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
+ /// <summary>
+ /// Inserts a specification attribute
+ /// </summary>
+ /// <param name="specificationAttribute">The specification attribute</param>
+ public virtual async Task InsertSpecificationAttribute(SpecificationAttribute specificationAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(specificationAttribute);
- //event notification
- await _mediator.EntityInserted(specificationAttribute);
- }
+ await _specificationAttributeRepository.InsertAsync(specificationAttribute);
- /// <summary>
- /// Updates the specification attribute
- /// </summary>
- /// <param name="specificationAttribute">The specification attribute</param>
- public virtual async Task UpdateSpecificationAttribute(SpecificationAttribute specificationAttribute)
- {
- ArgumentNullException.ThrowIfNull(specificationAttribute);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
- await _specificationAttributeRepository.UpdateAsync(specificationAttribute);
+ //event notification
+ await _mediator.EntityInserted(specificationAttribute);
+ }
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
+ /// <summary>
+ /// Updates the specification attribute
+ /// </summary>
+ /// <param name="specificationAttribute">The specification attribute</param>
+ public virtual async Task UpdateSpecificationAttribute(SpecificationAttribute specificationAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(specificationAttribute);
- //event notification
- await _mediator.EntityUpdated(specificationAttribute);
- }
- /// <summary>
- /// Deletes a specification attribute
- /// </summary>
- /// <param name="specificationAttribute">The specification attribute</param>
- public virtual async Task DeleteSpecificationAttribute(SpecificationAttribute specificationAttribute)
- {
- ArgumentNullException.ThrowIfNull(specificationAttribute);
+ await _specificationAttributeRepository.UpdateAsync(specificationAttribute);
+
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
+
+ //event notification
+ await _mediator.EntityUpdated(specificationAttribute);
+ }
- //delete from all product collections
- await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeId, specificationAttribute.Id);
+ /// <summary>
+ /// Deletes a specification attribute
+ /// </summary>
+ /// <param name="specificationAttribute">The specification attribute</param>
+ public virtual async Task DeleteSpecificationAttribute(SpecificationAttribute specificationAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(specificationAttribute);
- await _specificationAttributeRepository.DeleteAsync(specificationAttribute);
+ //delete from all product collections
+ await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes,
+ z => z.SpecificationAttributeId, specificationAttribute.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
+ await _specificationAttributeRepository.DeleteAsync(specificationAttribute);
- //event notification
- await _mediator.EntityDeleted(specificationAttribute);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(specificationAttribute);
+ }
- #region Specification attribute option
+ #endregion
- /// <summary>
- /// Gets a specification attribute option
- /// </summary>
- /// <param name="specificationAttributeOptionId">The specification attribute option identifier</param>
- /// <returns>Specification attribute option</returns>
- public virtual async Task<SpecificationAttribute> GetSpecificationAttributeByOptionId(string specificationAttributeOptionId)
- {
- if (string.IsNullOrEmpty(specificationAttributeOptionId))
- return await Task.FromResult<SpecificationAttribute>(null);
-
- var key = string.Format(CacheKey.SPECIFICATION_BY_OPTIONID_KEY, specificationAttributeOptionId);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from p in _specificationAttributeRepository.Table
- where p.SpecificationAttributeOptions.Any(x => x.Id == specificationAttributeOptionId)
- select p;
- return await Task.FromResult(query.FirstOrDefault());
- });
- }
-
- /// <summary>
- /// Deletes a specification attribute option
- /// </summary>
- /// <param name="specificationAttributeOption">The specification attribute option</param>
- public virtual async Task DeleteSpecificationAttributeOption(SpecificationAttributeOption specificationAttributeOption)
+ #region Specification attribute option
+
+ /// <summary>
+ /// Gets a specification attribute option
+ /// </summary>
+ /// <param name="specificationAttributeOptionId">The specification attribute option identifier</param>
+ /// <returns>Specification attribute option</returns>
+ public virtual async Task<SpecificationAttribute> GetSpecificationAttributeByOptionId(
+ string specificationAttributeOptionId)
+ {
+ if (string.IsNullOrEmpty(specificationAttributeOptionId))
+ return await Task.FromResult<SpecificationAttribute>(null);
+
+ var key = string.Format(CacheKey.SPECIFICATION_BY_OPTIONID_KEY, specificationAttributeOptionId);
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(specificationAttributeOption);
+ var query = from p in _specificationAttributeRepository.Table
+ where p.SpecificationAttributeOptions.Any(x => x.Id == specificationAttributeOptionId)
+ select p;
+ return await Task.FromResult(query.FirstOrDefault());
+ });
+ }
- //delete from all product collections
- await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id);
+ /// <summary>
+ /// Deletes a specification attribute option
+ /// </summary>
+ /// <param name="specificationAttributeOption">The specification attribute option</param>
+ public virtual async Task DeleteSpecificationAttributeOption(
+ SpecificationAttributeOption specificationAttributeOption)
+ {
+ ArgumentNullException.ThrowIfNull(specificationAttributeOption);
- var specificationAttribute = await GetSpecificationAttributeByOptionId(specificationAttributeOption.Id);
- var sao = specificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == specificationAttributeOption.Id);
- if (sao == null)
- throw new ArgumentException("No specification attribute option found with the specified id");
+ //delete from all product collections
+ await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes,
+ z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id);
- specificationAttribute.SpecificationAttributeOptions.Remove(sao);
- await UpdateSpecificationAttribute(specificationAttribute);
+ var specificationAttribute = await GetSpecificationAttributeByOptionId(specificationAttributeOption.Id);
+ var sao = specificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x =>
+ x.Id == specificationAttributeOption.Id);
+ if (sao == null)
+ throw new ArgumentException("No specification attribute option found with the specified id");
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ specificationAttribute.SpecificationAttributeOptions.Remove(sao);
+ await UpdateSpecificationAttribute(specificationAttribute);
- //event notification
- await _mediator.EntityDeleted(specificationAttributeOption);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SPECIFICATION_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityDeleted(specificationAttributeOption);
+ }
- #endregion
+ #endregion
- #region Product specification attribute
+ #region Product specification attribute
-
- /// <summary>
- /// Inserts a product specification attribute mapping
- /// </summary>
- /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task InsertProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId)
- {
- ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
+ /// <summary>
+ /// Inserts a product specification attribute mapping
+ /// </summary>
+ /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task InsertProductSpecificationAttribute(
+ ProductSpecificationAttribute productSpecificationAttribute, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
- await _productRepository.AddToSet(productId, x => x.ProductSpecificationAttributes, productSpecificationAttribute);
+ await _productRepository.AddToSet(productId, x => x.ProductSpecificationAttributes,
+ productSpecificationAttribute);
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityInserted(productSpecificationAttribute);
- }
+ //event notification
+ await _mediator.EntityInserted(productSpecificationAttribute);
+ }
- /// <summary>
- /// Updates the product specification attribute mapping
- /// </summary>
- /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task UpdateProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId)
- {
- ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
-
- await _productRepository.UpdateToSet(productId, x => x.ProductSpecificationAttributes, z => z.Id, productSpecificationAttribute.Id, productSpecificationAttribute);
-
- //cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
-
- //event notification
- await _mediator.EntityUpdated(productSpecificationAttribute);
- }
- /// <summary>
- /// Deletes a product specification attribute mapping
- /// </summary>
- /// <param name="productSpecificationAttribute">Product specification attribute</param>
- /// <param name="productId">Product ident</param>
- public virtual async Task DeleteProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId)
- {
- ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
+ /// <summary>
+ /// Updates the product specification attribute mapping
+ /// </summary>
+ /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task UpdateProductSpecificationAttribute(
+ ProductSpecificationAttribute productSpecificationAttribute, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
- await _productRepository.PullFilter(productId, x => x.ProductSpecificationAttributes, x => x.Id, productSpecificationAttribute.Id);
+ await _productRepository.UpdateToSet(productId, x => x.ProductSpecificationAttributes, z => z.Id,
+ productSpecificationAttribute.Id, productSpecificationAttribute);
- //clear cache
- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
+ //cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- //event notification
- await _mediator.EntityDeleted(productSpecificationAttribute);
- }
+ //event notification
+ await _mediator.EntityUpdated(productSpecificationAttribute);
+ }
- /// <summary>
- /// Gets a count of product specification attribute mapping records
- /// </summary>
- /// <param name="productId">Product identifier; "" to load all records</param>
- /// <param name="specificationAttributeOptionId">The specification attribute option identifier; "" to load all records</param>
- /// <returns>Count</returns>
- public virtual int GetProductSpecificationAttributeCount(string productId = "", string specificationAttributeOptionId = "")
- {
- var query = from p in _productRepository.Table
- select p;
+ /// <summary>
+ /// Deletes a product specification attribute mapping
+ /// </summary>
+ /// <param name="productSpecificationAttribute">Product specification attribute</param>
+ /// <param name="productId">Product ident</param>
+ public virtual async Task DeleteProductSpecificationAttribute(
+ ProductSpecificationAttribute productSpecificationAttribute, string productId)
+ {
+ ArgumentNullException.ThrowIfNull(productSpecificationAttribute);
- if (!string.IsNullOrEmpty(productId))
- query = query.Where(psa => psa.Id == productId);
- if (!string.IsNullOrEmpty(specificationAttributeOptionId))
- query = query.Where(psa => psa.ProductSpecificationAttributes.Any(x => x.SpecificationAttributeOptionId == specificationAttributeOptionId));
+ await _productRepository.PullFilter(productId, x => x.ProductSpecificationAttributes, x => x.Id,
+ productSpecificationAttribute.Id);
- return query.Count();
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, productId));
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(productSpecificationAttribute);
+ }
- #endregion
+ /// <summary>
+ /// Gets a count of product specification attribute mapping records
+ /// </summary>
+ /// <param name="productId">Product identifier; "" to load all records</param>
+ /// <param name="specificationAttributeOptionId">The specification attribute option identifier; "" to load all records</param>
+ /// <returns>Count</returns>
+ public virtual int GetProductSpecificationAttributeCount(string productId = "",
+ string specificationAttributeOptionId = "")
+ {
+ var query = from p in _productRepository.Table
+ select p;
+
+ if (!string.IsNullOrEmpty(productId))
+ query = query.Where(psa => psa.Id == productId);
+ if (!string.IsNullOrEmpty(specificationAttributeOptionId))
+ query = query.Where(psa =>
+ psa.ProductSpecificationAttributes.Any(x =>
+ x.SpecificationAttributeOptionId == specificationAttributeOptionId));
+
+ return query.Count();
}
-}
+
+ #endregion
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs
index 436b9f422..6831cfc00 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs
@@ -4,185 +4,157 @@ using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
-namespace Grand.Business.Catalog.Services.Products
+namespace Grand.Business.Catalog.Services.Products;
+
+public class StockQuantityService : IStockQuantityService
{
- public class StockQuantityService : IStockQuantityService
+ public virtual int GetTotalStockQuantity(Product product, bool useReservedQuantity = true,
+ string warehouseId = "", bool total = false)
{
- public virtual int GetTotalStockQuantity(Product product, bool useReservedQuantity = true,
- string warehouseId = "", bool total = false)
- {
- ArgumentNullException.ThrowIfNull(product);
-
- if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock)
- {
- return 0;
- }
-
- if (product.UseMultipleWarehouses)
- {
- if (total)
- {
- return useReservedQuantity
- ? product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity)
- : product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
- }
+ ArgumentNullException.ThrowIfNull(product);
- var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null) return 0;
- var result = pwi.StockQuantity;
- if (useReservedQuantity)
- {
- result -= pwi.ReservedQuantity;
- }
+ if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock) return 0;
- return result;
- }
-
- if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))
- return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);
+ if (product.UseMultipleWarehouses)
+ {
+ if (total)
+ return useReservedQuantity
+ ? product.ProductWarehouseInventory.Sum(x => x.StockQuantity - x.ReservedQuantity)
+ : product.ProductWarehouseInventory.Sum(x => x.StockQuantity);
- if (product.WarehouseId == warehouseId)
- return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);
+ var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null) return 0;
+ var result = pwi.StockQuantity;
+ if (useReservedQuantity) result -= pwi.ReservedQuantity;
- return 0;
+ return result;
}
- public virtual int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination,
- bool useReservedQuantity = true, string warehouseId = "")
- {
- ArgumentNullException.ThrowIfNull(product);
- ArgumentNullException.ThrowIfNull(combination);
+ if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))
+ return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);
- if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes)
- {
- return 0;
- }
+ if (product.WarehouseId == warehouseId)
+ return product.StockQuantity - (useReservedQuantity ? product.ReservedQuantity : 0);
- if (product.UseMultipleWarehouses)
- {
- var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
- if (pwi == null) return 0;
- var result = pwi.StockQuantity;
- if (useReservedQuantity)
- {
- result -= pwi.ReservedQuantity;
- }
+ return 0;
+ }
- return result;
- }
+ public virtual int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination,
+ bool useReservedQuantity = true, string warehouseId = "")
+ {
+ ArgumentNullException.ThrowIfNull(product);
+ ArgumentNullException.ThrowIfNull(combination);
- if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))
- return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);
+ if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes) return 0;
- if (product.WarehouseId == warehouseId)
- return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);
+ if (product.UseMultipleWarehouses)
+ {
+ var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId);
+ if (pwi == null) return 0;
+ var result = pwi.StockQuantity;
+ if (useReservedQuantity) result -= pwi.ReservedQuantity;
- return 0;
+ return result;
}
- public virtual (string resource, object? arg0) FormatStockMessage(Product product, string warehouseId,
- IList<CustomAttribute> attributes)
- {
- ArgumentNullException.ThrowIfNull(product);
+ if (string.IsNullOrEmpty(warehouseId) || string.IsNullOrEmpty(product.WarehouseId))
+ return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);
- var stockMessage = string.Empty;
+ if (product.WarehouseId == warehouseId)
+ return combination.StockQuantity - (useReservedQuantity ? combination.ReservedQuantity : 0);
- return product.ManageInventoryMethodId switch {
- ManageInventoryMethod.ManageStock => StockInventoryFormatStockMessage(product, warehouseId,
- stockMessage),
- ManageInventoryMethod.ManageStockByAttributes => StockByAttributesFormatStockMessage(product,
- warehouseId, attributes, stockMessage),
- _ => (stockMessage, null)
- };
- }
+ return 0;
+ }
- private (string resource, object? arg0) StockByAttributesFormatStockMessage(Product product, string warehouseId,
- IList<CustomAttribute> attributes, string stockMessage)
- {
- if (!product.StockAvailability)
- {
- return (stockMessage, null);
- }
+ public virtual (string resource, object? arg0) FormatStockMessage(Product product, string warehouseId,
+ IList<CustomAttribute> attributes)
+ {
+ ArgumentNullException.ThrowIfNull(product);
- var combination = product.FindProductAttributeCombination(attributes);
- if (combination != null)
- {
- //combination exists
- var stockQuantity =
- GetTotalStockQuantityForCombination(product, combination, warehouseId: warehouseId);
- if (stockQuantity > 0)
- {
- if (product.DisplayStockQuantity)
- //display "in stock" with stock quantity
- {
- return ("Products.Availability.InStockWithQuantity", stockQuantity);
- }
-
- //display "in stock" without stock quantity
- {
- return ("Products.Availability.InStock", null);
- }
- }
+ var stockMessage = string.Empty;
- //out of stock
- switch (product.BackorderModeId)
- {
- case BackorderMode.NoBackorders:
- {
- return ("Products.Availability.Attributes.OutOfStock", null);
- }
- case BackorderMode.AllowQtyBelowZero:
- {
- return ("Products.Availability.Attributes.Backordering", null);
- }
- }
+ return product.ManageInventoryMethodId switch {
+ ManageInventoryMethod.ManageStock => StockInventoryFormatStockMessage(product, warehouseId,
+ stockMessage),
+ ManageInventoryMethod.ManageStockByAttributes => StockByAttributesFormatStockMessage(product,
+ warehouseId, attributes, stockMessage),
+ _ => (stockMessage, null)
+ };
+ }
- if (!combination.AllowOutOfStockOrders)
- {
- return ("Products.Availability.Attributes.OutOfStock", null);
- }
- }
- else
- {
- return ("Products.Availability.AttributeCombinationsNotExists", null);
- }
- return (stockMessage, null);
- }
+ private (string resource, object? arg0) StockByAttributesFormatStockMessage(Product product, string warehouseId,
+ IList<CustomAttribute> attributes, string stockMessage)
+ {
+ if (!product.StockAvailability) return (stockMessage, null);
- private (string resource, object? arg0) StockInventoryFormatStockMessage(Product product, string warehouseId,
- string stockMessage)
+ var combination = product.FindProductAttributeCombination(attributes);
+ if (combination != null)
{
- if (!product.StockAvailability)
- {
- return (stockMessage, null);
- }
-
- var stockQuantity = GetTotalStockQuantity(product, warehouseId: warehouseId);
+ //combination exists
+ var stockQuantity =
+ GetTotalStockQuantityForCombination(product, combination, warehouseId: warehouseId);
if (stockQuantity > 0)
{
if (product.DisplayStockQuantity)
- {
+ //display "in stock" with stock quantity
return ("Products.Availability.InStockWithQuantity", stockQuantity);
- }
+ //display "in stock" without stock quantity
{
return ("Products.Availability.InStock", null);
}
}
+ //out of stock
switch (product.BackorderModeId)
{
case BackorderMode.NoBackorders:
{
- return ("Products.Availability.OutOfStock", null);
+ return ("Products.Availability.Attributes.OutOfStock", null);
}
case BackorderMode.AllowQtyBelowZero:
{
- return ("Products.Availability.Backordering", null);
+ return ("Products.Availability.Attributes.Backordering", null);
}
}
- return (stockMessage, null);
+ if (!combination.AllowOutOfStockOrders) return ("Products.Availability.Attributes.OutOfStock", null);
+ }
+ else
+ {
+ return ("Products.Availability.AttributeCombinationsNotExists", null);
}
+
+ return (stockMessage, null);
+ }
+
+ private (string resource, object? arg0) StockInventoryFormatStockMessage(Product product, string warehouseId,
+ string stockMessage)
+ {
+ if (!product.StockAvailability) return (stockMessage, null);
+
+ var stockQuantity = GetTotalStockQuantity(product, warehouseId: warehouseId);
+ if (stockQuantity > 0)
+ {
+ if (product.DisplayStockQuantity) return ("Products.Availability.InStockWithQuantity", stockQuantity);
+
+ {
+ return ("Products.Availability.InStock", null);
+ }
+ }
+
+ switch (product.BackorderModeId)
+ {
+ case BackorderMode.NoBackorders:
+ {
+ return ("Products.Availability.OutOfStock", null);
+ }
+ case BackorderMode.AllowQtyBelowZero:
+ {
+ return ("Products.Availability.Backordering", null);
+ }
+ }
+
+ return (stockMessage, null);
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs
index b2bfe1f33..b5437aa56 100644
--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs
@@ -1,125 +1,125 @@
using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Data;
+using Grand.Domain.Tax;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Data;
-using Grand.Domain.Tax;
using MediatR;
-namespace Grand.Business.Catalog.Services.Tax
+namespace Grand.Business.Catalog.Services.Tax;
+
+/// <summary>
+/// Tax category service
+/// </summary>
+public class TaxCategoryService : ITaxCategoryService
{
+ #region Ctor
+
/// <summary>
- /// Tax category service
+ /// Ctor
/// </summary>
- public class TaxCategoryService : ITaxCategoryService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="taxCategoryRepository">Tax category repository</param>
+ /// <param name="mediator">Mediator</param>
+ public TaxCategoryService(ICacheBase cacheBase,
+ IRepository<TaxCategory> taxCategoryRepository,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<TaxCategory> _taxCategoryRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ _cacheBase = cacheBase;
+ _taxCategoryRepository = taxCategoryRepository;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="taxCategoryRepository">Tax category repository</param>
- /// <param name="mediator">Mediator</param>
- public TaxCategoryService(ICacheBase cacheBase,
- IRepository<TaxCategory> taxCategoryRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _taxCategoryRepository = taxCategoryRepository;
- _mediator = mediator;
- }
+ private readonly IRepository<TaxCategory> _taxCategoryRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets all tax categories
- /// </summary>
- /// <returns>Tax categories</returns>
- public virtual async Task<IList<TaxCategory>> GetAllTaxCategories()
- {
- var key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from tc in _taxCategoryRepository.Table
- orderby tc.DisplayOrder
- select tc;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a tax category
- /// </summary>
- /// <param name="taxCategoryId">Tax category identifier</param>
- /// <returns>Tax category</returns>
- public virtual Task<TaxCategory> GetTaxCategoryById(string taxCategoryId)
- {
- var key = string.Format(CacheKey.TAXCATEGORIES_BY_ID_KEY, taxCategoryId);
- return _cacheBase.GetAsync(key, () => _taxCategoryRepository.GetByIdAsync(taxCategoryId));
- }
-
- /// <summary>
- /// Inserts a tax category
- /// </summary>
- /// <param name="taxCategory">Tax category</param>
- public virtual async Task InsertTaxCategory(TaxCategory taxCategory)
+ /// <summary>
+ /// Gets all tax categories
+ /// </summary>
+ /// <returns>Tax categories</returns>
+ public virtual async Task<IList<TaxCategory>> GetAllTaxCategories()
+ {
+ var key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY);
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(taxCategory);
+ var query = from tc in _taxCategoryRepository.Table
+ orderby tc.DisplayOrder
+ select tc;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _taxCategoryRepository.InsertAsync(taxCategory);
+ /// <summary>
+ /// Gets a tax category
+ /// </summary>
+ /// <param name="taxCategoryId">Tax category identifier</param>
+ /// <returns>Tax category</returns>
+ public virtual Task<TaxCategory> GetTaxCategoryById(string taxCategoryId)
+ {
+ var key = string.Format(CacheKey.TAXCATEGORIES_BY_ID_KEY, taxCategoryId);
+ return _cacheBase.GetAsync(key, () => _taxCategoryRepository.GetByIdAsync(taxCategoryId));
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
+ /// <summary>
+ /// Inserts a tax category
+ /// </summary>
+ /// <param name="taxCategory">Tax category</param>
+ public virtual async Task InsertTaxCategory(TaxCategory taxCategory)
+ {
+ ArgumentNullException.ThrowIfNull(taxCategory);
- //event notification
- await _mediator.EntityInserted(taxCategory);
- }
+ await _taxCategoryRepository.InsertAsync(taxCategory);
- /// <summary>
- /// Updates the tax category
- /// </summary>
- /// <param name="taxCategory">Tax category</param>
- public virtual async Task UpdateTaxCategory(TaxCategory taxCategory)
- {
- ArgumentNullException.ThrowIfNull(taxCategory);
+ await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
- await _taxCategoryRepository.UpdateAsync(taxCategory);
+ //event notification
+ await _mediator.EntityInserted(taxCategory);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
+ /// <summary>
+ /// Updates the tax category
+ /// </summary>
+ /// <param name="taxCategory">Tax category</param>
+ public virtual async Task UpdateTaxCategory(TaxCategory taxCategory)
+ {
+ ArgumentNullException.ThrowIfNull(taxCategory);
- //event notification
- await _mediator.EntityUpdated(taxCategory);
- }
- /// <summary>
- /// Deletes a tax category
- /// </summary>
- /// <param name="taxCategory">Tax category</param>
- public virtual async Task DeleteTaxCategory(TaxCategory taxCategory)
- {
- ArgumentNullException.ThrowIfNull(taxCategory);
+ await _taxCategoryRepository.UpdateAsync(taxCategory);
+
+ await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
+
+ //event notification
+ await _mediator.EntityUpdated(taxCategory);
+ }
- await _taxCategoryRepository.DeleteAsync(taxCategory);
+ /// <summary>
+ /// Deletes a tax category
+ /// </summary>
+ /// <param name="taxCategory">Tax category</param>
+ public virtual async Task DeleteTaxCategory(TaxCategory taxCategory)
+ {
+ ArgumentNullException.ThrowIfNull(taxCategory);
- //clear tax categories cache
- await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
+ await _taxCategoryRepository.DeleteAsync(taxCategory);
- //clear product cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
+ //clear tax categories cache
+ await _cacheBase.RemoveByPrefix(CacheKey.TAXCATEGORIES_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(taxCategory);
- }
+ //clear product cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(taxCategory);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
index 71bc87a0a..abeddc1a3 100644
--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
@@ -1,7 +1,7 @@
using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Interfaces.Catalog.Tax;
-using Grand.Business.Core.Utilities.Catalog;
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Utilities.Catalog;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
@@ -12,655 +12,627 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Extensions;
using Microsoft.Extensions.Logging;
-namespace Grand.Business.Catalog.Services.Tax
+namespace Grand.Business.Catalog.Services.Tax;
+
+/// <summary>
+/// Tax service
+/// </summary>
+public class TaxService : ITaxService
{
- /// <summary>
- /// Tax service
- /// </summary>
- public class TaxService : ITaxService
+ #region Ctor
+
+ public TaxService(
+ IWorkContext workContext,
+ IGroupService groupService,
+ IGeoLookupService geoLookupService,
+ ICountryService countryService,
+ IEnumerable<ITaxProvider> taxProviders,
+ ILogger<TaxService> logger,
+ TaxSettings taxSettings,
+ TaxProviderSettings taxProviderSettings,
+ CustomerSettings customerSettings,
+ AddressSettings addressSettings)
{
- #region Fields
-
- private readonly IWorkContext _workContext;
- private readonly IGroupService _groupService;
- private readonly IGeoLookupService _geoLookupService;
- private readonly ICountryService _countryService;
- private readonly IEnumerable<ITaxProvider> _taxProviders;
- private readonly ILogger<TaxService> _logger;
- private readonly TaxSettings _taxSettings;
- private readonly TaxProviderSettings _taxProviderSettings;
- private readonly CustomerSettings _customerSettings;
- private readonly AddressSettings _addressSettings;
-
- #endregion
-
- #region Ctor
-
- public TaxService(
- IWorkContext workContext,
- IGroupService groupService,
- IGeoLookupService geoLookupService,
- ICountryService countryService,
- IEnumerable<ITaxProvider> taxProviders,
- ILogger<TaxService> logger,
- TaxSettings taxSettings,
- TaxProviderSettings taxProviderSettings,
- CustomerSettings customerSettings,
- AddressSettings addressSettings)
- {
- _workContext = workContext;
- _groupService = groupService;
- _taxSettings = taxSettings;
- _taxProviderSettings = taxProviderSettings;
- _taxProviders = taxProviders;
- _geoLookupService = geoLookupService;
- _logger = logger;
- _countryService = countryService;
- _customerSettings = customerSettings;
- _addressSettings = addressSettings;
- }
+ _workContext = workContext;
+ _groupService = groupService;
+ _taxSettings = taxSettings;
+ _taxProviderSettings = taxProviderSettings;
+ _taxProviders = taxProviders;
+ _geoLookupService = geoLookupService;
+ _logger = logger;
+ _countryService = countryService;
+ _customerSettings = customerSettings;
+ _addressSettings = addressSettings;
+ }
- #endregion
+ #endregion
- #region Utilities
+ #region Fields
- /// <summary>
- /// Get a value indicating whether a customer is consumer (a person, not a company) located in Europe Union
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <returns>Result</returns>
- protected virtual async Task<bool> IsEuConsumer(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ private readonly IWorkContext _workContext;
+ private readonly IGroupService _groupService;
+ private readonly IGeoLookupService _geoLookupService;
+ private readonly ICountryService _countryService;
+ private readonly IEnumerable<ITaxProvider> _taxProviders;
+ private readonly ILogger<TaxService> _logger;
+ private readonly TaxSettings _taxSettings;
+ private readonly TaxProviderSettings _taxProviderSettings;
+ private readonly CustomerSettings _customerSettings;
+ private readonly AddressSettings _addressSettings;
- Country country = null;
+ #endregion
- //get country from billing address
- if (_addressSettings.CountryEnabled && customer.BillingAddress != null)
- {
- country = await _countryService.GetCountryById(customer.BillingAddress.CountryId);
- }
- //get country specified during registration?
- if (country == null && _customerSettings.CountryEnabled)
- {
- var countryId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId);
- country = await _countryService.GetCountryById(countryId);
- }
+ #region Utilities
- //get country by IP address
- if (country == null && _taxSettings.GetCountryByIPAddress)
- {
- var ipAddress = customer.LastIpAddress;
- var countryIsoCode = _geoLookupService.CountryIsoCode(ipAddress);
- country = await _countryService.GetCountryByTwoLetterIsoCode(countryIsoCode);
- }
+ /// <summary>
+ /// Get a value indicating whether a customer is consumer (a person, not a company) located in Europe Union
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <returns>Result</returns>
+ protected virtual async Task<bool> IsEuConsumer(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- //we cannot detect country
- if (country is not { SubjectToVat: true })
- return false;
-
- //company (business) or consumer?
- var customerVatStatus = (VatNumberStatus)customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId);
- return customerVatStatus != VatNumberStatus.Valid;
+ Country country = null;
+
+ //get country from billing address
+ if (_addressSettings.CountryEnabled && customer.BillingAddress != null)
+ country = await _countryService.GetCountryById(customer.BillingAddress.CountryId);
+ //get country specified during registration?
+ if (country == null && _customerSettings.CountryEnabled)
+ {
+ var countryId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId);
+ country = await _countryService.GetCountryById(countryId);
}
- /// <summary>
- /// Create request for tax calculation
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="taxCategoryId">Tax category identifier</param>
- /// <param name="customer">Customer</param>
- /// <param name="price">Price</param>
- /// <returns>Package for tax calculation</returns>
- protected virtual async Task<TaxRequest> CreateCalculateTaxRequest(Product product,
- string taxCategoryId, Customer customer, double price)
+ //get country by IP address
+ if (country == null && _taxSettings.GetCountryByIPAddress)
{
- ArgumentNullException.ThrowIfNull(customer);
+ var ipAddress = customer.LastIpAddress;
+ var countryIsoCode = _geoLookupService.CountryIsoCode(ipAddress);
+ country = await _countryService.GetCountryByTwoLetterIsoCode(countryIsoCode);
+ }
- var calculateTaxRequest = new TaxRequest {
- Customer = customer,
- Product = product,
- Price = price
- };
+ //we cannot detect country
+ if (country is not { SubjectToVat: true })
+ return false;
- if (!string.IsNullOrEmpty(taxCategoryId))
- {
- calculateTaxRequest.TaxCategoryId = taxCategoryId;
- }
- else
- {
- if (product != null)
- calculateTaxRequest.TaxCategoryId = product.TaxCategoryId;
- }
- var basedOn = _taxSettings.TaxBasedOn;
- if (_taxSettings.EuVatEnabled)
- {
- //telecommunications, broadcasting and electronic services?
- if (product is { IsTele: true })
- {
- //Europe Union consumer?
- if (await IsEuConsumer(customer))
- {
- //We must charge VAT in the EU country where the customer belongs (not where the business is based)
- basedOn = TaxBasedOn.BillingAddress;
- }
- }
- }
- if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null)
- basedOn = TaxBasedOn.DefaultAddress;
- if (basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null)
- basedOn = TaxBasedOn.DefaultAddress;
+ //company (business) or consumer?
+ var customerVatStatus =
+ (VatNumberStatus)customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId);
+ return customerVatStatus != VatNumberStatus.Valid;
+ }
- Address address;
+ /// <summary>
+ /// Create request for tax calculation
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="taxCategoryId">Tax category identifier</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="price">Price</param>
+ /// <returns>Package for tax calculation</returns>
+ protected virtual async Task<TaxRequest> CreateCalculateTaxRequest(Product product,
+ string taxCategoryId, Customer customer, double price)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- switch (basedOn)
- {
- case TaxBasedOn.BillingAddress:
- {
- address = customer.BillingAddress;
- }
- break;
- case TaxBasedOn.ShippingAddress:
- {
- address = customer.ShippingAddress;
- }
- break;
- case TaxBasedOn.DefaultAddress:
- default:
- {
- address = _taxSettings.DefaultTaxAddress;
- }
- break;
- }
+ var calculateTaxRequest = new TaxRequest {
+ Customer = customer,
+ Product = product,
+ Price = price
+ };
- calculateTaxRequest.Address = address;
- return calculateTaxRequest;
+ if (!string.IsNullOrEmpty(taxCategoryId))
+ {
+ calculateTaxRequest.TaxCategoryId = taxCategoryId;
}
-
- /// <summary>
- /// Calculated price
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="percent">Percent</param>
- /// <param name="increase">Increase</param>
- /// <returns>New price</returns>
- protected virtual double CalculatePrice(double price, double percent, bool increase)
+ else
{
- if (percent == 0)
- return price;
-
- var result = increase ? price * (1 + percent / 100) : price / (1 + percent / 100);
-
- if (result == 0)
- return 0;
-
- return Math.Round(result, _taxSettings.CalculateRoundPrice, _taxSettings.MidpointRounding);
+ if (product != null)
+ calculateTaxRequest.TaxCategoryId = product.TaxCategoryId;
}
- /// <summary>
- /// Gets tax rate
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="taxCategoryId">Tax category identifier</param>
- /// <param name="customer">Customer</param>
- /// <param name="price">Price (taxable value)</param>
- protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId,
- Customer customer, double price)
+ var basedOn = _taxSettings.TaxBasedOn;
+ if (_taxSettings.EuVatEnabled)
+ //telecommunications, broadcasting and electronic services?
+ if (product is { IsTele: true })
+ //Europe Union consumer?
+ if (await IsEuConsumer(customer))
+ //We must charge VAT in the EU country where the customer belongs (not where the business is based)
+ basedOn = TaxBasedOn.BillingAddress;
+ if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null)
+ basedOn = TaxBasedOn.DefaultAddress;
+ if (basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null)
+ basedOn = TaxBasedOn.DefaultAddress;
+
+ Address address;
+
+ switch (basedOn)
{
- double taxRate = 0;
- var isTaxable = true;
-
- //active tax provider
- var activeTaxProvider = LoadActiveTaxProvider();
- if (activeTaxProvider == null)
- return (taxRate, true);
-
- //tax request
- var calculateTaxRequest = await CreateCalculateTaxRequest(product, taxCategoryId, customer, price);
-
- //tax exempt
- if (await IsTaxExempt(product, calculateTaxRequest.Customer))
+ case TaxBasedOn.BillingAddress:
{
- isTaxable = false;
+ address = customer.BillingAddress;
}
- //make EU VAT exempt validation (the European Union Value Added Tax)
- if (isTaxable &&
- _taxSettings.EuVatEnabled &&
- await IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer))
+ break;
+ case TaxBasedOn.ShippingAddress:
{
- //VAT is not chargeable
- isTaxable = false;
+ address = customer.ShippingAddress;
}
-
- //get tax rate
- var calculateTaxResult = await activeTaxProvider.GetTaxRate(calculateTaxRequest);
- if (calculateTaxResult.Success)
- {
- //ensure that tax is equal or greater than zero
- if (calculateTaxResult.TaxRate < 0)
- calculateTaxResult.TaxRate = 0;
-
- taxRate = calculateTaxResult.TaxRate;
- }
- else
+ break;
+ case TaxBasedOn.DefaultAddress:
+ default:
{
- foreach (var error in calculateTaxResult.Errors)
- {
- _logger.LogError("{FriendlyName} - {Error}", activeTaxProvider.FriendlyName, error);
- }
+ address = _taxSettings.DefaultTaxAddress;
}
- return (taxRate, isTaxable);
+ break;
}
+ calculateTaxRequest.Address = address;
+ return calculateTaxRequest;
+ }
- #endregion
+ /// <summary>
+ /// Calculated price
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="percent">Percent</param>
+ /// <param name="increase">Increase</param>
+ /// <returns>New price</returns>
+ protected virtual double CalculatePrice(double price, double percent, bool increase)
+ {
+ if (percent == 0)
+ return price;
- #region Methods
+ var result = increase ? price * (1 + percent / 100) : price / (1 + percent / 100);
- /// <summary>
- /// Load active tax provider
- /// </summary>
- /// <returns>Active tax provider</returns>
- public virtual ITaxProvider LoadActiveTaxProvider()
- {
- var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName) ??
- LoadAllTaxProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id).FirstOrDefault();
- return taxProvider;
- }
+ if (result == 0)
+ return 0;
+
+ return Math.Round(result, _taxSettings.CalculateRoundPrice, _taxSettings.MidpointRounding);
+ }
- /// <summary>
- /// Load tax provider by system name
- /// </summary>
- /// <param name="systemName">System name</param>
- /// <returns>Found tax provider</returns>
- public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName)
+ /// <summary>
+ /// Gets tax rate
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="taxCategoryId">Tax category identifier</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="price">Price (taxable value)</param>
+ protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId,
+ Customer customer, double price)
+ {
+ double taxRate = 0;
+ var isTaxable = true;
+
+ //active tax provider
+ var activeTaxProvider = LoadActiveTaxProvider();
+ if (activeTaxProvider == null)
+ return (taxRate, true);
+
+ //tax request
+ var calculateTaxRequest = await CreateCalculateTaxRequest(product, taxCategoryId, customer, price);
+
+ //tax exempt
+ if (await IsTaxExempt(product, calculateTaxRequest.Customer)) isTaxable = false;
+ //make EU VAT exempt validation (the European Union Value Added Tax)
+ if (isTaxable &&
+ _taxSettings.EuVatEnabled &&
+ await IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer))
+ //VAT is not chargeable
+ isTaxable = false;
+
+ //get tax rate
+ var calculateTaxResult = await activeTaxProvider.GetTaxRate(calculateTaxRequest);
+ if (calculateTaxResult.Success)
{
- return _taxProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
- }
+ //ensure that tax is equal or greater than zero
+ if (calculateTaxResult.TaxRate < 0)
+ calculateTaxResult.TaxRate = 0;
- /// <summary>
- /// Load all tax providers
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="storeId">Store ident</param>
- /// <returns>Tax providers</returns>
- public virtual IList<ITaxProvider> LoadAllTaxProviders(Customer customer = null, string storeId = "")
+ taxRate = calculateTaxResult.TaxRate;
+ }
+ else
{
- return _taxProviders
- .Where(x =>
- x.IsAuthenticateStore(storeId) &&
- x.IsAuthenticateGroup(customer))
- .OrderBy(x => x.Priority).ToList();
+ foreach (var error in calculateTaxResult.Errors)
+ _logger.LogError("{FriendlyName} - {Error}", activeTaxProvider.FriendlyName, error);
}
+ return (taxRate, isTaxable);
+ }
+ #endregion
- /// <summary>
- /// Gets price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="price">Price</param>
- /// <returns>Price</returns>
- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price)
- {
- var customer = _workContext.CurrentCustomer;
- return await GetProductPrice(product, price, customer);
- }
+ #region Methods
- /// <summary>
- /// Gets price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="price">Price</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,
- Customer customer)
- {
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
- return await GetProductPrice(product, price, includingTax, customer);
- }
+ /// <summary>
+ /// Load active tax provider
+ /// </summary>
+ /// <returns>Active tax provider</returns>
+ public virtual ITaxProvider LoadActiveTaxProvider()
+ {
+ var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName) ??
+ LoadAllTaxProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id)
+ .FirstOrDefault();
+ return taxProvider;
+ }
- /// <summary>
- /// Gets price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="price">Price</param>
- /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,
- bool includingTax, Customer customer)
- {
- var priceIncludesTax = _taxSettings.PricesIncludeTax;
- return await GetProductPrice(product, string.Empty, price, includingTax,
- customer, priceIncludesTax);
- }
+ /// <summary>
+ /// Load tax provider by system name
+ /// </summary>
+ /// <param name="systemName">System name</param>
+ /// <returns>Found tax provider</returns>
+ public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName)
+ {
+ return _taxProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
+ }
- /// <summary>
- /// Gets price
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="taxCategoryId">Tax category identifier</param>
- /// <param name="price">Price</param>
- /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
- /// <param name="customer">Customer</param>
- /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>
- /// <returns>Price</returns>
- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, string taxCategoryId,
- double price, bool includingTax, Customer customer,
- bool priceIncludesTax)
- {
+ /// <summary>
+ /// Load all tax providers
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="storeId">Store ident</param>
+ /// <returns>Tax providers</returns>
+ public virtual IList<ITaxProvider> LoadAllTaxProviders(Customer customer = null, string storeId = "")
+ {
+ return _taxProviders
+ .Where(x =>
+ x.IsAuthenticateStore(storeId) &&
+ x.IsAuthenticateGroup(customer))
+ .OrderBy(x => x.Priority).ToList();
+ }
- //no need to calculate tax rate if passed "price" is 0
- if (price == 0)
- {
- return (0, 0);
- }
- var taxrates = await GetTaxRate(product, taxCategoryId, customer, price);
+ /// <summary>
+ /// Gets price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="price">Price</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price)
+ {
+ var customer = _workContext.CurrentCustomer;
+ return await GetProductPrice(product, price, customer);
+ }
+
+ /// <summary>
+ /// Gets price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="price">Price</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,
+ Customer customer)
+ {
+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ return await GetProductPrice(product, price, includingTax, customer);
+ }
+
+ /// <summary>
+ /// Gets price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="price">Price</param>
+ /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,
+ bool includingTax, Customer customer)
+ {
+ var priceIncludesTax = _taxSettings.PricesIncludeTax;
+ return await GetProductPrice(product, string.Empty, price, includingTax,
+ customer, priceIncludesTax);
+ }
+
+ /// <summary>
+ /// Gets price
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="taxCategoryId">Tax category identifier</param>
+ /// <param name="price">Price</param>
+ /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
+ /// <param name="customer">Customer</param>
+ /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product,
+ string taxCategoryId,
+ double price, bool includingTax, Customer customer,
+ bool priceIncludesTax)
+ {
+ //no need to calculate tax rate if passed "price" is 0
+ if (price == 0) return (0, 0);
+
+ var taxrates = await GetTaxRate(product, taxCategoryId, customer, price);
- if (priceIncludesTax)
+ if (priceIncludesTax)
+ {
+ //"price" already includes tax
+ if (includingTax)
{
- //"price" already includes tax
- if (includingTax)
- {
- //we should calculate price WITH tax
- if (!taxrates.isTaxable)
- {
- //but our request is not taxable
- //hence we should calculate price WITHOUT tax
- price = CalculatePrice(price, taxrates.taxRate, false);
- }
- }
- else
- {
- //we should calculate price WITHOUT tax
+ //we should calculate price WITH tax
+ if (!taxrates.isTaxable)
+ //but our request is not taxable
+ //hence we should calculate price WITHOUT tax
price = CalculatePrice(price, taxrates.taxRate, false);
- }
}
else
{
- //"price" doesn't include tax
- if (includingTax)
- {
- //we should calculate price WITH tax
- //do it only when price is taxable
- if (taxrates.isTaxable)
- {
- price = CalculatePrice(price, taxrates.taxRate, true);
- }
- }
- }
-
- if (!taxrates.isTaxable)
- {
- //we return 0% tax rate in case a request is not taxable
- taxrates.taxRate = 0;
+ //we should calculate price WITHOUT tax
+ price = CalculatePrice(price, taxrates.taxRate, false);
}
-
- //allowed to support negative price adjustments
- //if (price < 0)
- // price = 0;
-
- return (price, taxrates.taxRate);
}
-
- public virtual async Task<TaxProductPrice> GetTaxProductPrice(
- Product product,
- Customer customer,
- double unitPrice,
- double unitPriceWithoutDisc,
- int quantity,
- double subTotal,
- double discountAmount,
- bool priceIncludesTax
- )
+ else
{
- var taxrates = await GetTaxRate(product, product.TaxCategoryId, customer, 0);
+ //"price" doesn't include tax
+ if (includingTax)
+ //we should calculate price WITH tax
+ //do it only when price is taxable
+ if (taxrates.isTaxable)
+ price = CalculatePrice(price, taxrates.taxRate, true);
+ }
- var productPrice = new TaxProductPrice
- {
- TaxRate = taxrates.taxRate,
- Quantity = quantity
- };
+ if (!taxrates.isTaxable)
+ //we return 0% tax rate in case a request is not taxable
+ taxrates.taxRate = 0;
- if (priceIncludesTax)
- {
- if (taxrates.isTaxable)
- {
- productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;
- productPrice.UnitPriceWithoutDiscExclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
+ //allowed to support negative price adjustments
+ //if (price < 0)
+ // price = 0;
- productPrice.UnitPriceInclTax = unitPrice;
- productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
+ return (price, taxrates.taxRate);
+ }
+
+ public virtual async Task<TaxProductPrice> GetTaxProductPrice(
+ Product product,
+ Customer customer,
+ double unitPrice,
+ double unitPriceWithoutDisc,
+ int quantity,
+ double subTotal,
+ double discountAmount,
+ bool priceIncludesTax
+ )
+ {
+ var taxrates = await GetTaxRate(product, product.TaxCategoryId, customer, 0);
- productPrice.SubTotalInclTax = subTotal;
- productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
+ var productPrice = new TaxProductPrice {
+ TaxRate = taxrates.taxRate,
+ Quantity = quantity
+ };
- productPrice.DiscountAmountInclTax = discountAmount;
- productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
- }
- else
- {
- productPrice.UnitPriceWithoutDiscInclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
- productPrice.UnitPriceWithoutDiscExclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
+ if (priceIncludesTax)
+ {
+ if (taxrates.isTaxable)
+ {
+ productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;
+ productPrice.UnitPriceWithoutDiscExclTax =
+ CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
- productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
- productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
+ productPrice.UnitPriceInclTax = unitPrice;
+ productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
- productPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
- productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
+ productPrice.SubTotalInclTax = subTotal;
+ productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
- productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
- productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
- }
+ productPrice.DiscountAmountInclTax = discountAmount;
+ productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
}
else
{
- if (taxrates.isTaxable)
- {
- productPrice.UnitPriceWithoutDiscInclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, true);
- productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;
+ productPrice.UnitPriceWithoutDiscInclTax =
+ CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
+ productPrice.UnitPriceWithoutDiscExclTax =
+ CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, false);
- productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, true);
- productPrice.UnitPriceExclTax = unitPrice;
+ productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
+ productPrice.UnitPriceExclTax = CalculatePrice(unitPrice, taxrates.taxRate, false);
- productPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, true);
- productPrice.SubTotalExclTax = subTotal;
+ productPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
+ productPrice.SubTotalExclTax = CalculatePrice(subTotal, taxrates.taxRate, false);
- productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, true);
- productPrice.DiscountAmountExclTax = discountAmount;
- }
- else
- {
- productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;
- productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;
+ productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
+ productPrice.DiscountAmountExclTax = CalculatePrice(discountAmount, taxrates.taxRate, false);
+ }
+ }
+ else
+ {
+ if (taxrates.isTaxable)
+ {
+ productPrice.UnitPriceWithoutDiscInclTax = CalculatePrice(unitPriceWithoutDisc, taxrates.taxRate, true);
+ productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;
- productPrice.UnitPriceInclTax = unitPrice;
- productPrice.UnitPriceExclTax = unitPrice;
+ productPrice.UnitPriceInclTax = CalculatePrice(unitPrice, taxrates.taxRate, true);
+ productPrice.UnitPriceExclTax = unitPrice;
- productPrice.SubTotalInclTax = subTotal;
- productPrice.SubTotalExclTax = subTotal;
+ productPrice.SubTotalInclTax = CalculatePrice(subTotal, taxrates.taxRate, true);
+ productPrice.SubTotalExclTax = subTotal;
- productPrice.DiscountAmountInclTax = discountAmount;
- productPrice.DiscountAmountExclTax = discountAmount;
- }
+ productPrice.DiscountAmountInclTax = CalculatePrice(discountAmount, taxrates.taxRate, true);
+ productPrice.DiscountAmountExclTax = discountAmount;
}
-
- if (!taxrates.isTaxable)
+ else
{
- //we return 0% tax rate in case a request is not taxable
- taxrates.taxRate = 0;
- }
- return productPrice;
- }
+ productPrice.UnitPriceWithoutDiscInclTax = unitPriceWithoutDisc;
+ productPrice.UnitPriceWithoutDiscExclTax = unitPriceWithoutDisc;
- /// <summary>
- /// Gets shipping price
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer)
- {
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
- return await GetShippingPrice(price, includingTax, customer);
- }
+ productPrice.UnitPriceInclTax = unitPrice;
+ productPrice.UnitPriceExclTax = unitPrice;
- /// <summary>
- /// Gets shipping price
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax, Customer customer)
- {
- if (!_taxSettings.ShippingIsTaxable)
- {
- return (price, 0);
- }
+ productPrice.SubTotalInclTax = subTotal;
+ productPrice.SubTotalExclTax = subTotal;
- var taxCategoryId = _taxSettings.ShippingTaxCategoryId;
- var priceIncludesTax = _taxSettings.ShippingPriceIncludesTax;
- var prices = await GetProductPrice(null, taxCategoryId, price, includingTax, customer,
- priceIncludesTax);
- return (prices.productprice, prices.taxRate);
+ productPrice.DiscountAmountInclTax = discountAmount;
+ productPrice.DiscountAmountExclTax = discountAmount;
+ }
}
- /// <summary>
- /// Gets payment method additional handling fee
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, Customer customer)
- {
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
- return await GetPaymentMethodAdditionalFee(price, includingTax, customer);
- }
+ if (!taxrates.isTaxable)
+ //we return 0% tax rate in case a request is not taxable
+ taxrates.taxRate = 0;
+ return productPrice;
+ }
- /// <summary>
- /// Gets payment method additional handling fee
- /// </summary>
- /// <param name="price">Price</param>
- /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, bool includingTax, Customer customer)
- {
- if (!_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
- {
- return (price, 0);
- }
- var taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxCategoryId;
- var priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax;
- var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,
- priceIncludesTax);
- return (prices.productprice, prices.taxRate);
- }
+ /// <summary>
+ /// Gets shipping price
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer)
+ {
+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ return await GetShippingPrice(price, includingTax, customer);
+ }
- /// <summary>
- /// Gets checkout attribute value price
- /// </summary>
- /// <param name="ca">Checkout attribute</param>
- /// <param name="cav">Checkout attribute value</param>
- /// <returns>Price</returns>
- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav)
- {
- var customer = _workContext.CurrentCustomer;
- return await GetCheckoutAttributePrice(ca, cav, customer);
- }
+ /// <summary>
+ /// Gets shipping price
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax,
+ Customer customer)
+ {
+ if (!_taxSettings.ShippingIsTaxable) return (price, 0);
- /// <summary>
- /// Gets checkout attribute value price
- /// </summary>
- /// <param name="ca">Checkout attribute</param>
- /// <param name="cav">Checkout attribute value</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, Customer customer)
- {
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
- return await GetCheckoutAttributePrice(ca, cav, includingTax, customer);
- }
+ var taxCategoryId = _taxSettings.ShippingTaxCategoryId;
+ var priceIncludesTax = _taxSettings.ShippingPriceIncludesTax;
+ var prices = await GetProductPrice(null, taxCategoryId, price, includingTax, customer,
+ priceIncludesTax);
+ return (prices.productprice, prices.taxRate);
+ }
- /// <summary>
- /// Gets checkout attribute value price
- /// </summary>
- /// <param name="ca">Checkout attribute</param>
- /// <param name="cav">Checkout attribute value</param>
- /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
- /// <param name="customer">Customer</param>
- /// <returns>Price</returns>
- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, bool includingTax, Customer customer)
- {
- ArgumentNullException.ThrowIfNull(ca);
- ArgumentNullException.ThrowIfNull(cav);
+ /// <summary>
+ /// Gets payment method additional handling fee
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price,
+ Customer customer)
+ {
+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ return await GetPaymentMethodAdditionalFee(price, includingTax, customer);
+ }
- var price = cav.PriceAdjustment;
- if (ca.IsTaxExempt)
- {
- return (price, 0);
- }
+ /// <summary>
+ /// Gets payment method additional handling fee
+ /// </summary>
+ /// <param name="price">Price</param>
+ /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price,
+ bool includingTax, Customer customer)
+ {
+ if (!_taxSettings.PaymentMethodAdditionalFeeIsTaxable) return (price, 0);
+ var taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxCategoryId;
+ var priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax;
+ var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,
+ priceIncludesTax);
+ return (prices.productprice, prices.taxRate);
+ }
- var priceIncludesTax = _taxSettings.PricesIncludeTax;
- var taxClassId = ca.TaxCategoryId;
- var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,
- priceIncludesTax);
+ /// <summary>
+ /// Gets checkout attribute value price
+ /// </summary>
+ /// <param name="ca">Checkout attribute</param>
+ /// <param name="cav">Checkout attribute value</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,
+ CheckoutAttributeValue cav)
+ {
+ var customer = _workContext.CurrentCustomer;
+ return await GetCheckoutAttributePrice(ca, cav, customer);
+ }
- return (prices.productprice, prices.taxRate);
- }
+ /// <summary>
+ /// Gets checkout attribute value price
+ /// </summary>
+ /// <param name="ca">Checkout attribute</param>
+ /// <param name="cav">Checkout attribute value</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,
+ CheckoutAttributeValue cav, Customer customer)
+ {
+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ return await GetCheckoutAttributePrice(ca, cav, includingTax, customer);
+ }
+ /// <summary>
+ /// Gets checkout attribute value price
+ /// </summary>
+ /// <param name="ca">Checkout attribute</param>
+ /// <param name="cav">Checkout attribute value</param>
+ /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Price</returns>
+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,
+ CheckoutAttributeValue cav, bool includingTax, Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(ca);
+ ArgumentNullException.ThrowIfNull(cav);
+ var price = cav.PriceAdjustment;
+ if (ca.IsTaxExempt) return (price, 0);
- /// <summary>
- /// Gets a value indicating whether a product is tax exempt
- /// </summary>
- /// <param name="product">Product</param>
- /// <param name="customer">Customer</param>
- /// <returns>A value indicating whether a product is tax exempt</returns>
- public virtual async Task<bool> IsTaxExempt(Product product, Customer customer)
- {
- if (customer == null) return product is { IsTaxExempt: true };
- if (customer.IsTaxExempt)
- return true;
+ var priceIncludesTax = _taxSettings.PricesIncludeTax;
+ var taxClassId = ca.TaxCategoryId;
+ var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,
+ priceIncludesTax);
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- if (customerGroups.Any(cr => cr.TaxExempt))
- return true;
+ return (prices.productprice, prices.taxRate);
+ }
- return product is { IsTaxExempt: true };
- }
- /// <summary>
- /// Gets a value indicating whether EU VAT exempt (the European Union Value Added Tax)
- /// </summary>
- /// <param name="address">Address</param>
- /// <param name="customer">Customer</param>
- /// <returns>Result</returns>
- public virtual async Task<bool> IsVatExempt(Address address, Customer customer)
- {
- if (!_taxSettings.EuVatEnabled)
- return false;
-
- if (address == null || string.IsNullOrEmpty(address.CountryId) || customer == null)
- return false;
-
- var country = await _countryService.GetCountryById(address.CountryId);
- if (!country.SubjectToVat)
- // VAT not chargeable if shipping outside VAT zone
- return true;
-
- // VAT not chargeable if address, customer and config meet our VAT exemption requirements:
- // returns true if this customer is VAT exempt because they are shipping within the EU but outside our shop country, they have supplied a validated VAT number, and the shop is configured to allow VAT exemption
- var customerVatStatus = (VatNumberStatus)customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId);
- return address.CountryId != _taxSettings.EuVatShopCountryId &&
- customerVatStatus == VatNumberStatus.Valid &&
- _taxSettings.EuVatAllowVatExemption;
- }
+ /// <summary>
+ /// Gets a value indicating whether a product is tax exempt
+ /// </summary>
+ /// <param name="product">Product</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>A value indicating whether a product is tax exempt</returns>
+ public virtual async Task<bool> IsTaxExempt(Product product, Customer customer)
+ {
+ if (customer == null) return product is { IsTaxExempt: true };
+ if (customer.IsTaxExempt)
+ return true;
+
+ var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
+ if (customerGroups.Any(cr => cr.TaxExempt))
+ return true;
- #endregion
+ return product is { IsTaxExempt: true };
}
-}
+
+ /// <summary>
+ /// Gets a value indicating whether EU VAT exempt (the European Union Value Added Tax)
+ /// </summary>
+ /// <param name="address">Address</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>Result</returns>
+ public virtual async Task<bool> IsVatExempt(Address address, Customer customer)
+ {
+ if (!_taxSettings.EuVatEnabled)
+ return false;
+
+ if (address == null || string.IsNullOrEmpty(address.CountryId) || customer == null)
+ return false;
+
+ var country = await _countryService.GetCountryById(address.CountryId);
+ if (!country.SubjectToVat)
+ // VAT not chargeable if shipping outside VAT zone
+ return true;
+
+ // VAT not chargeable if address, customer and config meet our VAT exemption requirements:
+ // returns true if this customer is VAT exempt because they are shipping within the EU but outside our shop country, they have supplied a validated VAT number, and the shop is configured to allow VAT exemption
+ var customerVatStatus =
+ (VatNumberStatus)customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId);
+ return address.CountryId != _taxSettings.EuVatShopCountryId &&
+ customerVatStatus == VatNumberStatus.Valid &&
+ _taxSettings.EuVatAllowVatExemption;
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs
index b371f77b7..e8b059dbe 100644
--- a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs
@@ -3,109 +3,110 @@ using Grand.Business.Core.Utilities.Catalog;
using Grand.Domain.Tax;
using System.Text.RegularExpressions;
-namespace Grand.Business.Catalog.Services.Tax
+namespace Grand.Business.Catalog.Services.Tax;
+
+public class VatService : IVatService
{
- public class VatService : IVatService
+ private readonly TaxSettings _taxSettings;
+
+ public VatService(TaxSettings taxSettings)
{
- private readonly TaxSettings _taxSettings;
+ _taxSettings = taxSettings;
+ }
- public VatService(TaxSettings taxSettings)
- {
- _taxSettings = taxSettings;
- }
+ /// <summary>
+ /// Gets VAT Number status
+ /// </summary>
+ /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param>
+ /// <returns>VAT Number status</returns>
+ public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)>
+ GetVatNumberStatus(string fullVatNumber)
+ {
+ var name = string.Empty;
+ var address = string.Empty;
- /// <summary>
- /// Gets VAT Number status
- /// </summary>
- /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param>
- /// <returns>VAT Number status</returns>
- public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus(string fullVatNumber)
- {
- var name = string.Empty;
- var address = string.Empty;
+ if (string.IsNullOrWhiteSpace(fullVatNumber))
+ return (VatNumberStatus.Empty, name, address, null);
- if (string.IsNullOrWhiteSpace(fullVatNumber))
- return (VatNumberStatus.Empty, name, address, null);
+ fullVatNumber = fullVatNumber.Trim();
- fullVatNumber = fullVatNumber.Trim();
+ //PL 111 1111 111 or PL 1111111111
+ //more advanced regex - http://codeigniter.com/wiki/European_Vat_Checker
+ var r = new Regex(@"^(\w{2})(.*)");
+ var match = r.Match(fullVatNumber);
+ if (!match.Success)
+ return (VatNumberStatus.Invalid, name, address, null);
+ var twoLetterIsoCode = match.Groups[1].Value;
+ var vatNumber = match.Groups[2].Value;
- //PL 111 1111 111 or PL 1111111111
- //more advanced regex - http://codeigniter.com/wiki/European_Vat_Checker
- var r = new Regex(@"^(\w{2})(.*)");
- var match = r.Match(fullVatNumber);
- if (!match.Success)
- return (VatNumberStatus.Invalid, name, address, null);
- var twoLetterIsoCode = match.Groups[1].Value;
- var vatNumber = match.Groups[2].Value;
+ return await GetVatNumberStatus(twoLetterIsoCode, vatNumber);
+ }
- return await GetVatNumberStatus(twoLetterIsoCode, vatNumber);
- }
+ /// <summary>
+ /// Gets VAT Number status
+ /// </summary>
+ /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>
+ /// <param name="vatNumber">VAT number</param>
+ /// <returns>VAT Number status</returns>
+ public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)>
+ GetVatNumberStatus(string twoLetterIsoCode, string vatNumber)
+ {
+ var name = string.Empty;
+ var address = string.Empty;
- /// <summary>
- /// Gets VAT Number status
- /// </summary>
- /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>
- /// <param name="vatNumber">VAT number</param>
- /// <returns>VAT Number status</returns>
- public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus(string twoLetterIsoCode, string vatNumber)
- {
- var name = string.Empty;
- var address = string.Empty;
+ if (string.IsNullOrEmpty(twoLetterIsoCode))
+ return (VatNumberStatus.Empty, name, address, null);
- if (string.IsNullOrEmpty(twoLetterIsoCode))
- return (VatNumberStatus.Empty, name, address, null);
+ if (string.IsNullOrEmpty(vatNumber))
+ return (VatNumberStatus.Empty, name, address, null);
- if (string.IsNullOrEmpty(vatNumber))
- return (VatNumberStatus.Empty, name, address, null);
+ if (_taxSettings.EuVatAssumeValid)
+ return (VatNumberStatus.Valid, name, address, null);
- if (_taxSettings.EuVatAssumeValid)
- return (VatNumberStatus.Valid, name, address, null);
+ if (!_taxSettings.EuVatUseWebService)
+ return (VatNumberStatus.Unknown, name, address, null);
- if (!_taxSettings.EuVatUseWebService)
- return (VatNumberStatus.Unknown, name, address, null);
+ return await DoVatCheck(twoLetterIsoCode, vatNumber);
+ }
- return await DoVatCheck(twoLetterIsoCode, vatNumber);
- }
+ /// <summary>
+ /// Performs a basic check of a VAT number for validity
+ /// </summary>
+ /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>
+ /// <param name="vatNumber">VAT number</param>
+ /// <returns>VAT number status</returns>
+ public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)>
+ DoVatCheck(string twoLetterIsoCode, string vatNumber)
+ {
+ vatNumber ??= string.Empty;
+ vatNumber = vatNumber.Trim().Replace(" ", "");
+
+ twoLetterIsoCode ??= string.Empty;
+ if (!string.IsNullOrEmpty(twoLetterIsoCode))
+ //The service returns INVALID_INPUT for country codes that are not uppercase.
+ twoLetterIsoCode = twoLetterIsoCode.ToUpper();
- /// <summary>
- /// Performs a basic check of a VAT number for validity
- /// </summary>
- /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param>
- /// <param name="vatNumber">VAT number</param>
- /// <returns>VAT number status</returns>
- public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)>
- DoVatCheck(string twoLetterIsoCode, string vatNumber)
+ try
{
- vatNumber ??= string.Empty;
- vatNumber = vatNumber.Trim().Replace(" ", "");
-
- twoLetterIsoCode ??= string.Empty;
- if (!string.IsNullOrEmpty(twoLetterIsoCode))
- //The service returns INVALID_INPUT for country codes that are not uppercase.
- twoLetterIsoCode = twoLetterIsoCode.ToUpper();
-
- try
- {
- var result = await CheckVatRequest(new VatRequest {
- CountryCode = twoLetterIsoCode,
- VatNumber = vatNumber
- });
- var valid = result.Valid;
- var name = result.Name;
- var address = result.Address;
-
- return (valid ? VatNumberStatus.Valid : VatNumberStatus.Invalid, name, address, null);
- }
- catch (Exception ex)
- {
- return (VatNumberStatus.Unknown, string.Empty, string.Empty, ex);
- }
+ var result = await CheckVatRequest(new VatRequest {
+ CountryCode = twoLetterIsoCode,
+ VatNumber = vatNumber
+ });
+ var valid = result.Valid;
+ var name = result.Name;
+ var address = result.Address;
+
+ return (valid ? VatNumberStatus.Valid : VatNumberStatus.Invalid, name, address, null);
}
-
- public Task<VatResponse> CheckVatRequest(VatRequest checkVatRequest)
+ catch (Exception ex)
{
- return Task.FromResult(new VatResponse());
+ return (VatNumberStatus.Unknown, string.Empty, string.Empty, ex);
}
}
-}
+
+ public Task<VatResponse> CheckVatRequest(VatRequest checkVatRequest)
+ {
+ return Task.FromResult(new VatResponse());
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
index 60f2105b9..c0cc88f49 100644
--- a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
@@ -1,109 +1,105 @@
-using Grand.Business.Core.Interfaces.Catalog.Categories;
-using Grand.Business.Core.Interfaces.Catalog.Discounts;
-using Grand.Business.Core.Interfaces.Catalog.Collections;
-using Grand.Business.Core.Interfaces.Catalog.Prices;
-using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Catalog.Services.Brands;
using Grand.Business.Catalog.Services.Categories;
-using Grand.Business.Catalog.Services.Discounts;
using Grand.Business.Catalog.Services.Collections;
+using Grand.Business.Catalog.Services.Directory;
+using Grand.Business.Catalog.Services.Discounts;
+using Grand.Business.Catalog.Services.ExportImport;
using Grand.Business.Catalog.Services.Prices;
using Grand.Business.Catalog.Services.Products;
using Grand.Business.Catalog.Services.Tax;
+using Grand.Business.Core.Dto;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
+using Grand.Business.Core.Interfaces.Catalog.Collections;
+using Grand.Business.Core.Interfaces.Catalog.Directory;
+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.Interfaces.ExportImport;
+using Grand.Domain.Catalog;
using Grand.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-using Grand.Business.Catalog.Services.Brands;
-using Grand.Business.Core.Interfaces.Catalog.Brands;
-using Grand.Business.Catalog.Services.Directory;
-using Grand.Business.Core.Interfaces.Catalog.Directory;
-using Grand.Business.Core.Interfaces.ExportImport;
-using Grand.Domain.Catalog;
-using Grand.Business.Catalog.Services.ExportImport;
-using Grand.Business.Core.Dto;
-namespace Grand.Business.Catalog.Startup
+namespace Grand.Business.Catalog.Startup;
+
+public class StartupApplication : IStartupApplication
{
- public class StartupApplication : IStartupApplication
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
+ RegisterCatalogService(services);
+ RegisterDiscountsService(services);
+ RegisterTaxService(services);
+ RegisterExportImport(services);
+ }
- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
- {
- RegisterCatalogService(services);
- RegisterDiscountsService(services);
- RegisterTaxService(services);
- RegisterExportImport(services);
- }
-
- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
- {
-
- }
- public int Priority => 100;
- public bool BeforeConfigure => false;
-
- private void RegisterCatalogService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IOutOfStockSubscriptionService, OutOfStockSubscriptionService>();
- serviceCollection.AddScoped<ICategoryService, CategoryService>();
- serviceCollection.AddScoped<IBrandService, BrandService>();
- serviceCollection.AddScoped<IRecentlyViewedProductsService, RecentlyViewedProductsService>();
- serviceCollection.AddScoped<ICollectionService, CollectionService>();
- serviceCollection.AddScoped<IPriceFormatter, PriceFormatter>();
- serviceCollection.AddScoped<IProductAttributeFormatter, ProductAttributeFormatter>();
- serviceCollection.AddScoped<IProductAttributeService, ProductAttributeService>();
- serviceCollection.AddScoped<IProductService, ProductService>();
- serviceCollection.AddScoped<IProductCategoryService, ProductCategoryService>();
- serviceCollection.AddScoped<IProductCollectionService, ProductCollectionService>();
- serviceCollection.AddScoped<IProductReviewService, ProductReviewService>();
- serviceCollection.AddScoped<ICopyProductService, CopyProductService>();
- serviceCollection.AddScoped<IProductReservationService, ProductReservationService>();
- serviceCollection.AddScoped<IAuctionService, AuctionService>();
- serviceCollection.AddScoped<IProductCourseService, ProductCourseService>();
- serviceCollection.AddScoped<ISpecificationAttributeService, SpecificationAttributeService>();
- serviceCollection.AddScoped<IProductLayoutService, ProductLayoutService>();
- serviceCollection.AddScoped<IBrandLayoutService, BrandLayoutService>();
- serviceCollection.AddScoped<ICategoryLayoutService, CategoryLayoutService>();
- serviceCollection.AddScoped<ICollectionLayoutService, CollectionLayoutService>();
- serviceCollection.AddScoped<IProductTagService, ProductTagService>();
- serviceCollection.AddScoped<ICustomerGroupProductService, CustomerGroupProductService>();
- serviceCollection.AddScoped<IInventoryManageService, InventoryManageService>();
- serviceCollection.AddScoped<IStockQuantityService, StockQuantityService>();
- serviceCollection.AddScoped<IPricingService, PricingService>();
- serviceCollection.AddScoped<ISearchTermService, SearchTermService>();
- serviceCollection.AddScoped<IGeoLookupService, GeoLookupService>();
- serviceCollection.AddScoped<IMeasureService, MeasureService>();
+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
+ {
+ }
- }
+ public int Priority => 100;
+ public bool BeforeConfigure => false;
- private void RegisterDiscountsService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IDiscountService, DiscountService>();
- serviceCollection.AddScoped<IDiscountValidationService, DiscountValidationService>();
- serviceCollection.AddSingleton<IDiscountProviderLoader, DiscountProviderLoader>();
- }
+ private void RegisterCatalogService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IOutOfStockSubscriptionService, OutOfStockSubscriptionService>();
+ serviceCollection.AddScoped<ICategoryService, CategoryService>();
+ serviceCollection.AddScoped<IBrandService, BrandService>();
+ serviceCollection.AddScoped<IRecentlyViewedProductsService, RecentlyViewedProductsService>();
+ serviceCollection.AddScoped<ICollectionService, CollectionService>();
+ serviceCollection.AddScoped<IPriceFormatter, PriceFormatter>();
+ serviceCollection.AddScoped<IProductAttributeFormatter, ProductAttributeFormatter>();
+ serviceCollection.AddScoped<IProductAttributeService, ProductAttributeService>();
+ serviceCollection.AddScoped<IProductService, ProductService>();
+ serviceCollection.AddScoped<IProductCategoryService, ProductCategoryService>();
+ serviceCollection.AddScoped<IProductCollectionService, ProductCollectionService>();
+ serviceCollection.AddScoped<IProductReviewService, ProductReviewService>();
+ serviceCollection.AddScoped<ICopyProductService, CopyProductService>();
+ serviceCollection.AddScoped<IProductReservationService, ProductReservationService>();
+ serviceCollection.AddScoped<IAuctionService, AuctionService>();
+ serviceCollection.AddScoped<IProductCourseService, ProductCourseService>();
+ serviceCollection.AddScoped<ISpecificationAttributeService, SpecificationAttributeService>();
+ serviceCollection.AddScoped<IProductLayoutService, ProductLayoutService>();
+ serviceCollection.AddScoped<IBrandLayoutService, BrandLayoutService>();
+ serviceCollection.AddScoped<ICategoryLayoutService, CategoryLayoutService>();
+ serviceCollection.AddScoped<ICollectionLayoutService, CollectionLayoutService>();
+ serviceCollection.AddScoped<IProductTagService, ProductTagService>();
+ serviceCollection.AddScoped<ICustomerGroupProductService, CustomerGroupProductService>();
+ serviceCollection.AddScoped<IInventoryManageService, InventoryManageService>();
+ serviceCollection.AddScoped<IStockQuantityService, StockQuantityService>();
+ serviceCollection.AddScoped<IPricingService, PricingService>();
+ serviceCollection.AddScoped<ISearchTermService, SearchTermService>();
+ serviceCollection.AddScoped<IGeoLookupService, GeoLookupService>();
+ serviceCollection.AddScoped<IMeasureService, MeasureService>();
+ }
- private void RegisterTaxService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ITaxService, TaxService>();
- serviceCollection.AddScoped<IVatService, VatService>();
- serviceCollection.AddScoped<ITaxCategoryService, TaxCategoryService>();
- }
+ private void RegisterDiscountsService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IDiscountService, DiscountService>();
+ serviceCollection.AddScoped<IDiscountValidationService, DiscountValidationService>();
+ serviceCollection.AddSingleton<IDiscountProviderLoader, DiscountProviderLoader>();
+ }
- private void RegisterExportImport(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ISchemaProperty<Brand>, BrandSchemaProperty>();
- serviceCollection.AddScoped<ISchemaProperty<Category>, CategorySchemaProperty>();
- serviceCollection.AddScoped<ISchemaProperty<Collection>, CollectionSchemaProperty>();
- serviceCollection.AddScoped<ISchemaProperty<Product>, ProductSchemaProperty>();
+ private void RegisterTaxService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<ITaxService, TaxService>();
+ serviceCollection.AddScoped<IVatService, VatService>();
+ serviceCollection.AddScoped<ITaxCategoryService, TaxCategoryService>();
+ }
- serviceCollection.AddScoped<IImportDataObject<CategoryDto>, CategoryImportDataObject>();
- serviceCollection.AddScoped<IImportDataObject<BrandDto>, BrandImportDataObject>();
- serviceCollection.AddScoped<IImportDataObject<CollectionDto>, CollectionImportDataObject>();
- serviceCollection.AddScoped<IImportDataObject<ProductDto>, ProductImportDataObject>();
- }
+ private void RegisterExportImport(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<ISchemaProperty<Brand>, BrandSchemaProperty>();
+ serviceCollection.AddScoped<ISchemaProperty<Category>, CategorySchemaProperty>();
+ serviceCollection.AddScoped<ISchemaProperty<Collection>, CollectionSchemaProperty>();
+ serviceCollection.AddScoped<ISchemaProperty<Product>, ProductSchemaProperty>();
+ serviceCollection.AddScoped<IImportDataObject<CategoryDto>, CategoryImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<BrandDto>, BrandImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<CollectionDto>, CollectionImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<ProductDto>, ProductImportDataObject>();
}
-}
+}
\ No newline at end of file