From 562b6a5076fec82f967410205c983dbba113074c Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Fri, 28 Jun 2024 14:46:39 +0400 Subject: [PATCH 1/2] Refactor your C# code with primary constructors --- .../Domain/ProductAttributeOption.cs | 48 +++--- .../Domain/ProductAttributeOptionsSet.cs | 5 +- .../Domain/ProductVariantAttribute.cs | 38 ++-- .../ProductVariantAttributeCombination.cs | 4 +- .../ProductVariantAttributeSelection.cs | 25 +-- .../Domain/ProductVariantAttributeValue.cs | 39 ++--- .../Attributes/Domain/ProductVariantQuery.cs | 25 +-- .../Domain/SpecificationAttributeOption.cs | 8 +- .../ProductVariantAttributeCombinationHook.cs | 13 +- .../Hooks/ProductVariantAttributeHook.cs | 9 +- .../Hooks/ProductVariantAttributeValueHook.cs | 11 +- .../UnavailableAttributeCombinationsHook.cs | 5 +- .../Modelling/ProductVariantQueryFactory.cs | 21 +-- ...ariantAttributeValueRuleOptionsProvider.cs | 9 +- ...ationAttributeOptionRuleOptionsProvider.cs | 9 +- .../Services/ProductAttributeFormatter.cs | 46 ++--- .../Services/ProductAttributeMaterializer.cs | 41 ++--- .../Services/ProductAttributeService.cs | 12 +- .../Catalog/Brands/Domain/Manufacturer.cs | 10 +- .../Catalog/Brands/Hooks/ManufacturerHook.cs | 9 +- .../Rules/ManufacturerRuleOptionsProvider.cs | 9 +- .../Brands/Services/ManufacturerService.cs | 26 +-- .../Catalog/Categories/Domain/Category.cs | 10 +- .../Catalog/Categories/Domain/CategoryNode.cs | 20 +-- .../Extensions/ITreeNodeQueryExtensions.cs | 1 + .../Catalog/Categories/Hooks/CategoryHook.cs | 12 +- .../Hooks/CategoryTreeChangeHandler.cs | 36 ++-- .../Catalog/Categories/Hooks/ITreeNodeHook.cs | 9 +- .../Categories/Import/CategoryImporter.cs | 21 +-- .../Rules/CategoryRuleOptionsProvider.cs | 12 +- .../Categories/Services/CategoryService.cs | 46 ++--- .../Hooks/DiscountUsageHistoryHook.cs | 9 +- .../Discounts/Services/DiscountService.cs | 38 ++-- .../Pricing/Domain/CalculatorContext.cs | 19 +- .../Catalog/Pricing/Hooks/PriceLabelHook.cs | 12 +- .../Catalog/Pricing/Hooks/TierPriceHook.cs | 9 +- .../Services/CalculatorUsageAttribute.cs | 11 +- .../Calculators/AttributePriceCalculator.cs | 11 +- .../Calculators/BundlePriceCalculator.cs | 12 +- .../Calculators/DiscountPriceCalculator.cs | 18 +- .../GroupedProductPriceCalculator.cs | 16 +- .../Calculators/PreselectedPriceCalculator.cs | 9 +- .../Services/PriceCalculationService.cs | 81 ++++----- .../Pricing/Services/PriceCalculator.cs | 5 +- .../Services/PriceCalculatorFactory.cs | 15 +- .../Pricing/Services/PriceLabelService.cs | 25 +-- .../Domain/GroupedProductConfiguration.cs | 11 +- .../Products/Domain/ProductBundleItem.cs | 50 +++--- .../ProductBundleItemAttributeFilter.cs | 5 +- .../Domain/ProductBundleItemOrderData.cs | 20 +-- .../Domain/ProductReviewHelpfulness.cs | 5 +- .../Products/Events/BarcodeScannedEvent.cs | 12 +- .../Products/Events/ProductClonedEvent.cs | 12 +- .../Products/Hooks/ProductBundleItemHook.cs | 9 +- .../Catalog/Products/Hooks/ProductHook.cs | 21 +-- .../Products/Hooks/ProductMediaFileHook.cs | 9 +- .../Products/Import/ProductImporter.cs | 20 +-- .../Catalog/Products/ProductBatchContext.cs | 106 ++++-------- .../Rules/ProductRuleOptionsProvider.cs | 31 ++-- .../Rules/ProductTagRuleOptionsProvider.cs | 9 +- .../Products/Services/ProductCloner.cs | 41 ++--- .../Services/ProductCompareService.cs | 26 +-- .../Products/Services/ProductService.cs | 61 +++---- .../Products/Services/ProductTagService.cs | 20 +-- .../Products/Services/ProductUrlHelper.cs | 41 ++--- .../Services/RecentlyViewedProductsService.cs | 31 ++-- .../Services/StockSubscriptionService.cs | 37 ++-- .../Catalog/Rules/AttributeRuleContext.cs | 26 +-- .../Catalog/Rules/ProductRuleEvaluatorTask.cs | 21 +-- .../Catalog/Rules/ProductRuleProvider.cs | 44 ++--- .../Catalog/Rules/SearchFilterDescriptor.cs | 5 +- .../Catalog/Search/CatalogSearchQuery.cs | 93 ++++------ .../Search/CatalogSearchQueryContext.cs | 11 +- .../Search/CatalogSearchQueryVisitor.cs | 12 +- .../Catalog/Search/CatalogSearchService.cs | 32 ++-- .../Search/Facets/CatalogFacetUrlHelper.cs | 19 +- .../Search/Hooks/SearchQueryAliasHook.cs | 21 +-- .../Search/LinqCatalogSearchService.cs | 33 ++-- .../CatalogSearchQueryAliasMapper.cs | 51 ++---- .../Modelling/CatalogSearchQueryFactory.cs | 29 ++-- .../Filters/CheckAffiliateAttribute.cs | 12 +- .../Rules/AffiliateRuleOptionsProvider.cs | 9 +- .../Domain/CheckoutAttributeSelection.cs | 22 +-- .../Domain/CheckoutAttributeValue.cs | 10 +- .../Services/CheckoutAttributeFormatter.cs | 41 ++--- .../Services/CheckoutAttributeMaterializer.cs | 9 +- .../CheckoutBootstrappingExtensions.cs | 7 +- .../Checkout/Bootstrapping/CheckoutStarter.cs | 1 + .../Consumers/ValidatingCartEventConsumer.cs | 26 +-- .../Cart/Domain/OrganizedShoppingCartItem.cs | 13 +- .../ShoppingCartItemQueryExtensions.cs | 7 +- .../Cart/Services/ShoppingCartService.cs | 85 ++++----- .../Cart/Services/ShoppingCartValidator.cs | 71 +++----- .../Checkout/GiftCards/Domain/GiftCard.cs | 10 +- .../Domain/GiftCardCouponCodeConverter.cs | 9 +- .../Checkout/GiftCards/Domain/GiftCardInfo.cs | 5 +- .../GiftCards/Services/GiftCardService.cs | 12 +- .../Checkout/Orders/Domain/CheckoutState.cs | 5 +- .../Checkout/Orders/Domain/OrderNote.cs | 10 +- .../Events/CreateAttachmentsConsumer.cs | 12 +- .../Checkout/Orders/Events/OrderEvents.cs | 27 +-- .../OrderEventPublisherExtensions.cs | 22 ++- .../Checkout/Orders/Hooks/OrderItemHook.cs | 12 +- .../Checkout/Orders/Hooks/OrderNoteHook.cs | 12 +- .../Orders/Hooks/ReturnRequestHook.cs | 12 +- .../Orders/Services/CheckoutFactory.cs | 5 +- .../Orders/Services/CheckoutResult.cs | 20 +-- .../Checkout/Orders/Services/CheckoutStep.cs | 1 + .../Orders/Services/CheckoutWorkflow.cs | 71 +++----- .../Services/DefaultCheckoutStateAccessor.cs | 9 +- .../Handlers/BillingAddressHandler.cs | 21 +-- .../Services/Handlers/PaymentMethodHandler.cs | 36 ++-- .../Handlers/ShippingAddressHandler.cs | 21 +-- .../Handlers/ShippingMethodHandler.cs | 21 +-- .../Services/OrderCalculationService.cs | 108 +++++------- .../Orders/Services/OrderProcessingService.cs | 163 +++++++----------- .../Checkout/Orders/Services/OrderService.cs | 36 ++-- .../Orders/Services/PdfInvoiceHttpClient.cs | 15 +- .../Payment/Domain/PaymentException.cs | 10 +- .../Checkout/Payment/Domain/PaymentMethod.cs | 5 +- .../Payment/Domain/PaymentResponse.cs | 15 +- .../Payment/Domain/PaymentValidationResult.cs | 10 +- .../Payment/Domain/RecurringPaymentHistory.cs | 15 +- .../PaymentMessageFactoryExtensions.cs | 1 + .../Payment/Hooks/RecurringPaymentHook.cs | 12 +- .../Rules/PaymentMethodRuleOptionsProvider.cs | 14 +- .../Payment/Service/PaymentService.cs | 1 + .../Checkout/Rules/CartCompositeRule.cs | 12 +- .../Checkout/Rules/CartRuleProvider.cs | 52 +++--- .../Checkout/Rules/Impl/BillingCountryRule.cs | 1 + .../Impl/CartItemFromCategoryQuantityRule.cs | 9 +- .../Checkout/Rules/Impl/CartSubtotalRule.cs | 12 +- .../Checkout/Rules/Impl/CartTotalRule.cs | 13 +- .../Checkout/Rules/Impl/CurrencyRule.cs | 1 + .../Rules/Impl/CustomerAffiliateRule.cs | 9 +- .../Rules/Impl/CustomerAuthenticationRule.cs | 9 +- .../Checkout/Rules/Impl/IPCountryRule.cs | 12 +- .../Checkout/Rules/Impl/LanguageRule.cs | 1 + .../Checkout/Rules/Impl/OrderCountRule.cs | 9 +- .../Checkout/Rules/Impl/PaidByRule.cs | 9 +- .../Impl/ProductFromCategoryInCartRule.cs | 10 +- .../Impl/ProductFromManufacturerInCartRule.cs | 9 +- .../Checkout/Rules/Impl/ProductInCartRule.cs | 1 + .../Rules/Impl/ProductOnWishlistRule.cs | 1 + .../Rules/Impl/ProductReviewCountRule.cs | 9 +- .../Impl/PurchasedFromManufacturerRule.cs | 9 +- .../Rules/Impl/PurchasedProductRule.cs | 10 +- .../Rules/Impl/RewardPointsBalanceRule.cs | 1 + .../Checkout/Rules/Impl/RuleSetRule.cs | 12 +- .../Rules/Impl/ShippingCountryRule.cs | 1 + .../Checkout/Rules/Impl/SpentAmountRule.cs | 21 +-- .../Checkout/Rules/Impl/StoreRule.cs | 1 + .../Impl/UserAgent/BrowserMajorVersionRule.cs | 9 +- .../Impl/UserAgent/BrowserMinorVersionRule.cs | 9 +- .../Rules/Impl/UserAgent/BrowserRule.cs | 16 +- .../Rules/Impl/UserAgent/DeviceRule.cs | 8 +- .../Rules/Impl/UserAgent/IsMobileRule.cs | 10 +- .../Checkout/Rules/Impl/UserAgent/OSRule.cs | 17 +- .../Checkout/Rules/Impl/WeekdayRule.cs | 1 + .../Checkout/Shipping/Domain/Shipment.cs | 10 +- .../Shipping/Domain/ShippingMethod.cs | 6 +- .../Shipping/Domain/ShippingOption.cs | 10 +- .../ShipmentEventPublisherExtensions.cs | 14 +- .../Checkout/Shipping/Hooks/ShipmentHook.cs | 26 +-- .../ShippingMethodRuleOptionsProvider.cs | 9 +- ...ateComputationMethodRuleOptionsProvider.cs | 14 +- .../Shipping/Services/ShippingService.cs | 67 +++---- .../Tracking/CompositeShipmentTracker.cs | 9 +- .../Checkout/Tax/Domain/Tax.cs | 53 +++--- .../Checkout/Tax/Domain/TaxRate.cs | 12 +- .../Checkout/Tax/Domain/VatCheckResult.cs | 18 +- .../Tax/Extensions/ITaxServiceExtensions.cs | 3 + .../Checkout/Tax/Services/TaxCalculator.cs | 31 ++-- .../Tax/Services/ViesTaxationHttpClient.cs | 9 +- src/Smartstore.Core/Common/Domain/Address.cs | 67 +++---- .../Common/Domain/MeasureDimension.cs | 4 +- .../Common/Domain/MeasureWeight.cs | 4 +- src/Smartstore.Core/Common/Domain/Money.cs | 8 +- .../Common/Extensions/CurrencyExtensions.cs | 1 + .../Extensions/DateTimeHelperExtensions.cs | 13 +- .../Common/Hooks/AssignedEntitiesHook.cs | 9 +- .../Common/Hooks/MeasureDimensionHook.cs | 9 +- .../Common/Hooks/QuantityUnitHook.cs | 9 +- .../JsonConverters/UTCDateTimeConverter.cs | 15 +- .../Common/Rules/CommonRuleOptionsProvider.cs | 9 +- .../Common/Services/AddressService.cs | 31 ++-- .../Common/Services/CurrencyService.cs | 41 ++--- .../Common/Services/DateTimeHelper.cs | 26 +-- .../Common/Services/DeliveryTimeService.cs | 26 +-- .../Services/EcbExchangeRateProvider.cs | 9 +- .../Services/GenericAttributeService.cs | 15 +- .../Common/Services/MeasureService.cs | 12 +- .../Common/Services/RoundingHelper.cs | 19 +- .../Common/Tasks/TempFileCleanupTask.cs | 9 +- .../Common/Tasks/UpdateExchangeRateTask.cs | 21 +-- .../Content/Blocks/BlockHandlerBase.cs | 35 ++-- .../Content/Blocks/StoryAssetAttribute.cs | 8 +- 197 files changed, 1332 insertions(+), 2587 deletions(-) diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOption.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOption.cs index 02cc789505..a5a001189e 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOption.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOption.cs @@ -9,14 +9,12 @@ namespace Smartstore.Core.Catalog.Attributes { internal class ProductAttributeOptionMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => // INFO: DeleteBehavior.Cascade required otherwise System.InvalidOperationException when deleting ProductAttributeOptionsSet. builder.HasOne(c => c.ProductAttributeOptionsSet) .WithMany(c => c.ProductAttributeOptions) .HasForeignKey(c => c.ProductAttributeOptionsSetId) .OnDelete(DeleteBehavior.Cascade); - } } /// @@ -108,29 +106,25 @@ public ProductVariantAttributeValueType ValueType public int Quantity { get; set; } /// - public ProductVariantAttributeValue Clone() - { - var value = new ProductVariantAttributeValue - { - Alias = Alias, - Name = Name, - MediaFileId = MediaFileId, - Color = Color, - PriceAdjustment = PriceAdjustment, - WeightAdjustment = WeightAdjustment, - IsPreSelected = IsPreSelected, - DisplayOrder = DisplayOrder, - ValueTypeId = ValueTypeId, - LinkedProductId = LinkedProductId, - Quantity = Quantity - }; - - return value; - } - - object ICloneable.Clone() - { - return Clone(); - } + public ProductVariantAttributeValue Clone() => + new ProductVariantAttributeValue + { + Alias = Alias, + Name = Name, + MediaFileId = MediaFileId, + Color = Color, + PriceAdjustment = PriceAdjustment, + WeightAdjustment = WeightAdjustment, + IsPreSelected = IsPreSelected, + DisplayOrder = DisplayOrder, + ValueTypeId = ValueTypeId, + LinkedProductId = LinkedProductId, + Quantity = Quantity + }; + + + + + object ICloneable.Clone() => Clone(); } } diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOptionsSet.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOptionsSet.cs index 2159150d1a..fa23e1ac22 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOptionsSet.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttributeOptionsSet.cs @@ -6,12 +6,9 @@ namespace Smartstore.Core.Catalog.Attributes { internal class ProductAttributeOptionsSetMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { - builder.HasOne(c => c.ProductAttribute) + public void Configure(EntityTypeBuilder builder) => builder.HasOne(c => c.ProductAttribute) .WithMany(c => c.ProductAttributeOptionsSets) .HasForeignKey(c => c.ProductAttributeId); - } } /// diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttribute.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttribute.cs index 6281fdd4f8..040ff31a4f 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttribute.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttribute.cs @@ -111,17 +111,14 @@ public AttributeControlType AttributeControlType /// /// Gets a value indicating whether the attribute has a list of values. /// - public bool IsListTypeAttribute() + public bool IsListTypeAttribute() => AttributeControlType switch { - return AttributeControlType switch - { - AttributeControlType.TextBox or - AttributeControlType.MultilineTextbox or - AttributeControlType.Datepicker or - AttributeControlType.FileUpload => false, - _ => true, // All other attribute control types support values. - }; - } + AttributeControlType.TextBox or + AttributeControlType.MultilineTextbox or + AttributeControlType.Datepicker or + AttributeControlType.FileUpload => false, + _ => true, // All other attribute control types support values. + }; private ICollection _productVariantAttributeValues; /// @@ -144,19 +141,16 @@ public RuleSetEntity RuleSet set => _ruleSet = value; } - public ProductVariantAttribute Clone() + public ProductVariantAttribute Clone() => new() { - return new() - { - ProductId = ProductId, - ProductAttributeId = ProductAttributeId, - TextPrompt = TextPrompt, - CustomData = CustomData, - IsRequired = IsRequired, - AttributeControlTypeId = AttributeControlTypeId, - DisplayOrder = DisplayOrder, - }; - } + ProductId = ProductId, + ProductAttributeId = ProductAttributeId, + TextPrompt = TextPrompt, + CustomData = CustomData, + IsRequired = IsRequired, + AttributeControlTypeId = AttributeControlTypeId, + DisplayOrder = DisplayOrder, + }; object ICloneable.Clone() => Clone(); diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeCombination.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeCombination.cs index 4499d399cf..42e739410d 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeCombination.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeCombination.cs @@ -233,11 +233,9 @@ where idx > 0 /// /// Sets the assigned media file identifiers. /// - public void SetAssignedMediaIds(int[] ids) - { + public void SetAssignedMediaIds(int[] ids) => AssignedMediaFileIds = ids?.Length > 0 ? string.Join(',', ids) : null; - } } } diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeSelection.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeSelection.cs index 47d94feb53..d4ebc06ec1 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeSelection.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeSelection.cs @@ -9,21 +9,17 @@ namespace Smartstore.Core.Catalog.Attributes /// Represents a product variant attribute selection. /// /// This class can parse strings of XML or JSON format. - public class ProductVariantAttributeSelection : AttributeSelection + /// + /// Creates product variant attribute selection from string. + /// Use to access parsed attributes afterwards. + /// + /// Automatically differentiates between XML and JSON. + /// XML or JSON attributes string. + public class ProductVariantAttributeSelection(string rawAttributes) + : AttributeSelection(rawAttributes, "ProductVariantAttribute") { const string GiftCardAttributeName = "GiftCardInfo"; - /// - /// Creates product variant attribute selection from string. - /// Use to access parsed attributes afterwards. - /// - /// Automatically differentiates between XML and JSON. - /// XML or JSON attributes string. - public ProductVariantAttributeSelection(string rawAttributes) - : base(rawAttributes, "ProductVariantAttribute") - { - } - /// /// Gets the gift card information. /// @@ -40,10 +36,7 @@ public GiftCardInfo GetGiftCardInfo() /// Adds gift card infomation to be taken into account when serializing attributes. /// /// Gift card information. - public void AddGiftCardInfo(GiftCardInfo giftCard) - { - AddCustomAttributeValue(GiftCardAttributeName, giftCard); - } + public void AddGiftCardInfo(GiftCardInfo giftCard) => AddCustomAttributeValue(GiftCardAttributeName, giftCard); protected override object ToCustomAttributeValue(string attributeName, object value) { diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeValue.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeValue.cs index 9b39abf915..9ac3944436 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeValue.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantAttributeValue.cs @@ -9,12 +9,10 @@ namespace Smartstore.Core.Catalog.Attributes { internal class ProductVariantAttributeValueMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(c => c.ProductVariantAttribute) - .WithMany(c => c.ProductVariantAttributeValues) - .HasForeignKey(c => c.ProductVariantAttributeId); - } + .WithMany(c => c.ProductVariantAttributeValues) + .HasForeignKey(c => c.ProductVariantAttributeId); } /// @@ -111,24 +109,21 @@ public ProductVariantAttributeValueType ValueType /// public int Quantity { get; set; } - public ProductVariantAttributeValue Clone() + public ProductVariantAttributeValue Clone() => new() { - return new() - { - ProductVariantAttributeId = ProductVariantAttributeId, - Name = Name, - Alias = Alias, - MediaFileId = MediaFileId, - Color = Color, - PriceAdjustment = PriceAdjustment, - WeightAdjustment = WeightAdjustment, - IsPreSelected = IsPreSelected, - DisplayOrder = DisplayOrder, - ValueTypeId = ValueTypeId, - LinkedProductId = LinkedProductId, - Quantity = Quantity - }; - } + ProductVariantAttributeId = ProductVariantAttributeId, + Name = Name, + Alias = Alias, + MediaFileId = MediaFileId, + Color = Color, + PriceAdjustment = PriceAdjustment, + WeightAdjustment = WeightAdjustment, + IsPreSelected = IsPreSelected, + DisplayOrder = DisplayOrder, + ValueTypeId = ValueTypeId, + LinkedProductId = LinkedProductId, + Quantity = Quantity + }; object ICloneable.Clone() => Clone(); diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantQuery.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantQuery.cs index 284309e1f7..8f52db5759 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantQuery.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/ProductVariantQuery.cs @@ -38,24 +38,17 @@ public void AddVariant(ProductVariantQueryItem item) } } - public void AddGiftCard(GiftCardQueryItem item) - { - _giftCards.Add(item); - } + public void AddGiftCard(GiftCardQueryItem item) => _giftCards.Add(item); - public void AddCheckoutAttribute(CheckoutAttributeQueryItem item) - { - _checkoutAttributes.Add(item); - } + public void AddCheckoutAttribute(CheckoutAttributeQueryItem item) => _checkoutAttributes.Add(item); + + public string GetGiftCardValue(int productId, int bundleItemId, string name) => + _giftCards.FirstOrDefault(x => + x.ProductId == productId && + x.BundleItemId == bundleItemId && + x.Name.EqualsNoCase(name)) + ?.Value; - public string GetGiftCardValue(int productId, int bundleItemId, string name) - { - return _giftCards.FirstOrDefault(x => - x.ProductId == productId && - x.BundleItemId == bundleItemId && - x.Name.EqualsNoCase(name)) - ?.Value; - } public GiftCardInfo GetGiftCardInfo(int productId, int bundleItemId) { diff --git a/src/Smartstore.Core/Catalog/Attributes/Domain/SpecificationAttributeOption.cs b/src/Smartstore.Core/Catalog/Attributes/Domain/SpecificationAttributeOption.cs index 754c9e7e9f..960b9de0a0 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Domain/SpecificationAttributeOption.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Domain/SpecificationAttributeOption.cs @@ -9,12 +9,10 @@ namespace Smartstore.Core.Catalog.Attributes { internal class SpecificationAttributeOptionMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(c => c.SpecificationAttribute) - .WithMany(c => c.SpecificationAttributeOptions) - .HasForeignKey(c => c.SpecificationAttributeId); - } + .WithMany(c => c.SpecificationAttributeOptions) + .HasForeignKey(c => c.SpecificationAttributeId); } /// diff --git a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeCombinationHook.cs b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeCombinationHook.cs index 50bc39c798..7f5cd7278d 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeCombinationHook.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeCombinationHook.cs @@ -5,16 +5,11 @@ namespace Smartstore.Core.Catalog.Attributes { [Important] - internal class ProductVariantAttributeCombinationHook : AsyncDbSaveHook + internal class ProductVariantAttributeCombinationHook(SmartDbContext db, IRequestCache requestCache) + : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IRequestCache _requestCache; - - public ProductVariantAttributeCombinationHook(SmartDbContext db, IRequestCache requestCache) - { - _db = db; - _requestCache = requestCache; - } + private readonly SmartDbContext _db = db; + private readonly IRequestCache _requestCache = requestCache; public override Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeHook.cs b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeHook.cs index ec288b27d0..9c647fbfa7 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeHook.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Attributes { [Important] - internal class ProductVariantAttributeHook : AsyncDbSaveHook + internal class ProductVariantAttributeHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public ProductVariantAttributeHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override Task OnDeletedAsync(ProductVariantAttribute entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeValueHook.cs b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeValueHook.cs index 40137b134a..f8254f205e 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeValueHook.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Hooks/ProductVariantAttributeValueHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Attributes { [Important] - internal class ProductVariantAttributeValueHook : AsyncDbSaveHook + internal class ProductVariantAttributeValueHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public ProductVariantAttributeValueHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; /// /// Sets all product variant attribute values to = false if the currently inserted entity is preselected. @@ -19,6 +14,7 @@ public ProductVariantAttributeValueHook(SmartDbContext db) protected override async Task OnInsertingAsync(ProductVariantAttributeValue entity, IHookedEntity entry, CancellationToken cancelToken) { await ResetPreselectedProductVariantAttributeValues(entity, cancelToken); + return HookResult.Ok; } @@ -28,6 +24,7 @@ protected override async Task OnInsertingAsync(ProductVariantAttribu protected override async Task OnUpdatingAsync(ProductVariantAttributeValue entity, IHookedEntity entry, CancellationToken cancelToken) { await ResetPreselectedProductVariantAttributeValues(entity, cancelToken); + return HookResult.Ok; } diff --git a/src/Smartstore.Core/Catalog/Attributes/Hooks/UnavailableAttributeCombinationsHook.cs b/src/Smartstore.Core/Catalog/Attributes/Hooks/UnavailableAttributeCombinationsHook.cs index 30a85efa3a..12bc5182b7 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Hooks/UnavailableAttributeCombinationsHook.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Hooks/UnavailableAttributeCombinationsHook.cs @@ -13,10 +13,7 @@ internal class UnavailableAttributeCombinationsHook : AsyncDbSaveHook _cache = cache; public override async Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) { diff --git a/src/Smartstore.Core/Catalog/Attributes/Modelling/ProductVariantQueryFactory.cs b/src/Smartstore.Core/Catalog/Attributes/Modelling/ProductVariantQueryFactory.cs index 046d542b8f..cd08260b2a 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Modelling/ProductVariantQueryFactory.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Modelling/ProductVariantQueryFactory.cs @@ -8,28 +8,21 @@ namespace Smartstore.Core.Catalog.Attributes.Modelling { - public partial class ProductVariantQueryFactory : IProductVariantQueryFactory + public partial class ProductVariantQueryFactory( + IHttpContextAccessor httpContextAccessor, + IWorkContext workContext, + ICatalogSearchQueryAliasMapper catalogSearchQueryAliasMapper) : IProductVariantQueryFactory { internal static readonly Regex IsVariantKey = IsVariantKeyRegex(); internal static readonly Regex IsVariantAliasKey = IsVariantAliasKeyRegex(); internal static readonly Regex IsGiftCardKey = IsGiftCardKeyRegex(); internal static readonly Regex IsCheckoutAttributeKey = IsCheckoutAttributeKeyRegex(); - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IWorkContext _workContext; - private readonly ICatalogSearchQueryAliasMapper _catalogSearchQueryAliasMapper; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly IWorkContext _workContext = workContext; + private readonly ICatalogSearchQueryAliasMapper _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; private Multimap _queryItems; - public ProductVariantQueryFactory( - IHttpContextAccessor httpContextAccessor, - IWorkContext workContext, - ICatalogSearchQueryAliasMapper catalogSearchQueryAliasMapper) - { - _httpContextAccessor = httpContextAccessor; - _workContext = workContext; - _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; - } - protected Multimap QueryItems { get diff --git a/src/Smartstore.Core/Catalog/Attributes/Rules/ProductVariantAttributeValueRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Attributes/Rules/ProductVariantAttributeValueRuleOptionsProvider.cs index 7dbcb0b1f3..99979c7bb8 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Rules/ProductVariantAttributeValueRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Rules/ProductVariantAttributeValueRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Catalog.Attributes.Rules { - public partial class ProductVariantAttributeValueRuleOptionsProvider : IRuleOptionsProvider + public partial class ProductVariantAttributeValueRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public ProductVariantAttributeValueRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Attributes/Rules/SpecificationAttributeOptionRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Attributes/Rules/SpecificationAttributeOptionRuleOptionsProvider.cs index 9a665929ad..6e9cc0c680 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Rules/SpecificationAttributeOptionRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Rules/SpecificationAttributeOptionRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Catalog.Attributes.Rules { - public partial class SpecificationAttributeOptionRuleOptionsProvider : IRuleOptionsProvider + public partial class SpecificationAttributeOptionRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public SpecificationAttributeOptionRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeFormatter.cs b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeFormatter.cs index 66c5c8f0a4..e74be9a6eb 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeFormatter.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeFormatter.cs @@ -13,36 +13,24 @@ namespace Smartstore.Core.Catalog.Attributes { - public partial class ProductAttributeFormatter : IProductAttributeFormatter + public partial class ProductAttributeFormatter( + SmartDbContext db, + IWorkContext workContext, + IWebHelper webHelper, + IProductAttributeMaterializer productAttributeMaterializer, + ILocalizationService localizationService, + IPriceCalculationService priceCalculationService, + ShoppingCartSettings shoppingCartSettings, + PriceSettings priceSettings) : IProductAttributeFormatter { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IWebHelper _webHelper; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly ILocalizationService _localizationService; - private readonly IPriceCalculationService _priceCalculationService; - private readonly ShoppingCartSettings _shoppingCartSettings; - private readonly PriceSettings _priceSettings; - - public ProductAttributeFormatter( - SmartDbContext db, - IWorkContext workContext, - IWebHelper webHelper, - IProductAttributeMaterializer productAttributeMaterializer, - ILocalizationService localizationService, - IPriceCalculationService priceCalculationService, - ShoppingCartSettings shoppingCartSettings, - PriceSettings priceSettings) - { - _db = db; - _workContext = workContext; - _webHelper = webHelper; - _productAttributeMaterializer = productAttributeMaterializer; - _localizationService = localizationService; - _priceCalculationService = priceCalculationService; - _shoppingCartSettings = shoppingCartSettings; - _priceSettings = priceSettings; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IWebHelper _webHelper = webHelper; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly ILocalizationService _localizationService = localizationService; + private readonly IPriceCalculationService _priceCalculationService = priceCalculationService; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; + private readonly PriceSettings _priceSettings = priceSettings; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Task FormatAttributesAsync( diff --git a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeMaterializer.cs b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeMaterializer.cs index cb873afc4e..bb3eb9edaf 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeMaterializer.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeMaterializer.cs @@ -9,7 +9,14 @@ namespace Smartstore.Core.Catalog.Attributes { - public partial class ProductAttributeMaterializer : IProductAttributeMaterializer + public partial class ProductAttributeMaterializer( + SmartDbContext db, + IHttpContextAccessor httpContextAccessor, + IRequestCache requestCache, + ICacheManager cache, + Lazy downloadService, + Lazy catalogSettings, + PerformanceSettings performanceSettings) : IProductAttributeMaterializer { // 0 = Attribute IDs const string AttributesByIdsKey = "materialized-attributes:{0}"; @@ -27,31 +34,13 @@ public partial class ProductAttributeMaterializer : IProductAttributeMaterialize internal const string UnavailableCombinationsKey = "attributecombination:unavailable-{0}"; internal const string UanavailableCombinationsPatternKey = "attributecombination:unavailable-*"; - private readonly SmartDbContext _db; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IRequestCache _requestCache; - private readonly ICacheManager _cache; - private readonly Lazy _downloadService; - private readonly Lazy _catalogSettings; - private readonly PerformanceSettings _performanceSettings; - - public ProductAttributeMaterializer( - SmartDbContext db, - IHttpContextAccessor httpContextAccessor, - IRequestCache requestCache, - ICacheManager cache, - Lazy downloadService, - Lazy catalogSettings, - PerformanceSettings performanceSettings) - { - _db = db; - _httpContextAccessor = httpContextAccessor; - _requestCache = requestCache; - _cache = cache; - _downloadService = downloadService; - _catalogSettings = catalogSettings; - _performanceSettings = performanceSettings; - } + private readonly SmartDbContext _db = db; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly IRequestCache _requestCache = requestCache; + private readonly ICacheManager _cache = cache; + private readonly Lazy _downloadService = downloadService; + private readonly Lazy _catalogSettings = catalogSettings; + private readonly PerformanceSettings _performanceSettings = performanceSettings; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeService.cs b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeService.cs index 3f7bdbf739..bd35fec17f 100644 --- a/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeService.cs +++ b/src/Smartstore.Core/Catalog/Attributes/Services/ProductAttributeService.cs @@ -7,16 +7,10 @@ namespace Smartstore.Core.Catalog.Attributes { - public partial class ProductAttributeService : IProductAttributeService + public partial class ProductAttributeService(SmartDbContext db, ILocalizedEntityService localizedEntityService) : IProductAttributeService { - private readonly SmartDbContext _db; - private readonly ILocalizedEntityService _localizedEntityService; - - public ProductAttributeService(SmartDbContext db, ILocalizedEntityService localizedEntityService) - { - _db = db; - _localizedEntityService = localizedEntityService; - } + private readonly SmartDbContext _db = db; + private readonly ILocalizedEntityService _localizedEntityService = localizedEntityService; public virtual async Task> GetExportFieldMappingsAsync(string fieldPrefix) { diff --git a/src/Smartstore.Core/Catalog/Brands/Domain/Manufacturer.cs b/src/Smartstore.Core/Catalog/Brands/Domain/Manufacturer.cs index bc12316f63..85b29889cf 100644 --- a/src/Smartstore.Core/Catalog/Brands/Domain/Manufacturer.cs +++ b/src/Smartstore.Core/Catalog/Brands/Domain/Manufacturer.cs @@ -142,15 +142,9 @@ public MediaFile MediaFile public DateTime UpdatedOnUtc { get; set; } /// - public string GetDisplayName() - { - return Name; - } + public string GetDisplayName() => Name; /// - public string[] GetDisplayNameMemberNames() - { - return new[] { nameof(Name) }; - } + public string[] GetDisplayNameMemberNames() => new[] { nameof(Name) }; } } diff --git a/src/Smartstore.Core/Catalog/Brands/Hooks/ManufacturerHook.cs b/src/Smartstore.Core/Catalog/Brands/Hooks/ManufacturerHook.cs index 8004a2f37d..1f2d30328c 100644 --- a/src/Smartstore.Core/Catalog/Brands/Hooks/ManufacturerHook.cs +++ b/src/Smartstore.Core/Catalog/Brands/Hooks/ManufacturerHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Brands { [Important] - internal class ManufacturerHook : AsyncDbSaveHook + internal class ManufacturerHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public ManufacturerHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override Task OnInsertedAsync(Manufacturer entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Brands/Rules/ManufacturerRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Brands/Rules/ManufacturerRuleOptionsProvider.cs index 6152bbf252..4265d37bf0 100644 --- a/src/Smartstore.Core/Catalog/Brands/Rules/ManufacturerRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Brands/Rules/ManufacturerRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Catalog.Brands.Rules { - public partial class ManufacturerRuleOptionsProvider : IRuleOptionsProvider + public partial class ManufacturerRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public ManufacturerRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Brands/Services/ManufacturerService.cs b/src/Smartstore.Core/Catalog/Brands/Services/ManufacturerService.cs index 24d08b268c..1fc267f46b 100644 --- a/src/Smartstore.Core/Catalog/Brands/Services/ManufacturerService.cs +++ b/src/Smartstore.Core/Catalog/Brands/Services/ManufacturerService.cs @@ -5,21 +5,14 @@ namespace Smartstore.Core.Catalog.Brands { - public partial class ManufacturerService : IManufacturerService, IXmlSitemapPublisher + public partial class ManufacturerService( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext) : IManufacturerService, IXmlSitemapPublisher { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - - public ManufacturerService( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; public virtual async Task> GetProductManufacturersByProductIdsAsync(int[] productIds, bool includeHidden = false) { @@ -73,10 +66,7 @@ class ManufacturerXmlSitemapResult : XmlSitemapProvider { public IQueryable Query { get; set; } - public override async Task GetTotalCountAsync() - { - return await Query.CountAsync(); - } + public override async Task GetTotalCountAsync() => await Query.CountAsync(); public override async IAsyncEnumerable EnlistAsync([EnumeratorCancellation] CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Catalog/Categories/Domain/Category.cs b/src/Smartstore.Core/Catalog/Categories/Domain/Category.cs index 55f27ff20a..93e5eb25e7 100644 --- a/src/Smartstore.Core/Catalog/Categories/Domain/Category.cs +++ b/src/Smartstore.Core/Catalog/Categories/Domain/Category.cs @@ -279,15 +279,9 @@ public ICollection RuleSets } /// - public string GetDisplayName() - { - return Name; - } + public string GetDisplayName() => Name; /// - public string[] GetDisplayNameMemberNames() - { - return new[] { nameof(Name) }; - } + public string[] GetDisplayNameMemberNames() => new[] { nameof(Name) }; } } diff --git a/src/Smartstore.Core/Catalog/Categories/Domain/CategoryNode.cs b/src/Smartstore.Core/Catalog/Categories/Domain/CategoryNode.cs index 6e2a79b9a2..3273eaaaca 100644 --- a/src/Smartstore.Core/Catalog/Categories/Domain/CategoryNode.cs +++ b/src/Smartstore.Core/Catalog/Categories/Domain/CategoryNode.cs @@ -39,27 +39,15 @@ public class CategoryNode : ICategoryNode, IKeyedNode public bool LimitedToStores { get; set; } /// - object IKeyedNode.GetNodeKey() - { - return Id; - } + object IKeyedNode.GetNodeKey() => Id; /// - public string GetDisplayName() - { - return Name; - } + public string GetDisplayName() => Name; /// - public string[] GetDisplayNameMemberNames() - { - return new[] { nameof(Name) }; - } + public string[] GetDisplayNameMemberNames() => new[] { nameof(Name) }; /// - public string GetEntityName() - { - return nameof(Category); - } + public string GetEntityName() => nameof(Category); } } diff --git a/src/Smartstore.Core/Catalog/Categories/Extensions/ITreeNodeQueryExtensions.cs b/src/Smartstore.Core/Catalog/Categories/Extensions/ITreeNodeQueryExtensions.cs index f9f4e9d79d..1211856e8b 100644 --- a/src/Smartstore.Core/Catalog/Categories/Extensions/ITreeNodeQueryExtensions.cs +++ b/src/Smartstore.Core/Catalog/Categories/Extensions/ITreeNodeQueryExtensions.cs @@ -11,6 +11,7 @@ public static IQueryable ApplyDescendantsFilter( ITreeNode node) { Guard.NotNull(node); + return query.ApplyDescendantsFilter(node.TreePath, false); } diff --git a/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryHook.cs b/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryHook.cs index 4acbbd6c89..68b1e75b9d 100644 --- a/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryHook.cs +++ b/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryHook.cs @@ -5,16 +5,10 @@ namespace Smartstore.Core.Catalog.Categories { [Important] - internal class CategoryHook : AsyncDbSaveHook + internal class CategoryHook(SmartDbContext db, IRequestCache requestCache) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IRequestCache _requestCache; - - public CategoryHook(SmartDbContext db, IRequestCache requestCache) - { - _db = db; - _requestCache = requestCache; - } + private readonly SmartDbContext _db = db; + private readonly IRequestCache _requestCache = requestCache; protected override Task OnInsertedAsync(Category entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryTreeChangeHandler.cs b/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryTreeChangeHandler.cs index bf212371e4..b5630cdb6e 100644 --- a/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryTreeChangeHandler.cs +++ b/src/Smartstore.Core/Catalog/Categories/Hooks/CategoryTreeChangeHandler.cs @@ -22,17 +22,15 @@ public enum CategoryTreeChangeReason Hierarchy } - public class CategoryTreeChangedEvent + public class CategoryTreeChangedEvent(CategoryTreeChangeReason reason) { - public CategoryTreeChangedEvent(CategoryTreeChangeReason reason) - { - Reason = reason; - } - - public CategoryTreeChangeReason Reason { get; private set; } + public CategoryTreeChangeReason Reason { get; private set; } = reason; } - internal class CategoryTreeChangeHook : AsyncDbSaveHook, IConsumer + internal class CategoryTreeChangeHook( + SmartDbContext db, + ICacheManager cache, + IEventPublisher eventPublisher) : AsyncDbSaveHook, IConsumer { #region static @@ -65,23 +63,13 @@ internal class CategoryTreeChangeHook : AsyncDbSaveHook, IConsumer #endregion - private readonly SmartDbContext _db; - private readonly ICacheManager _cache; - private readonly IEventPublisher _eventPublisher; + private readonly SmartDbContext _db = db; + private readonly ICacheManager _cache = cache; + private readonly IEventPublisher _eventPublisher = eventPublisher; private readonly bool[] _handledReasons = new bool[(int)CategoryTreeChangeReason.Hierarchy + 1]; private bool _invalidated; - public CategoryTreeChangeHook( - SmartDbContext db, - ICacheManager cache, - IEventPublisher eventPublisher) - { - _db = db; - _cache = cache; - _eventPublisher = eventPublisher; - } - public override async Task OnBeforeSaveAsync(IHookedEntity entry, CancellationToken cancelToken) { if (_invalidated) @@ -301,9 +289,7 @@ private async Task PublishEvent(CategoryTreeChangeReason reason) } } - private static string BuildCacheKeyPattern(string includeHiddenToken = "*", string rolesToken = "*", string storeToken = "*") - { - return CategoryService.CategoryTreeKey.FormatInvariant(includeHiddenToken, rolesToken, storeToken); - } + private static string BuildCacheKeyPattern(string includeHiddenToken = "*", string rolesToken = "*", string storeToken = "*") + => CategoryService.CategoryTreeKey.FormatInvariant(includeHiddenToken, rolesToken, storeToken); } } diff --git a/src/Smartstore.Core/Catalog/Categories/Hooks/ITreeNodeHook.cs b/src/Smartstore.Core/Catalog/Categories/Hooks/ITreeNodeHook.cs index 6a6113cad5..245da8fa9c 100644 --- a/src/Smartstore.Core/Catalog/Categories/Hooks/ITreeNodeHook.cs +++ b/src/Smartstore.Core/Catalog/Categories/Hooks/ITreeNodeHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Categories { [Important(HookImportance.Essential)] - internal class TreeNodeHook : AsyncDbSaveHook + internal class TreeNodeHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public TreeNodeHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override async Task OnUpdatingAsync(ITreeNode entity, IHookedEntity entry, CancellationToken cancelToken) { diff --git a/src/Smartstore.Core/Catalog/Categories/Import/CategoryImporter.cs b/src/Smartstore.Core/Catalog/Categories/Import/CategoryImporter.cs index c6587db7de..ff9e2abb37 100644 --- a/src/Smartstore.Core/Catalog/Categories/Import/CategoryImporter.cs +++ b/src/Smartstore.Core/Catalog/Categories/Import/CategoryImporter.cs @@ -9,7 +9,12 @@ namespace Smartstore.Core.DataExchange.Import { - public class CategoryImporter : EntityImporterBase + public class CategoryImporter( + ICommonServices services, + IStoreMappingService storeMappingService, + IUrlService urlService, + IMediaImporter mediaImporter, + SeoSettings seoSettings) : EntityImporterBase(services, storeMappingService, urlService, seoSettings) { const string CargoDataKey = "CategoryImporter.CargoData"; const string TargetCategoryIdsKey = "CategoryImporter.TargetCategoryIds"; @@ -26,18 +31,7 @@ public class CategoryImporter : EntityImporterBase { nameof(Category.MetaTitle), x => x.MetaTitle } }.ToFrozenDictionary(); - private readonly IMediaImporter _mediaImporter; - - public CategoryImporter( - ICommonServices services, - IStoreMappingService storeMappingService, - IUrlService urlService, - IMediaImporter mediaImporter, - SeoSettings seoSettings) - : base(services, storeMappingService, urlService, seoSettings) - { - _mediaImporter = mediaImporter; - } + private readonly IMediaImporter _mediaImporter = mediaImporter; public static string[] SupportedKeyFields => new[] { nameof(Category.Id), nameof(Category.Name) }; public static string[] DefaultKeyFields => new[] { nameof(Category.Name), nameof(Category.Id) }; @@ -384,6 +378,7 @@ private async Task GetCargoData(ImportExecuteContext context) }; context.CustomProperties[CargoDataKey] = result; + return result; } diff --git a/src/Smartstore.Core/Catalog/Categories/Rules/CategoryRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Categories/Rules/CategoryRuleOptionsProvider.cs index a0052cedab..fbeeb3c487 100644 --- a/src/Smartstore.Core/Catalog/Categories/Rules/CategoryRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Categories/Rules/CategoryRuleOptionsProvider.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Catalog.Categories.Rules { - public partial class CategoryRuleOptionsProvider : IRuleOptionsProvider + public partial class CategoryRuleOptionsProvider(SmartDbContext db, ICategoryService categoryService) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - private readonly ICategoryService _categoryService; - - public CategoryRuleOptionsProvider(SmartDbContext db, ICategoryService categoryService) - { - _db = db; - _categoryService = categoryService; - } + private readonly SmartDbContext _db = db; + private readonly ICategoryService _categoryService = categoryService; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Categories/Services/CategoryService.cs b/src/Smartstore.Core/Catalog/Categories/Services/CategoryService.cs index 665e66c3f6..7670d75684 100644 --- a/src/Smartstore.Core/Catalog/Categories/Services/CategoryService.cs +++ b/src/Smartstore.Core/Catalog/Categories/Services/CategoryService.cs @@ -14,7 +14,15 @@ namespace Smartstore.Core.Catalog.Categories { - public partial class CategoryService : ICategoryService, IXmlSitemapPublisher + public partial class CategoryService( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext, + ICacheManager cache, + IRequestCache requestCache, + IStoreMappingService storeMappingService, + IAclService aclService, + ICatalogSearchService catalogSearchService) : ICategoryService, IXmlSitemapPublisher { internal static TimeSpan CategoryTreeCacheDuration = TimeSpan.FromHours(6); @@ -26,34 +34,14 @@ public partial class CategoryService : ICategoryService, IXmlSitemapPublisher internal readonly static CompositeFormat CategoriesByParentIdKey = CompositeFormat.Parse("category:byparent-{0}-{1}-{2}-{3}"); internal const string CategoriesPatternKey = "category:*"; - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly ICacheManager _cache; - private readonly IRequestCache _requestCache; - private readonly IStoreMappingService _storeMappingService; - private readonly IAclService _aclService; - private readonly ICatalogSearchService _catalogSearchService; - - public CategoryService( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext, - ICacheManager cache, - IRequestCache requestCache, - IStoreMappingService storeMappingService, - IAclService aclService, - ICatalogSearchService catalogSearchService) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - _cache = cache; - _requestCache = requestCache; - _storeMappingService = storeMappingService; - _aclService = aclService; - _catalogSearchService = catalogSearchService; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly ICacheManager _cache = cache; + private readonly IRequestCache _requestCache = requestCache; + private readonly IStoreMappingService _storeMappingService = storeMappingService; + private readonly IAclService _aclService = aclService; + private readonly ICatalogSearchService _catalogSearchService = catalogSearchService; public virtual async Task DeleteCategoryAsync(Category category, bool deleteSubCategories = false) { diff --git a/src/Smartstore.Core/Catalog/Discounts/Hooks/DiscountUsageHistoryHook.cs b/src/Smartstore.Core/Catalog/Discounts/Hooks/DiscountUsageHistoryHook.cs index 94f9b64725..8ccc30886c 100644 --- a/src/Smartstore.Core/Catalog/Discounts/Hooks/DiscountUsageHistoryHook.cs +++ b/src/Smartstore.Core/Catalog/Discounts/Hooks/DiscountUsageHistoryHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Discounts { - internal class DiscountUsageHistoryHook : AsyncDbSaveHook + internal class DiscountUsageHistoryHook(IRequestCache requestCache) : AsyncDbSaveHook { - private readonly IRequestCache _requestCache; - - public DiscountUsageHistoryHook(IRequestCache requestCache) - { - _requestCache = requestCache; - } + private readonly IRequestCache _requestCache = requestCache; public override Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Discounts/Services/DiscountService.cs b/src/Smartstore.Core/Catalog/Discounts/Services/DiscountService.cs index d59493d83d..9810f21130 100644 --- a/src/Smartstore.Core/Catalog/Discounts/Services/DiscountService.cs +++ b/src/Smartstore.Core/Catalog/Discounts/Services/DiscountService.cs @@ -12,34 +12,25 @@ namespace Smartstore.Core.Catalog.Discounts { - public partial class DiscountService : AsyncDbSaveHook, IDiscountService + public partial class DiscountService( + SmartDbContext db, + IRequestCache requestCache, + IStoreContext storeContext, + IRuleProviderFactory ruleProviderFactory, + Lazy cartService) : AsyncDbSaveHook, IDiscountService { // {0} = discountType, {1} = includeHidden, {2} = couponCode. private readonly static CompositeFormat DiscountsAllKey = CompositeFormat.Parse("discount.all-{0}-{1}-{2}"); internal const string DiscountsPatternKey = "discount.*"; - private readonly SmartDbContext _db; - private readonly IRequestCache _requestCache; - private readonly IStoreContext _storeContext; - private readonly ICartRuleProvider _cartRuleProvider; - private readonly Lazy _cartService ; + private readonly SmartDbContext _db = db; + private readonly IRequestCache _requestCache = requestCache; + private readonly IStoreContext _storeContext = storeContext; + private readonly ICartRuleProvider _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); + private readonly Lazy _cartService = cartService; private readonly Dictionary _discountValidityCache = []; private readonly Multimap _relatedEntityIds = new(items => new HashSet(items)); - public DiscountService( - SmartDbContext db, - IRequestCache requestCache, - IStoreContext storeContext, - IRuleProviderFactory ruleProviderFactory, - Lazy cartService) - { - _db = db; - _requestCache = requestCache; - _storeContext = storeContext; - _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); - _cartService = cartService; - } - #region Hook protected override Task OnInsertedAsync(Discount entity, IHookedEntity entry, CancellationToken cancelToken) @@ -350,12 +341,9 @@ protected virtual async Task CheckDiscountLimitationsAsync(Discount discou } } - class DiscountKey : Tuple + class DiscountKey(Discount discount, Customer customer, string customerCouponCode, Store store, DiscountValidationFlags flags) + : Tuple(discount, customer, customerCouponCode, store, flags) { - public DiscountKey(Discount discount, Customer customer, string customerCouponCode, Store store, DiscountValidationFlags flags) - : base(discount, customer, customerCouponCode, store, flags) - { - } } } } diff --git a/src/Smartstore.Core/Catalog/Pricing/Domain/CalculatorContext.cs b/src/Smartstore.Core/Catalog/Pricing/Domain/CalculatorContext.cs index 1ac07b51a6..b277ef770a 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Domain/CalculatorContext.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Domain/CalculatorContext.cs @@ -9,15 +9,12 @@ namespace Smartstore.Core.Catalog.Pricing /// All monetary amounts are in the primary store currency, without any tax calculation applied. /// The calculated price is always the unit price of the product. /// - public class CalculatorContext : PriceCalculationContext + public class CalculatorContext( + PriceCalculationContext context, + decimal finalPrice, + PricingType pricingType = PricingType.Calculated) + : PriceCalculationContext(context) { - public CalculatorContext(PriceCalculationContext context, decimal finalPrice, PricingType pricingType = PricingType.Calculated) - : base(context) - { - PricingType = pricingType; - FinalPrice = finalPrice; - RegularPrice = context.Product.Price; - } /// /// List of discount entities that have been applied during calculation. @@ -41,18 +38,18 @@ public CalculatorContext(PriceCalculationContext context, decimal finalPrice, Pr /// public TierPrice AppliedTierPrice { get; set; } - public PricingType PricingType { get; set; } + public PricingType PricingType { get; set; } = pricingType; /// /// The final price of the product. A calculator should set this property if any adjustment has been made to the price. /// - public decimal FinalPrice { get; set; } + public decimal FinalPrice { get; set; } = finalPrice; /// /// Pipeline emitted candidate for the regular price (unit price). /// The actual regular price is determined later in . /// - public decimal RegularPrice { get; set; } + public decimal RegularPrice { get; set; } = context.Product.Price; /// /// A value indicating whether the price has a range, which is mostly the case if the lowest price diff --git a/src/Smartstore.Core/Catalog/Pricing/Hooks/PriceLabelHook.cs b/src/Smartstore.Core/Catalog/Pricing/Hooks/PriceLabelHook.cs index af90c88528..38a8d0a96b 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Hooks/PriceLabelHook.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Hooks/PriceLabelHook.cs @@ -4,18 +4,12 @@ namespace Smartstore.Core.Catalog.Pricing { - internal class PriceLabelHook : AsyncDbSaveHook + internal class PriceLabelHook(SmartDbContext db, PriceSettings priceSettings) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly PriceSettings _priceSettings; + private readonly SmartDbContext _db = db; + private readonly PriceSettings _priceSettings = priceSettings; private string _hookErrorMessage; - public PriceLabelHook(SmartDbContext db, PriceSettings priceSettings) - { - _db = db; - _priceSettings = priceSettings; - } - public Localizer T { get; set; } = NullLocalizer.Instance; protected override Task OnDeletingAsync(PriceLabel entity, IHookedEntity entry, CancellationToken cancelToken) diff --git a/src/Smartstore.Core/Catalog/Pricing/Hooks/TierPriceHook.cs b/src/Smartstore.Core/Catalog/Pricing/Hooks/TierPriceHook.cs index 41c780edce..50e3a17395 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Hooks/TierPriceHook.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Hooks/TierPriceHook.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Catalog.Pricing { [Important] - internal class TierPriceHook : AsyncDbSaveHook + internal class TierPriceHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public TierPriceHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override Task OnInsertedAsync(TierPrice entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/CalculatorUsageAttribute.cs b/src/Smartstore.Core/Catalog/Pricing/Services/CalculatorUsageAttribute.cs index 779f232473..db3804cf6b 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/CalculatorUsageAttribute.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/CalculatorUsageAttribute.cs @@ -32,23 +32,18 @@ public enum CalculatorTargets /// can be annoated with this attribue. /// [AttributeUsage(AttributeTargets.Class, Inherited = true)] - public sealed class CalculatorUsageAttribute : Attribute + public sealed class CalculatorUsageAttribute(CalculatorTargets validTargets, int order) : Attribute { - public CalculatorUsageAttribute(CalculatorTargets validTargets, int order) - { - ValidTargets = validTargets; - Order = order; - } /// /// The valid targets for the annotated calculator. The calculator will be excluded from the pipeline /// if the product for which a price is calculated does not match. /// - public CalculatorTargets ValidTargets { get; } + public CalculatorTargets ValidTargets { get; } = validTargets; /// /// The order of the calculator within the pipeline. See . /// - public int Order { get; } + public int Order { get; } = order; } } diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/AttributePriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/AttributePriceCalculator.cs index 2be56d6f70..aaef44545e 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/AttributePriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/AttributePriceCalculator.cs @@ -10,15 +10,10 @@ namespace Smartstore.Core.Catalog.Pricing.Calculators /// Also applies attributes preselected by merchant if is true. /// [CalculatorUsage(CalculatorTargets.Product, CalculatorOrdering.Default + 10)] - public class AttributePriceCalculator : PriceCalculator + public class AttributePriceCalculator(IPriceCalculatorFactory calculatorFactory, SmartDbContext db) + : PriceCalculator(calculatorFactory) { - private readonly SmartDbContext _db; - - public AttributePriceCalculator(IPriceCalculatorFactory calculatorFactory, SmartDbContext db) - : base(calculatorFactory) - { - _db = db; - } + private readonly SmartDbContext _db = db; public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/BundlePriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/BundlePriceCalculator.cs index f6b9168b8d..5d70e10e27 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/BundlePriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/BundlePriceCalculator.cs @@ -7,15 +7,11 @@ namespace Smartstore.Core.Catalog.Pricing.Calculators /// then the price for each bundle item is calculated and multiplied by . /// [CalculatorUsage(CalculatorTargets.Bundle, CalculatorOrdering.Early)] - public class BundlePriceCalculator : PriceCalculator + public class BundlePriceCalculator( + IPriceCalculatorFactory calculatorFactory, + IProductService productService) : PriceCalculator(calculatorFactory) { - private readonly IProductService _productService; - - public BundlePriceCalculator(IPriceCalculatorFactory calculatorFactory, IProductService productService) - : base(calculatorFactory) - { - _productService = productService; - } + private readonly IProductService _productService = productService; public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/DiscountPriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/DiscountPriceCalculator.cs index cc63e9cb3e..50f9f7a98b 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/DiscountPriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/DiscountPriceCalculator.cs @@ -10,18 +10,14 @@ namespace Smartstore.Core.Catalog.Pricing.Calculators /// Also applies the discount amount on the minimum tier price if is activated. /// [CalculatorUsage(CalculatorTargets.All, CalculatorOrdering.Late)] - public class DiscountPriceCalculator : IPriceCalculator + public class DiscountPriceCalculator( + SmartDbContext db, + IDiscountService discountService, + PriceSettings priceSettings) : IPriceCalculator { - private readonly SmartDbContext _db; - private readonly IDiscountService _discountService; - private readonly PriceSettings _priceSettings; - - public DiscountPriceCalculator(SmartDbContext db, IDiscountService discountService, PriceSettings priceSettings) - { - _db = db; - _discountService = discountService; - _priceSettings = priceSettings; - } + private readonly SmartDbContext _db = db; + private readonly IDiscountService _discountService = discountService; + private readonly PriceSettings _priceSettings = priceSettings; public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/GroupedProductPriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/GroupedProductPriceCalculator.cs index 91667f46a9..1961a235bf 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/GroupedProductPriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/GroupedProductPriceCalculator.cs @@ -8,17 +8,13 @@ namespace Smartstore.Core.Catalog.Pricing.Calculators /// the lowest price of all associated products. /// [CalculatorUsage(CalculatorTargets.GroupedProduct, CalculatorOrdering.Early)] - public class GroupedProductPriceCalculator : PriceCalculator + public class GroupedProductPriceCalculator( + ICatalogSearchService catalogSearchService, + IPriceCalculatorFactory calculatorFactory, + IProductService productService) : PriceCalculator(calculatorFactory) { - private readonly ICatalogSearchService _catalogSearchService; - private readonly IProductService _productService; - - public GroupedProductPriceCalculator(ICatalogSearchService catalogSearchService, IPriceCalculatorFactory calculatorFactory, IProductService productService) - : base(calculatorFactory) - { - _catalogSearchService = catalogSearchService; - _productService = productService; - } + private readonly ICatalogSearchService _catalogSearchService = catalogSearchService; + private readonly IProductService _productService = productService; public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/PreselectedPriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/PreselectedPriceCalculator.cs index 45d76021ba..53b9689dbd 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/PreselectedPriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/Calculators/PreselectedPriceCalculator.cs @@ -8,14 +8,9 @@ namespace Smartstore.Core.Catalog.Pricing.Calculators /// That's why this calculator must run very early. /// [CalculatorUsage(CalculatorTargets.Product, CalculatorOrdering.Early + 1)] - public class PreselectedPriceCalculator : IPriceCalculator + public class PreselectedPriceCalculator(IProductAttributeMaterializer productAttributeMaterializer) : IPriceCalculator { - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - - public PreselectedPriceCalculator(IProductAttributeMaterializer productAttributeMaterializer) - { - _productAttributeMaterializer = productAttributeMaterializer; - } + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculationService.cs b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculationService.cs index 5313f5ca91..0a8dcf83f5 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculationService.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculationService.cs @@ -13,57 +13,37 @@ namespace Smartstore.Core.Catalog.Pricing { - public partial class PriceCalculationService : IPriceCalculationService + public partial class PriceCalculationService( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext, + IPriceCalculatorFactory calculatorFactory, + ITaxCalculator taxCalculator, + IProductService productService, + IProductAttributeMaterializer productAttributeMaterializer, + ITaxService taxService, + ICurrencyService currencyService, + IRoundingHelper roundingHelper, + IPriceLabelService priceLabelService, + PriceSettings priceSettings, + CurrencySettings currencySettings, + TaxSettings taxSettings) : IPriceCalculationService { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly IPriceCalculatorFactory _calculatorFactory; - private readonly ITaxCalculator _taxCalculator; - private readonly IProductService _productService; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly ITaxService _taxService; - private readonly ICurrencyService _currencyService; - private readonly IRoundingHelper _roundingHelper; - private readonly IPriceLabelService _priceLabelService; - private readonly PriceSettings _priceSettings; - private readonly CurrencySettings _currencySettings; - private readonly TaxSettings _taxSettings; - private readonly Currency _primaryCurrency; - - public PriceCalculationService( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext, - IPriceCalculatorFactory calculatorFactory, - ITaxCalculator taxCalculator, - IProductService productService, - IProductAttributeMaterializer productAttributeMaterializer, - ITaxService taxService, - ICurrencyService currencyService, - IRoundingHelper roundingHelper, - IPriceLabelService priceLabelService, - PriceSettings priceSettings, - CurrencySettings currencySettings, - TaxSettings taxSettings) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - _calculatorFactory = calculatorFactory; - _taxCalculator = taxCalculator; - _productService = productService; - _productAttributeMaterializer = productAttributeMaterializer; - _taxService = taxService; - _currencyService = currencyService; - _roundingHelper = roundingHelper; - _priceLabelService = priceLabelService; - _priceSettings = priceSettings; - _currencySettings = currencySettings; - _taxSettings = taxSettings; - - _primaryCurrency = currencyService.PrimaryCurrency; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly IPriceCalculatorFactory _calculatorFactory = calculatorFactory; + private readonly ITaxCalculator _taxCalculator = taxCalculator; + private readonly IProductService _productService = productService; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly ITaxService _taxService = taxService; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IPriceLabelService _priceLabelService = priceLabelService; + private readonly PriceSettings _priceSettings = priceSettings; + private readonly CurrencySettings _currencySettings = currencySettings; + private readonly TaxSettings _taxSettings = taxSettings; + private readonly Currency _primaryCurrency = currencyService.PrimaryCurrency; public Localizer T { get; set; } = NullLocalizer.Instance; @@ -174,6 +154,7 @@ public virtual async Task CalculatePriceAsync(PriceCalculationC } var subtotal = await CreateCalculatedPrice(calculatorContext, product, context.Quantity); + return (price, subtotal); } diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculator.cs b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculator.cs index 87b918f726..0e1a83c12a 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculator.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculator.cs @@ -13,10 +13,7 @@ public abstract class PriceCalculator : IPriceCalculator { private readonly IPriceCalculatorFactory _calculatorFactory; - protected PriceCalculator(IPriceCalculatorFactory calculatorFactory) - { - _calculatorFactory = calculatorFactory; - } + protected PriceCalculator(IPriceCalculatorFactory calculatorFactory) => _calculatorFactory = calculatorFactory; public virtual async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculatorFactory.cs b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculatorFactory.cs index 6a300ec98f..4a92caf2fd 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculatorFactory.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/PriceCalculatorFactory.cs @@ -3,16 +3,13 @@ namespace Smartstore.Core.Catalog.Pricing { - public partial class PriceCalculatorFactory : IPriceCalculatorFactory + public partial class PriceCalculatorFactory( + IRequestCache requestCache, + IEnumerable> calculators) : IPriceCalculatorFactory { - private readonly IRequestCache _requestCache; - private readonly IEnumerable> _lazyCalculators; - - public PriceCalculatorFactory(IRequestCache requestCache, IEnumerable> calculators) - { - _requestCache = requestCache; - _lazyCalculators = calculators.OrderBy(x => x.Metadata.Order); - } + private readonly IRequestCache _requestCache = requestCache; + private readonly IEnumerable> _lazyCalculators = calculators.OrderBy(x => x.Metadata.Order); public IPriceCalculator[] GetCalculators(PriceCalculationContext context) { diff --git a/src/Smartstore.Core/Catalog/Pricing/Services/PriceLabelService.cs b/src/Smartstore.Core/Catalog/Pricing/Services/PriceLabelService.cs index 6cd79e4889..b2e2c82914 100644 --- a/src/Smartstore.Core/Catalog/Pricing/Services/PriceLabelService.cs +++ b/src/Smartstore.Core/Catalog/Pricing/Services/PriceLabelService.cs @@ -6,32 +6,21 @@ namespace Smartstore.Core.Catalog.Pricing { - public class PriceLabelService : IPriceLabelService + public class PriceLabelService(SmartDbContext db, PriceSettings priceSettings) : IPriceLabelService { - private readonly SmartDbContext _db; - private readonly PriceSettings _priceSettings; + private readonly SmartDbContext _db = db; + private readonly PriceSettings _priceSettings = priceSettings; private Dictionary _allPriceLabels; private PriceLabel _defaultComparePriceLabel; private PriceLabel _defaultRegularPriceLabel; - public PriceLabelService(SmartDbContext db, PriceSettings priceSettings) - { - _db = db; - _priceSettings = priceSettings; - } - public Localizer T { get; set; } = NullLocalizer.Instance; - - public virtual PriceLabel GetDefaultComparePriceLabel() - { - return _defaultComparePriceLabel ??= GetPriceLabel(_priceSettings.DefaultComparePriceLabelId, true); - } - public virtual PriceLabel GetDefaultRegularPriceLabel() - { - return _defaultRegularPriceLabel ??= GetPriceLabel(_priceSettings.DefaultRegularPriceLabelId, false); - } + public virtual PriceLabel GetDefaultComparePriceLabel() => _defaultComparePriceLabel ??= GetPriceLabel(_priceSettings.DefaultComparePriceLabelId, true); + + public virtual PriceLabel GetDefaultRegularPriceLabel() => + _defaultRegularPriceLabel ??= GetPriceLabel(_priceSettings.DefaultRegularPriceLabelId, false); private PriceLabel GetPriceLabel(int? id, bool forComparePrice) { diff --git a/src/Smartstore.Core/Catalog/Products/Domain/GroupedProductConfiguration.cs b/src/Smartstore.Core/Catalog/Products/Domain/GroupedProductConfiguration.cs index b376939c5c..872286ac6b 100644 --- a/src/Smartstore.Core/Catalog/Products/Domain/GroupedProductConfiguration.cs +++ b/src/Smartstore.Core/Catalog/Products/Domain/GroupedProductConfiguration.cs @@ -75,14 +75,9 @@ public GroupedProductConfigurationConverter() { } - private static string Serialize(GroupedProductConfiguration obj) - { - return obj.ToJson(); - } + private static string Serialize(GroupedProductConfiguration obj) => obj.ToJson(); - private static GroupedProductConfiguration Deserialize(string json) - { - return CommonHelper.TryAction(() => JsonConvert.DeserializeObject(json)); - } + private static GroupedProductConfiguration Deserialize(string json) => + CommonHelper.TryAction(() => JsonConvert.DeserializeObject(json)); } } diff --git a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItem.cs b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItem.cs index 1d077ac8f8..36c562ca30 100644 --- a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItem.cs +++ b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItem.cs @@ -134,32 +134,28 @@ public ICollection AttributeFilters } /// - public ProductBundleItem Clone() - { - var bundleItem = new ProductBundleItem - { - ProductId = ProductId, - BundleProductId = BundleProductId, - Quantity = Quantity, - Discount = Discount, - DiscountPercentage = DiscountPercentage, - Name = Name, - ShortDescription = ShortDescription, - FilterAttributes = FilterAttributes, - HideThumbnail = HideThumbnail, - Visible = Visible, - Published = Published, - DisplayOrder = DisplayOrder, - CreatedOnUtc = CreatedOnUtc, - UpdatedOnUtc = UpdatedOnUtc - }; - - return bundleItem; - } - - object ICloneable.Clone() - { - return Clone(); - } + public ProductBundleItem Clone() => + new ProductBundleItem + { + ProductId = ProductId, + BundleProductId = BundleProductId, + Quantity = Quantity, + Discount = Discount, + DiscountPercentage = DiscountPercentage, + Name = Name, + ShortDescription = ShortDescription, + FilterAttributes = FilterAttributes, + HideThumbnail = HideThumbnail, + Visible = Visible, + Published = Published, + DisplayOrder = DisplayOrder, + CreatedOnUtc = CreatedOnUtc, + UpdatedOnUtc = UpdatedOnUtc + }; + + + + + object ICloneable.Clone() => Clone(); } } diff --git a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemAttributeFilter.cs b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemAttributeFilter.cs index e10a5e4c05..7e986e9715 100644 --- a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemAttributeFilter.cs +++ b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemAttributeFilter.cs @@ -51,9 +51,6 @@ public ProductBundleItemAttributeFilter Clone() return filter; } - object ICloneable.Clone() - { - return Clone(); - } + object ICloneable.Clone() => Clone(); } } diff --git a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemOrderData.cs b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemOrderData.cs index b927bb424b..0477fb3589 100644 --- a/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemOrderData.cs +++ b/src/Smartstore.Core/Catalog/Products/Domain/ProductBundleItemOrderData.cs @@ -63,25 +63,13 @@ public ITypeConverter GetConverter(Type type) } } - public class ProductBundleItemOrderDataConverter : DefaultTypeConverter + public class ProductBundleItemOrderDataConverter(bool forList) : DefaultTypeConverter(typeof(object)) { - private readonly bool _forList; + private readonly bool _forList = forList; - public ProductBundleItemOrderDataConverter(bool forList) - : base(typeof(object)) - { - _forList = forList; - } + public override bool CanConvertFrom(Type type) => type == typeof(string); - public override bool CanConvertFrom(Type type) - { - return type == typeof(string); - } - - public override bool CanConvertTo(Type type) - { - return type == typeof(string); - } + public override bool CanConvertTo(Type type) => type == typeof(string); public override object ConvertFrom(CultureInfo culture, object value) { diff --git a/src/Smartstore.Core/Catalog/Products/Domain/ProductReviewHelpfulness.cs b/src/Smartstore.Core/Catalog/Products/Domain/ProductReviewHelpfulness.cs index 6cc6cf5732..1361d39ada 100644 --- a/src/Smartstore.Core/Catalog/Products/Domain/ProductReviewHelpfulness.cs +++ b/src/Smartstore.Core/Catalog/Products/Domain/ProductReviewHelpfulness.cs @@ -7,13 +7,10 @@ namespace Smartstore.Core.Catalog.Products { internal class ProductReviewHelpfulnessMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { - builder.HasOne(c => c.ProductReview) + public void Configure(EntityTypeBuilder builder) => builder.HasOne(c => c.ProductReview) .WithMany(c => c.ProductReviewHelpfulnessEntries) .HasForeignKey(c => c.ProductReviewId) .OnDelete(DeleteBehavior.NoAction); - } } /// diff --git a/src/Smartstore.Core/Catalog/Products/Events/BarcodeScannedEvent.cs b/src/Smartstore.Core/Catalog/Products/Events/BarcodeScannedEvent.cs index 808def4880..1b1a49a99e 100644 --- a/src/Smartstore.Core/Catalog/Products/Events/BarcodeScannedEvent.cs +++ b/src/Smartstore.Core/Catalog/Products/Events/BarcodeScannedEvent.cs @@ -1,14 +1,8 @@ namespace Smartstore.Core.Catalog.Products { - public class BarcodeScannedEvent + public class BarcodeScannedEvent(int productId, string action) { - public BarcodeScannedEvent(int productId, string action) - { - ProductId = Guard.NotNull(productId); - Action = action; - } - - public int ProductId { get; } - public string Action { get; } + public int ProductId { get; } = Guard.NotNull(productId); + public string Action { get; } = action; } } diff --git a/src/Smartstore.Core/Catalog/Products/Events/ProductClonedEvent.cs b/src/Smartstore.Core/Catalog/Products/Events/ProductClonedEvent.cs index a9b9a6fa41..0ec7dc5b74 100644 --- a/src/Smartstore.Core/Catalog/Products/Events/ProductClonedEvent.cs +++ b/src/Smartstore.Core/Catalog/Products/Events/ProductClonedEvent.cs @@ -1,14 +1,8 @@ namespace Smartstore.Core.Catalog.Products { - public class ProductClonedEvent + public class ProductClonedEvent(Product source, Product clone) { - public ProductClonedEvent(Product source, Product clone) - { - Source = Guard.NotNull(source); - Clone = Guard.NotNull(clone); - } - - public Product Source { get; } - public Product Clone { get; } + public Product Source { get; } = Guard.NotNull(source); + public Product Clone { get; } = Guard.NotNull(clone); } } diff --git a/src/Smartstore.Core/Catalog/Products/Hooks/ProductBundleItemHook.cs b/src/Smartstore.Core/Catalog/Products/Hooks/ProductBundleItemHook.cs index 6a371ae1f3..9bd6640366 100644 --- a/src/Smartstore.Core/Catalog/Products/Hooks/ProductBundleItemHook.cs +++ b/src/Smartstore.Core/Catalog/Products/Hooks/ProductBundleItemHook.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Catalog.Products { - internal class ProductBundleItemHook : AsyncDbSaveHook + internal class ProductBundleItemHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public ProductBundleItemHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override Task OnDeletingAsync(ProductBundleItem entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Products/Hooks/ProductHook.cs b/src/Smartstore.Core/Catalog/Products/Hooks/ProductHook.cs index d67684374e..1355ed1b91 100644 --- a/src/Smartstore.Core/Catalog/Products/Hooks/ProductHook.cs +++ b/src/Smartstore.Core/Catalog/Products/Hooks/ProductHook.cs @@ -6,27 +6,20 @@ namespace Smartstore.Core.Catalog.Products { [Important] - internal class ProductHook : AsyncDbSaveHook + internal class ProductHook( + SmartDbContext db, + Lazy stockSubscriptionService, + Lazy productService) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly Lazy _stockSubscriptionService; - private readonly Lazy _productService; + private readonly SmartDbContext _db = db; + private readonly Lazy _stockSubscriptionService = stockSubscriptionService; + private readonly Lazy _productService = productService; private readonly HashSet _toSendStockNotification = new(); private readonly HashSet _toAdjustInventory = new(); private readonly HashSet _oldSampleDownloadIds = new(); private string _hookErrorMessage; - public ProductHook( - SmartDbContext db, - Lazy stockSubscriptionService, - Lazy productService) - { - _db = db; - _stockSubscriptionService = stockSubscriptionService; - _productService = productService; - } - protected override Task OnInsertedAsync(Product entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Products/Hooks/ProductMediaFileHook.cs b/src/Smartstore.Core/Catalog/Products/Hooks/ProductMediaFileHook.cs index 3619e0733e..be43d00f1f 100644 --- a/src/Smartstore.Core/Catalog/Products/Hooks/ProductMediaFileHook.cs +++ b/src/Smartstore.Core/Catalog/Products/Hooks/ProductMediaFileHook.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Catalog.Products { - internal class ProductMediaFileHook : AsyncDbSaveHook + internal class ProductMediaFileHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - - public ProductMediaFileHook(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; protected override Task OnInsertedAsync(ProductMediaFile entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Catalog/Products/Import/ProductImporter.cs b/src/Smartstore.Core/Catalog/Products/Import/ProductImporter.cs index dfe12f35da..ceec6e401e 100644 --- a/src/Smartstore.Core/Catalog/Products/Import/ProductImporter.cs +++ b/src/Smartstore.Core/Catalog/Products/Import/ProductImporter.cs @@ -16,7 +16,12 @@ namespace Smartstore.Core.DataExchange.Import { - public class ProductImporter : EntityImporterBase + public class ProductImporter( + ICommonServices services, + IStoreMappingService storeMappingService, + IUrlService urlService, + IMediaImporter mediaImporter, + SeoSettings seoSettings) : EntityImporterBase(services, storeMappingService, urlService, seoSettings) { const string CargoDataKey = "ProductImporter.CargoData"; @@ -41,18 +46,7 @@ public class ProductImporter : EntityImporterBase { nameof(Product.BundleTitleText), x => x.BundleTitleText } }.ToFrozenDictionary(); - private readonly IMediaImporter _mediaImporter; - - public ProductImporter( - ICommonServices services, - IStoreMappingService storeMappingService, - IUrlService urlService, - IMediaImporter mediaImporter, - SeoSettings seoSettings) - : base(services, storeMappingService, urlService, seoSettings) - { - _mediaImporter = mediaImporter; - } + private readonly IMediaImporter _mediaImporter = mediaImporter; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Catalog/Products/ProductBatchContext.cs b/src/Smartstore.Core/Catalog/Products/ProductBatchContext.cs index 86754acc1b..913ce39c22 100644 --- a/src/Smartstore.Core/Catalog/Products/ProductBatchContext.cs +++ b/src/Smartstore.Core/Catalog/Products/ProductBatchContext.cs @@ -107,80 +107,47 @@ internal IManufacturerService ManufacturerService public IReadOnlyList ProductIds => _productIds; - public LazyMultimap Attributes - { - get => _attributes ??= new LazyMultimap(LoadAttributes, _productIds); - } + public LazyMultimap Attributes => + _attributes ??= new LazyMultimap(LoadAttributes, _productIds); - public LazyMultimap AttributeCombinations - { - get => _attributeCombinations ??= new LazyMultimap(LoadAttributeCombinations, _productIds); - } + public LazyMultimap AttributeCombinations => + _attributeCombinations ??= new LazyMultimap(LoadAttributeCombinations, _productIds); - public LazyMultimap TierPrices - { - get => _tierPrices ??= new LazyMultimap(LoadTierPrices, _productIdsTierPrices); - } + public LazyMultimap TierPrices => + _tierPrices ??= new LazyMultimap(LoadTierPrices, _productIdsTierPrices); - public LazyMultimap ProductCategories - { - get => _productCategories ??= new LazyMultimap(LoadProductCategories, _productIds); - } + public LazyMultimap ProductCategories => + _productCategories ??= new LazyMultimap(LoadProductCategories, _productIds); - public LazyMultimap ProductManufacturers - { - get => _productManufacturers ??= new LazyMultimap(LoadProductManufacturers, _productIds); - } + public LazyMultimap ProductManufacturers => + _productManufacturers ??= new LazyMultimap(LoadProductManufacturers, _productIds); - public LazyMultimap AppliedDiscounts - { - get => _appliedDiscounts ??= new LazyMultimap(LoadAppliedDiscounts, _productIdsAppliedDiscounts); - } + public LazyMultimap AppliedDiscounts => + _appliedDiscounts ??= new LazyMultimap(LoadAppliedDiscounts, _productIdsAppliedDiscounts); - public LazyMultimap ProductBundleItems - { - get => _productBundleItems ??= new LazyMultimap(LoadProductBundleItems, _bundledProductIds); - } + public LazyMultimap ProductBundleItems => + _productBundleItems ??= new LazyMultimap(LoadProductBundleItems, _bundledProductIds); - public LazyMultimap AssociatedProducts - { - get => _associatedProducts ??= new LazyMultimap(LoadAssociatedProducts, _groupedProductIds); - } + public LazyMultimap AssociatedProducts => + _associatedProducts ??= new LazyMultimap(LoadAssociatedProducts, _groupedProductIds); - public LazyMultimap ProductMediaFiles - { - get => _productMediaFiles ??= new LazyMultimap(LoadProductMediaFiles, _productIds); - } + public LazyMultimap ProductMediaFiles => + _productMediaFiles ??= new LazyMultimap(LoadProductMediaFiles, _productIds); - public LazyMultimap ProductTags - { - get => _productTags ??= new LazyMultimap(LoadProductTags, _productIds); - } + public LazyMultimap ProductTags => + _productTags ??= new LazyMultimap(LoadProductTags, _productIds); - public LazyMultimap SpecificationAttributes - { - get => _specificationAttributes ??= new LazyMultimap(LoadSpecificationAttributes, _productIds); - } + public LazyMultimap SpecificationAttributes => + _specificationAttributes ??= new LazyMultimap(LoadSpecificationAttributes, _productIds); - public LazyMultimap EssentialAttributes - { - get => _essentialSpecAttributes ??= new LazyMultimap(LoadEssentialAttributes, _productIds); - } + public LazyMultimap EssentialAttributes => + _essentialSpecAttributes ??= new LazyMultimap(LoadEssentialAttributes, _productIds); - public LazyMultimap Downloads - { - get => _downloads ??= new LazyMultimap(LoadDownloads, _productIds); - } + public LazyMultimap Downloads => _downloads ??= new LazyMultimap(LoadDownloads, _productIds); - public LazyMultimap RelatedProducts - { - get => _relatedProducts ??= new LazyMultimap(LoadRelatedProducts, _productIds); - } + public LazyMultimap RelatedProducts => _relatedProducts ??= new LazyMultimap(LoadRelatedProducts, _productIds); - public LazyMultimap CrossSellProducts - { - get => _crossSellProducts ??= new LazyMultimap(LoadCrossSellProducts, _productIds); - } + public LazyMultimap CrossSellProducts => _crossSellProducts ??= new LazyMultimap(LoadCrossSellProducts, _productIds); /// /// Adds more product identifiers. Enables the subsequent loading of products. @@ -243,6 +210,7 @@ protected virtual async Task> LoadAttribu .ThenBy(x => x.DisplayOrder) .AsQueryable(); var attributes = await query.ToListAsync(); + return attributes.ToMultimap(x => x.ProductId, x => x); } @@ -254,6 +222,7 @@ protected virtual async Task> .OrderBy(x => x.ProductId) .AsQueryable(); var attributeCombinations = await query.ToListAsync(); + return attributeCombinations.ToMultimap(x => x.ProductId, x => x); } @@ -277,12 +246,14 @@ protected virtual async Task> LoadTierPrices(int[] ids) protected virtual async Task> LoadProductCategories(int[] ids) { var productCategories = await CategoryService.GetProductCategoriesByProductIdsAsync(ids, _includeHidden); + return productCategories.ToMultimap(x => x.ProductId, x => x); } protected virtual async Task> LoadProductManufacturers(int[] ids) { var productManufacturers = await ManufacturerService.GetProductManufacturersByProductIdsAsync(ids, _includeHidden); + return productManufacturers.ToMultimap(x => x.ProductId, x => x); } @@ -357,24 +328,22 @@ protected virtual async Task> LoadProductMediaFi return files.ToMultimap(x => x.ProductId, x => x); } - protected virtual async Task> LoadProductTags(int[] ids) - { - return await ProductService.GetProductTagsByProductIdsAsync(ids, _includeHidden); - } + protected virtual async Task> LoadProductTags(int[] ids) => + await ProductService.GetProductTagsByProductIdsAsync(ids, _includeHidden); - private static IQueryable BuildSpecAttributesQuery(SmartDbContext db, int[] ids, bool? essentialAttributes) - { - return db.ProductSpecificationAttributes + private static IQueryable BuildSpecAttributesQuery(SmartDbContext db, int[] ids, bool? essentialAttributes) => + db.ProductSpecificationAttributes .AsNoTracking() .Include(x => x.SpecificationAttributeOption) .ThenInclude(x => x.SpecificationAttribute) .Where(x => ids.Contains(x.ProductId) && (essentialAttributes == null || x.SpecificationAttributeOption.SpecificationAttribute.Essential == essentialAttributes.Value)) .OrderBy(x => x.ProductId) .OrderBy(x => x.DisplayOrder); - } + protected virtual async Task> LoadSpecificationAttributes(int[] ids) { var attributes = await BuildSpecAttributesQuery(_db, ids, null).ToListAsync(); + return attributes.ToMultimap(x => x.ProductId, x => x); } @@ -389,6 +358,7 @@ protected virtual async Task> LoadE } var attributes = await BuildSpecAttributesQuery(_db, ids, true).ToListAsync(); + return attributes.ToMultimap(x => x.ProductId, x => x); } diff --git a/src/Smartstore.Core/Catalog/Products/Rules/ProductRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Products/Rules/ProductRuleOptionsProvider.cs index 50f438ef18..f6e400ae15 100644 --- a/src/Smartstore.Core/Catalog/Products/Rules/ProductRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Products/Rules/ProductRuleOptionsProvider.cs @@ -6,27 +6,18 @@ namespace Smartstore.Core.Catalog.Products.Rules { - public partial class ProductRuleOptionsProvider : IRuleOptionsProvider + public partial class ProductRuleOptionsProvider( + SmartDbContext db, + IWorkContext workContext, + ICatalogSearchService catalogSearchService, + ILocalizedEntityService localizedEntityService, + SearchSettings searchSettings) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly ICatalogSearchService _catalogSearchService; - private readonly ILocalizedEntityService _localizedEntityService; - private readonly SearchSettings _searchSettings; - - public ProductRuleOptionsProvider( - SmartDbContext db, - IWorkContext workContext, - ICatalogSearchService catalogSearchService, - ILocalizedEntityService localizedEntityService, - SearchSettings searchSettings) - { - _db = db; - _workContext = workContext; - _catalogSearchService = catalogSearchService; - _localizedEntityService = localizedEntityService; - _searchSettings = searchSettings; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly ICatalogSearchService _catalogSearchService = catalogSearchService; + private readonly ILocalizedEntityService _localizedEntityService = localizedEntityService; + private readonly SearchSettings _searchSettings = searchSettings; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Products/Rules/ProductTagRuleOptionsProvider.cs b/src/Smartstore.Core/Catalog/Products/Rules/ProductTagRuleOptionsProvider.cs index 3b7e3584b8..d23b11e59b 100644 --- a/src/Smartstore.Core/Catalog/Products/Rules/ProductTagRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Catalog/Products/Rules/ProductTagRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductTagRuleOptionsProvider : IRuleOptionsProvider + public partial class ProductTagRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public ProductTagRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Products/Services/ProductCloner.cs b/src/Smartstore.Core/Catalog/Products/Services/ProductCloner.cs index 5a73eb811e..aac7f1b41a 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/ProductCloner.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/ProductCloner.cs @@ -14,33 +14,22 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductCloner : IProductCloner + public partial class ProductCloner( + SmartDbContext db, + IChronometer chronometer, + ILanguageService languageService, + IStoreMappingService storeMappingService, + ILocalizedEntityService localizedEntityService, + IProductAttributeMaterializer productAttributeMaterializer, + IUrlService urlService) : IProductCloner { - private readonly SmartDbContext _db; - private readonly IChronometer _chronometer; - private readonly ILanguageService _languageService; - private readonly IStoreMappingService _storeMappingService; - private readonly ILocalizedEntityService _localizedEntityService; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly IUrlService _urlService; - - public ProductCloner( - SmartDbContext db, - IChronometer chronometer, - ILanguageService languageService, - IStoreMappingService storeMappingService, - ILocalizedEntityService localizedEntityService, - IProductAttributeMaterializer productAttributeMaterializer, - IUrlService urlService) - { - _db = db; - _chronometer = chronometer; - _languageService = languageService; - _storeMappingService = storeMappingService; - _localizedEntityService = localizedEntityService; - _productAttributeMaterializer = productAttributeMaterializer; - _urlService = urlService; - } + private readonly SmartDbContext _db = db; + private readonly IChronometer _chronometer = chronometer; + private readonly ILanguageService _languageService = languageService; + private readonly IStoreMappingService _storeMappingService = storeMappingService; + private readonly ILocalizedEntityService _localizedEntityService = localizedEntityService; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly IUrlService _urlService = urlService; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Catalog/Products/Services/ProductCompareService.cs b/src/Smartstore.Core/Catalog/Products/Services/ProductCompareService.cs index 67bfa5e992..f17bb02d31 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/ProductCompareService.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/ProductCompareService.cs @@ -5,24 +5,16 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductCompareService : IProductCompareService + public partial class ProductCompareService( + SmartDbContext db, + IHttpContextAccessor httpContextAccessor, + CatalogSettings catalogSettings, + ICatalogSearchService catalogSearchService) : IProductCompareService { - private readonly SmartDbContext _db; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly CatalogSettings _catalogSettings; - private readonly ICatalogSearchService _catalogSearchService; - - public ProductCompareService( - SmartDbContext db, - IHttpContextAccessor httpContextAccessor, - CatalogSettings catalogSettings, - ICatalogSearchService catalogSearchService) - { - _db = db; - _httpContextAccessor = httpContextAccessor; - _catalogSettings = catalogSettings; - _catalogSearchService = catalogSearchService; - } + private readonly SmartDbContext _db = db; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly CatalogSettings _catalogSettings = catalogSettings; + private readonly ICatalogSearchService _catalogSearchService = catalogSearchService; public virtual async Task CountComparedProductsAsync() { diff --git a/src/Smartstore.Core/Catalog/Products/Services/ProductService.cs b/src/Smartstore.Core/Catalog/Products/Services/ProductService.cs index 04941c3237..f23f140766 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/ProductService.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/ProductService.cs @@ -20,45 +20,30 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductService : IProductService + public partial class ProductService( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext, + IEventPublisher eventPublisher, + ICacheManager cache, + IComponentContext componentContext, + Lazy productTagService, + IProductAttributeMaterializer productAttributeMaterializer, + IUrlService urlService, + IMessageFactory messageFactory, + LocalizationSettings localizationSettings) : IProductService { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly IEventPublisher _eventPublisher; - private readonly ICacheManager _cache; - private readonly IComponentContext _componentContext; - private readonly Lazy _productTagService; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly IUrlService _urlService; - private readonly IMessageFactory _messageFactory; - private readonly LocalizationSettings _localizationSettings; - - public ProductService( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext, - IEventPublisher eventPublisher, - ICacheManager cache, - IComponentContext componentContext, - Lazy productTagService, - IProductAttributeMaterializer productAttributeMaterializer, - IUrlService urlService, - IMessageFactory messageFactory, - LocalizationSettings localizationSettings) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - _eventPublisher = eventPublisher; - _cache = cache; - _componentContext = componentContext; - _productTagService = productTagService; - _productAttributeMaterializer = productAttributeMaterializer; - _urlService = urlService; - _messageFactory = messageFactory; - _localizationSettings = localizationSettings; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly ICacheManager _cache = cache; + private readonly IComponentContext _componentContext = componentContext; + private readonly Lazy _productTagService = productTagService; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly IUrlService _urlService = urlService; + private readonly IMessageFactory _messageFactory = messageFactory; + private readonly LocalizationSettings _localizationSettings = localizationSettings; public ILogger Logger { get; set; } = NullLogger.Instance; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Catalog/Products/Services/ProductTagService.cs b/src/Smartstore.Core/Catalog/Products/Services/ProductTagService.cs index 1d45b0a6a3..c3272d122c 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/ProductTagService.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/ProductTagService.cs @@ -6,22 +6,15 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductTagService : AsyncDbSaveHook, IProductTagService + public partial class ProductTagService(SmartDbContext db, IWorkContext workContext, ICacheManager cache) : AsyncDbSaveHook, IProductTagService { // {0} : include hidden, {1} : store ID, {2} : customer roles IDs. const string ProductTagCountKey = "producttag:count-{0}-{1}-{2}"; const string ProductTagPatternKey = "producttag:*"; - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly ICacheManager _cache; - - public ProductTagService(SmartDbContext db, IWorkContext workContext, ICacheManager cache) - { - _db = db; - _workContext = workContext; - _cache = cache; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly ICacheManager _cache = cache; #region Hook @@ -194,10 +187,7 @@ from sm in psm.DefaultIfEmpty() return result; } - public virtual Task ClearCacheAsync() - { - return _cache.RemoveByPatternAsync(ProductTagPatternKey); - } + public virtual Task ClearCacheAsync() => _cache.RemoveByPatternAsync(ProductTagPatternKey); private class ProductsPerTag { diff --git a/src/Smartstore.Core/Catalog/Products/Services/ProductUrlHelper.cs b/src/Smartstore.Core/Catalog/Products/Services/ProductUrlHelper.cs index efd13eb385..03b85f44c6 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/ProductUrlHelper.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/ProductUrlHelper.cs @@ -11,33 +11,22 @@ namespace Smartstore.Core.Catalog.Products { - public partial class ProductUrlHelper + public partial class ProductUrlHelper( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext, + IWebHelper webHelper, + Lazy urlHelper, + IHttpContextAccessor httpContextAccessor, + Lazy catalogSearchQueryAliasMapper) { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly IWebHelper _webHelper; - private readonly Lazy _urlHelper; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly Lazy _catalogSearchQueryAliasMapper; - - public ProductUrlHelper( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext, - IWebHelper webHelper, - Lazy urlHelper, - IHttpContextAccessor httpContextAccessor, - Lazy catalogSearchQueryAliasMapper) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - _webHelper = webHelper; - _urlHelper = urlHelper; - _httpContextAccessor = httpContextAccessor; - _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly IWebHelper _webHelper = webHelper; + private readonly Lazy _urlHelper = urlHelper; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly Lazy _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; /// /// URL of the product page used to create the new product URL. Created from route if null. diff --git a/src/Smartstore.Core/Catalog/Products/Services/RecentlyViewedProductsService.cs b/src/Smartstore.Core/Catalog/Products/Services/RecentlyViewedProductsService.cs index 72c8f0e576..e662c60f02 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/RecentlyViewedProductsService.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/RecentlyViewedProductsService.cs @@ -8,27 +8,18 @@ namespace Smartstore.Core.Catalog.Products { - public partial class RecentlyViewedProductsService : IRecentlyViewedProductsService + public partial class RecentlyViewedProductsService( + SmartDbContext db, + IStoreContext storeContext, + IWorkContext workContext, + IHttpContextAccessor httpContextAccessor, + CatalogSettings catalogSettings) : IRecentlyViewedProductsService { - private readonly SmartDbContext _db; - private readonly IStoreContext _storeContext; - private readonly IWorkContext _workContext; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly CatalogSettings _catalogSettings; - - public RecentlyViewedProductsService( - SmartDbContext db, - IStoreContext storeContext, - IWorkContext workContext, - IHttpContextAccessor httpContextAccessor, - CatalogSettings catalogSettings) - { - _db = db; - _storeContext = storeContext; - _workContext = workContext; - _httpContextAccessor = httpContextAccessor; - _catalogSettings = catalogSettings; - } + private readonly SmartDbContext _db = db; + private readonly IStoreContext _storeContext = storeContext; + private readonly IWorkContext _workContext = workContext; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly CatalogSettings _catalogSettings = catalogSettings; public virtual async Task> GetRecentlyViewedProductsAsync( int count, diff --git a/src/Smartstore.Core/Catalog/Products/Services/StockSubscriptionService.cs b/src/Smartstore.Core/Catalog/Products/Services/StockSubscriptionService.cs index 3bd566f2d0..e8bb7f5b3f 100644 --- a/src/Smartstore.Core/Catalog/Products/Services/StockSubscriptionService.cs +++ b/src/Smartstore.Core/Catalog/Products/Services/StockSubscriptionService.cs @@ -7,27 +7,18 @@ namespace Smartstore.Core.Catalog.Products { - public partial class StockSubscriptionService : IStockSubscriptionService + public partial class StockSubscriptionService( + SmartDbContext db, + IMessageFactory messageFactory, + IWorkContext workContext, + IStoreContext storeContext, + CatalogSettings catalogSettings) : IStockSubscriptionService { - private readonly SmartDbContext _db; - private readonly IMessageFactory _messageFactory; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly CatalogSettings _catalogSettings; - - public StockSubscriptionService( - SmartDbContext db, - IMessageFactory messageFactory, - IWorkContext workContext, - IStoreContext storeContext, - CatalogSettings catalogSettings) - { - _db = db; - _messageFactory = messageFactory; - _workContext = workContext; - _storeContext = storeContext; - _catalogSettings = catalogSettings; - } + private readonly SmartDbContext _db = db; + private readonly IMessageFactory _messageFactory = messageFactory; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly CatalogSettings _catalogSettings = catalogSettings; public Localizer T { get; set; } = NullLocalizer.Instance; @@ -172,11 +163,9 @@ public virtual async Task SendNotificationsToSubscribersAsync(Product produ return numberOfMessages; } - protected virtual async Task GetSubscriptionAsync(Product product, Customer customer, int storeId) - { - return await _db.BackInStockSubscriptions + protected virtual async Task GetSubscriptionAsync(Product product, Customer customer, int storeId) => + await _db.BackInStockSubscriptions .ApplyStandardFilter(product.Id, customer.Id, storeId) .FirstOrDefaultAsync(); - } } } diff --git a/src/Smartstore.Core/Catalog/Rules/AttributeRuleContext.cs b/src/Smartstore.Core/Catalog/Rules/AttributeRuleContext.cs index 90ef5b983b..455921c4ac 100644 --- a/src/Smartstore.Core/Catalog/Rules/AttributeRuleContext.cs +++ b/src/Smartstore.Core/Catalog/Rules/AttributeRuleContext.cs @@ -3,42 +3,32 @@ namespace Smartstore.Core.Catalog.Rules { - public class AttributeRuleContext + public class AttributeRuleContext( + Product product, + ProductVariantAttribute attribute, + IList selectedValues) { private int[] _selectedValueIds; - public AttributeRuleContext( - Product product, - ProductVariantAttribute attribute, - IList selectedValues) - { - Product = Guard.NotNull(product); - Attribute = Guard.NotNull(attribute); - SelectedValues = Guard.NotNull(selectedValues); - } - /// /// Gets the product belonging to . /// - public Product Product { get; } + public Product Product { get; } = Guard.NotNull(product); /// /// Gets the current product attribute to be checked. /// - public ProductVariantAttribute Attribute { get; } + public ProductVariantAttribute Attribute { get; } = Guard.NotNull(attribute); /// /// Gets the values of the currently selected product attributes. /// - public IList SelectedValues { get; } + public IList SelectedValues { get; } = Guard.NotNull(selectedValues); /// /// Gets the identifiers of the selected product attribute values. /// Only includes list-type attributes (). /// - public int[] SelectedValueIds - { - get => _selectedValueIds ??= SelectedValues.Select(x => x.Id).ToArray(); - } + public int[] SelectedValueIds => _selectedValueIds ??= SelectedValues.Select(x => x.Id).ToArray(); } } diff --git a/src/Smartstore.Core/Catalog/Rules/ProductRuleEvaluatorTask.cs b/src/Smartstore.Core/Catalog/Rules/ProductRuleEvaluatorTask.cs index 1e5d2b5ee6..a965704b64 100644 --- a/src/Smartstore.Core/Catalog/Rules/ProductRuleEvaluatorTask.cs +++ b/src/Smartstore.Core/Catalog/Rules/ProductRuleEvaluatorTask.cs @@ -11,21 +11,14 @@ namespace Smartstore.Core.Catalog.Rules /// /// Updates the system assignments to categories for rules. /// - public partial class ProductRuleEvaluatorTask : ITask + public partial class ProductRuleEvaluatorTask( + SmartDbContext db, + IRuleService ruleService, + IRuleProviderFactory ruleProviderFactory) : ITask { - protected readonly SmartDbContext _db; - protected readonly IRuleService _ruleService; - protected readonly IProductRuleProvider _productRuleProvider; - - public ProductRuleEvaluatorTask( - SmartDbContext db, - IRuleService ruleService, - IRuleProviderFactory ruleProviderFactory) - { - _db = db; - _ruleService = ruleService; - _productRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Product); - } + protected readonly SmartDbContext _db = db; + protected readonly IRuleService _ruleService = ruleService; + protected readonly IProductRuleProvider _productRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Product); public async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Catalog/Rules/ProductRuleProvider.cs b/src/Smartstore.Core/Catalog/Rules/ProductRuleProvider.cs index a9c5259c6d..d05081f77e 100644 --- a/src/Smartstore.Core/Catalog/Rules/ProductRuleProvider.cs +++ b/src/Smartstore.Core/Catalog/Rules/ProductRuleProvider.cs @@ -12,45 +12,33 @@ namespace Smartstore.Core.Catalog.Rules { - public partial class ProductRuleProvider : RuleProviderBase, IProductRuleProvider + public partial class ProductRuleProvider( + ICommonServices services, + IRuleService ruleService, + ICatalogSearchService catalogSearchService, + ICategoryService categoryService, + ILocalizationService localizationService, + CatalogSettings catalogSettings) : RuleProviderBase(RuleScope.Product), IProductRuleProvider { - private readonly ICommonServices _services; - private readonly IRuleService _ruleService; - private readonly ICatalogSearchService _catalogSearchService; - private readonly ICategoryService _categoryService; - private readonly ILocalizationService _localizationService; - private readonly CatalogSettings _catalogSettings; - - public ProductRuleProvider( - ICommonServices services, - IRuleService ruleService, - ICatalogSearchService catalogSearchService, - ICategoryService categoryService, - ILocalizationService localizationService, - CatalogSettings catalogSettings) - : base(RuleScope.Product) - { - _services = services; - _ruleService = ruleService; - _catalogSearchService = catalogSearchService; - _categoryService = categoryService; - _localizationService = localizationService; - _catalogSettings = catalogSettings; - } + private readonly ICommonServices _services = services; + private readonly IRuleService _ruleService = ruleService; + private readonly ICatalogSearchService _catalogSearchService = catalogSearchService; + private readonly ICategoryService _categoryService = categoryService; + private readonly ILocalizationService _localizationService = localizationService; + private readonly CatalogSettings _catalogSettings = catalogSettings; public Localizer T { get; set; } = NullLocalizer.Instance; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public async Task CreateExpressionGroupAsync(int ruleSetId) - { - return await _ruleService.CreateExpressionGroupAsync(ruleSetId, this) as SearchFilterExpressionGroup; - } + public async Task CreateExpressionGroupAsync(int ruleSetId) => + await _ruleService.CreateExpressionGroupAsync(ruleSetId, this) as SearchFilterExpressionGroup; public override async Task VisitRuleAsync(RuleEntity rule) { var expression = new SearchFilterExpression(); await base.ConvertRuleAsync(rule, expression); expression.Descriptor = ((RuleExpression)expression).Descriptor as SearchFilterDescriptor; + return expression; } diff --git a/src/Smartstore.Core/Catalog/Rules/SearchFilterDescriptor.cs b/src/Smartstore.Core/Catalog/Rules/SearchFilterDescriptor.cs index d91bb1081a..06f40b6095 100644 --- a/src/Smartstore.Core/Catalog/Rules/SearchFilterDescriptor.cs +++ b/src/Smartstore.Core/Catalog/Rules/SearchFilterDescriptor.cs @@ -30,9 +30,6 @@ public SearchFilterDescriptor(Func Filter { get; protected set; } - public override CatalogSearchQuery ApplyFilter(SearchFilterContext ctx) - { - return Filter(ctx, ctx.Expression.Value.Convert()); - } + public override CatalogSearchQuery ApplyFilter(SearchFilterContext ctx) => Filter(ctx, ctx.Expression.Value.Convert()); } } diff --git a/src/Smartstore.Core/Catalog/Search/CatalogSearchQuery.cs b/src/Smartstore.Core/Catalog/Search/CatalogSearchQuery.cs index abd64cf20a..e80f546d7f 100644 --- a/src/Smartstore.Core/Catalog/Search/CatalogSearchQuery.cs +++ b/src/Smartstore.Core/Catalog/Search/CatalogSearchQuery.cs @@ -206,18 +206,14 @@ public CatalogSearchQuery AllowedCustomerRoles(params int[] customerRoleIds) return this; } - public CatalogSearchQuery PublishedOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsPublished, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery PublishedOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsPublished, value).Mandatory().ExactMatch().NotAnalyzed()); /// /// Filters products based on their stock level. /// - public CatalogSearchQuery AvailableOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsAvailable, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery AvailableOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsAvailable, value).Mandatory().ExactMatch().NotAnalyzed()); /// /// Filters products by their availability date. @@ -240,15 +236,11 @@ public CatalogSearchQuery AvailableByDate(bool value) return this; } - public CatalogSearchQuery WithVisibility(ProductVisibility value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.Visibility, (int)value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery WithVisibility(ProductVisibility value) => + WithFilter(SearchFilter.ByField(KnownFilters.Visibility, (int)value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery HasParentGroupedProduct(params int[] parentProductIds) - { - return CreateFilter(KnownFilters.ParentId, parentProductIds); - } + public CatalogSearchQuery HasParentGroupedProduct(params int[] parentProductIds) => + CreateFilter(KnownFilters.ParentId, parentProductIds); public override CatalogSearchQuery HasStoreId(int id) { @@ -271,15 +263,10 @@ public override CatalogSearchQuery HasStoreId(int id) return this; } - public CatalogSearchQuery IsProductType(ProductType type) - { - return WithFilter(SearchFilter.ByField(KnownFilters.TypeId, (int)type).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery IsProductType(ProductType type) => + WithFilter(SearchFilter.ByField(KnownFilters.TypeId, (int)type).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery WithProductIds(params int[] ids) - { - return CreateFilter(KnownFilters.ProductId, ids); - } + public CatalogSearchQuery WithProductIds(params int[] ids) => CreateFilter(KnownFilters.ProductId, ids); public CatalogSearchQuery WithProductId(int? fromId, int? toId) { @@ -376,15 +363,9 @@ public CatalogSearchQuery HasAnyManufacturer(bool value) } } - public CatalogSearchQuery WithProductTagIds(params int[] ids) - { - return CreateFilter(KnownFilters.TagId, ids); - } + public CatalogSearchQuery WithProductTagIds(params int[] ids) => CreateFilter(KnownFilters.TagId, ids); - public CatalogSearchQuery WithDeliveryTimeIds(params int[] ids) - { - return CreateFilter(KnownFilters.DeliveryId, ids); - } + public CatalogSearchQuery WithDeliveryTimeIds(params int[] ids) => CreateFilter(KnownFilters.DeliveryId, ids); public CatalogSearchQuery WithCondition(params ProductCondition[] conditions) { @@ -405,45 +386,29 @@ public CatalogSearchQuery WithCondition(params ProductCondition[] conditions) return this; } - public CatalogSearchQuery HomePageProductsOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.ShowOnHomepage, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery HomePageProductsOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.ShowOnHomepage, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery DownloadOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsDownload, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery DownloadOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsDownload, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery RecurringOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsRecurring, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery RecurringOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsRecurring, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery ShipEnabledOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsShippingEnabled, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery ShipEnabledOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsShippingEnabled, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery FreeShippingOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsFreeShipping, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery FreeShippingOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsFreeShipping, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery TaxExemptOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsTaxExempt, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery TaxExemptOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsTaxExempt, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery EsdOnly(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.IsEsd, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery EsdOnly(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.IsEsd, value).Mandatory().ExactMatch().NotAnalyzed()); - public CatalogSearchQuery HasDiscount(bool value) - { - return WithFilter(SearchFilter.ByField(KnownFilters.HasDiscount, value).Mandatory().ExactMatch().NotAnalyzed()); - } + public CatalogSearchQuery HasDiscount(bool value) => + WithFilter(SearchFilter.ByField(KnownFilters.HasDiscount, value).Mandatory().ExactMatch().NotAnalyzed()); public CatalogSearchQuery WithStockQuantity( int? fromQuantity, diff --git a/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryContext.cs b/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryContext.cs index 6474e53f70..596dd4a129 100644 --- a/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryContext.cs +++ b/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryContext.cs @@ -2,15 +2,10 @@ namespace Smartstore.Core.Catalog.Search { - public class CatalogSearchQueryContext : SearchQueryContext + public class CatalogSearchQueryContext(CatalogSearchQuery query, + ICommonServices services) : SearchQueryContext(query) { - public CatalogSearchQueryContext(CatalogSearchQuery query, ICommonServices services) - : base(query) - { - Services = Guard.NotNull(services); - } - - public ICommonServices Services { get; } + public ICommonServices Services { get; } = Guard.NotNull(services); public int? CategoryId { get; set; } public int? ManufacturerId { get; set; } } diff --git a/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryVisitor.cs b/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryVisitor.cs index 9f55fd70a5..b0f3982c67 100644 --- a/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryVisitor.cs +++ b/src/Smartstore.Core/Catalog/Search/CatalogSearchQueryVisitor.cs @@ -617,22 +617,18 @@ private static IQueryable ApplyFeaturedSorting(IQueryable quer } } - private static IQueryable ApplyCategoriesFilter(IQueryable query, int[] ids, bool? featuredOnly) - { - return + private static IQueryable ApplyCategoriesFilter(IQueryable query, int[] ids, bool? featuredOnly) => from p in query from pc in p.ProductCategories.Where(pc => ids.Contains(pc.CategoryId)) where !featuredOnly.HasValue || featuredOnly.Value == pc.IsFeaturedProduct select p; - } - private static IQueryable ApplyManufacturersFilter(IQueryable query, int[] ids, bool? featuredOnly) - { - return + + private static IQueryable ApplyManufacturersFilter(IQueryable query, int[] ids, bool? featuredOnly) => from p in query from pm in p.ProductManufacturers.Where(pm => ids.Contains(pm.ManufacturerId)) where !featuredOnly.HasValue || featuredOnly.Value == pm.IsFeaturedProduct select p; - } + } } diff --git a/src/Smartstore.Core/Catalog/Search/CatalogSearchService.cs b/src/Smartstore.Core/Catalog/Search/CatalogSearchService.cs index c5e480d47a..0dcb9696de 100644 --- a/src/Smartstore.Core/Catalog/Search/CatalogSearchService.cs +++ b/src/Smartstore.Core/Catalog/Search/CatalogSearchService.cs @@ -11,24 +11,16 @@ namespace Smartstore.Core.Catalog.Search { - public partial class CatalogSearchService : SearchServiceBase, ICatalogSearchService, IXmlSitemapPublisher + public partial class CatalogSearchService( + SmartDbContext db, + ICommonServices services, + IIndexManager indexManager, + ICurrencyService currencyService) : SearchServiceBase, ICatalogSearchService, IXmlSitemapPublisher { - private readonly SmartDbContext _db; - private readonly ICommonServices _services; - private readonly IIndexManager _indexManager; - private readonly ICurrencyService _currencyService; - - public CatalogSearchService( - SmartDbContext db, - ICommonServices services, - IIndexManager indexManager, - ICurrencyService currencyService) - { - _db = db; - _services = services; - _indexManager = indexManager; - _currencyService = currencyService; - } + private readonly SmartDbContext _db = db; + private readonly ICommonServices _services = services; + private readonly IIndexManager _indexManager = indexManager; + private readonly ICurrencyService _currencyService = currencyService; public ILogger Logger { get; set; } = NullLogger.Instance; public Localizer T { get; set; } = NullLocalizer.Instance; @@ -38,6 +30,7 @@ public CatalogSearchService( public IQueryable PrepareQuery(CatalogSearchQuery searchQuery, IQueryable baseQuery = null) { var linqCatalogSearchService = _services.ResolveNamed("linq"); + return linqCatalogSearchService.PrepareQuery(searchQuery, baseQuery); } @@ -234,10 +227,7 @@ protected virtual void ApplyFacetLabels(IDictionary facets) } } - protected virtual string FormatPrice(decimal price) - { - return _currencyService.ConvertToWorkingCurrency(price).ToString(); - } + protected virtual string FormatPrice(decimal price) => _currencyService.ConvertToWorkingCurrency(price).ToString(); #region XML Sitemap diff --git a/src/Smartstore.Core/Catalog/Search/Facets/CatalogFacetUrlHelper.cs b/src/Smartstore.Core/Catalog/Search/Facets/CatalogFacetUrlHelper.cs index 05988a209b..f5fc1600c4 100644 --- a/src/Smartstore.Core/Catalog/Search/Facets/CatalogFacetUrlHelper.cs +++ b/src/Smartstore.Core/Catalog/Search/Facets/CatalogFacetUrlHelper.cs @@ -6,7 +6,10 @@ namespace Smartstore.Core.Search.Facets { - public partial class CatalogFacetUrlHelper : FacetUrlHelperBase + public partial class CatalogFacetUrlHelper( + IHttpContextAccessor httpContextAccessor, + IWorkContext workContext, + ICatalogSearchQueryAliasMapper catalogAliasMapper) : FacetUrlHelperBase(httpContextAccessor.HttpContext?.Request) { private readonly static FrozenDictionary _queryNames = new Dictionary() { @@ -19,18 +22,8 @@ public partial class CatalogFacetUrlHelper : FacetUrlHelperBase { FacetGroupKind.NewArrivals, "n" } }.ToFrozenDictionary(); - private readonly IWorkContext _workContext; - private readonly ICatalogSearchQueryAliasMapper _catalogAliasMapper; - - public CatalogFacetUrlHelper( - IHttpContextAccessor httpContextAccessor, - IWorkContext workContext, - ICatalogSearchQueryAliasMapper catalogAliasMapper) - : base(httpContextAccessor.HttpContext?.Request) - { - _workContext = workContext; - _catalogAliasMapper = catalogAliasMapper; - } + private readonly IWorkContext _workContext = workContext; + private readonly ICatalogSearchQueryAliasMapper _catalogAliasMapper = catalogAliasMapper; public override int Order => 0; diff --git a/src/Smartstore.Core/Catalog/Search/Hooks/SearchQueryAliasHook.cs b/src/Smartstore.Core/Catalog/Search/Hooks/SearchQueryAliasHook.cs index 5ec1d56cc4..ac5cad3af5 100644 --- a/src/Smartstore.Core/Catalog/Search/Hooks/SearchQueryAliasHook.cs +++ b/src/Smartstore.Core/Catalog/Search/Hooks/SearchQueryAliasHook.cs @@ -11,24 +11,17 @@ namespace Smartstore.Core.Catalog.Search { [Important] - internal class SearchQueryAliasHook : AsyncDbSaveHook + internal class SearchQueryAliasHook( + SmartDbContext db, + Lazy catalogSearchQueryAliasMapper, + SeoSettings seoSettings) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly Lazy _catalogSearchQueryAliasMapper; - private readonly SeoSettings _seoSettings; + private readonly SmartDbContext _db = db; + private readonly Lazy _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; + private readonly SeoSettings _seoSettings = seoSettings; private string _errorMessage; - public SearchQueryAliasHook( - SmartDbContext db, - Lazy catalogSearchQueryAliasMapper, - SeoSettings seoSettings) - { - _db = db; - _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; - _seoSettings = seoSettings; - } - public Localizer T { get; set; } = NullLocalizer.Instance; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Catalog/Search/LinqCatalogSearchService.cs b/src/Smartstore.Core/Catalog/Search/LinqCatalogSearchService.cs index ec3a202a17..d8208dc8c8 100644 --- a/src/Smartstore.Core/Catalog/Search/LinqCatalogSearchService.cs +++ b/src/Smartstore.Core/Catalog/Search/LinqCatalogSearchService.cs @@ -9,31 +9,21 @@ namespace Smartstore.Core.Catalog.Search { - public partial class LinqCatalogSearchService : SearchServiceBase, ICatalogSearchService + public partial class LinqCatalogSearchService( + SmartDbContext db, + IEnumerable> queryVisitors, + ICommonServices services, + ICategoryService categoryService) : SearchServiceBase, ICatalogSearchService { private static readonly int[] _priceThresholds = new[] { 10, 25, 50, 100, 250, 500, 1000 }; - private readonly SmartDbContext _db; - private readonly LinqSearchQueryVisitor[] _queryVisitors; - private readonly ICommonServices _services; - private readonly ICategoryService _categoryService; + private readonly SmartDbContext _db = db; + private readonly LinqSearchQueryVisitor[] _queryVisitors = queryVisitors.OrderBy(x => x.Order).ToArray(); + private readonly ICommonServices _services = services; + private readonly ICategoryService _categoryService = categoryService; - public LinqCatalogSearchService( - SmartDbContext db, - IEnumerable> queryVisitors, - ICommonServices services, - ICategoryService categoryService) - { - _db = db; - _queryVisitors = queryVisitors.OrderBy(x => x.Order).ToArray(); - _services = services; - _categoryService = categoryService; - } - - public IQueryable PrepareQuery(CatalogSearchQuery searchQuery, IQueryable baseQuery = null) - { - return GetProductQuery(searchQuery, baseQuery); - } + public IQueryable PrepareQuery(CatalogSearchQuery searchQuery, IQueryable baseQuery = null) => + GetProductQuery(searchQuery, baseQuery); public async Task SearchAsync(CatalogSearchQuery searchQuery, bool direct = false) { @@ -315,6 +305,7 @@ private async Task> GetLocalizedNames(string entityName, .ToListAsync(); var result = values.ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); + return result; } diff --git a/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryAliasMapper.cs b/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryAliasMapper.cs index d8cb532f91..5446bb1381 100644 --- a/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryAliasMapper.cs +++ b/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryAliasMapper.cs @@ -7,7 +7,10 @@ namespace Smartstore.Core.Catalog.Search.Modelling { - public partial class CatalogSearchQueryAliasMapper : ICatalogSearchQueryAliasMapper + public partial class CatalogSearchQueryAliasMapper( + SmartDbContext db, + ICacheManager cache, + ISettingService settingService) : ICatalogSearchQueryAliasMapper { private const string ALL_ATTRIBUTE_ID_BY_ALIAS_KEY = "search:attribute.id.alias.mappings.all"; private const string ALL_ATTRIBUTE_ALIAS_BY_ID_KEY = "search:attribute.alias.id.mappings.all"; @@ -16,19 +19,9 @@ public partial class CatalogSearchQueryAliasMapper : ICatalogSearchQueryAliasMap private const string ALL_VARIANT_ID_BY_ALIAS_KEY = "search:variant.id.alias.mappings.all"; private const string ALL_VARIANT_ALIAS_BY_ID_KEY = "search:variant.alias.id.mappings.all"; - private readonly SmartDbContext _db; - private readonly ICacheManager _cache; - private readonly ISettingService _settingService; - - public CatalogSearchQueryAliasMapper( - SmartDbContext db, - ICacheManager cache, - ISettingService settingService) - { - _db = db; - _cache = cache; - _settingService = settingService; - } + private readonly SmartDbContext _db = db; + private readonly ICacheManager _cache = cache; + private readonly ISettingService _settingService = settingService; #region Specification Attributes @@ -392,13 +385,11 @@ protected virtual IDictionary GetVariantAliasByIdMappings() public string GetCommonFacetAliasByGroupKind(FacetGroupKind kind, int languageId) { var mappings = GetCommonFacetAliasByGroupKindMappings(); + return mappings.Get(FacetUtility.GetFacetAliasSettingKey(kind, languageId)); } - public Task ClearCommonFacetCacheAsync() - { - return _cache.RemoveAsync(ALL_COMMONFACET_ALIAS_BY_KIND_KEY); - } + public Task ClearCommonFacetCacheAsync() => _cache.RemoveAsync(ALL_COMMONFACET_ALIAS_BY_KIND_KEY); protected virtual IDictionary GetCommonFacetAliasByGroupKindMappings() { @@ -449,23 +440,15 @@ protected virtual IDictionary GetCommonFacetAliasByGroupKindMapp #region Utilities - protected static string CreateKey(string prefix, int languageId, string alias) - { - return $"{prefix}.{languageId}.{alias}"; - } - protected static string CreateKey(string prefix, int languageId, int attributeId) - { - return $"{prefix}.{languageId}.{attributeId}"; - } + protected static string CreateKey(string prefix, int languageId, string alias) => + $"{prefix}.{languageId}.{alias}"; + protected static string CreateKey(string prefix, int languageId, int attributeId) => + $"{prefix}.{languageId}.{attributeId}"; - protected static string CreateOptionKey(string prefix, int languageId, int attributeId, string optionAlias) - { - return $"{prefix}.{languageId}.{attributeId}.{optionAlias}"; - } - protected static string CreateOptionKey(string prefix, int languageId, int optionId) - { - return $"{prefix}.{languageId}.{optionId}"; - } + protected static string CreateOptionKey(string prefix, int languageId, int attributeId, string optionAlias) => + $"{prefix}.{languageId}.{attributeId}.{optionAlias}"; + protected static string CreateOptionKey(string prefix, int languageId, int optionId) => + $"{prefix}.{languageId}.{optionId}"; protected void CacheLocalizedAlias(string localeKeyGroup, Action caching) { diff --git a/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryFactory.cs b/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryFactory.cs index f02e2c94cc..238494c65f 100644 --- a/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryFactory.cs +++ b/src/Smartstore.Core/Catalog/Search/Modelling/CatalogSearchQueryFactory.cs @@ -27,26 +27,17 @@ namespace Smartstore.Core.Catalog.Search.Modelling * - Variants & attributes */ - public partial class CatalogSearchQueryFactory : SearchQueryFactoryBase, ICatalogSearchQueryFactory + public partial class CatalogSearchQueryFactory( + IHttpContextAccessor httpContextAccessor, + ICommonServices services, + ICatalogSearchQueryAliasMapper catalogSearchQueryAliasMapper, + CatalogSettings catalogSettings, + SearchSettings searchSettings) : SearchQueryFactoryBase(httpContextAccessor), ICatalogSearchQueryFactory { - protected readonly ICommonServices _services; - protected readonly ICatalogSearchQueryAliasMapper _catalogSearchQueryAliasMapper; - protected readonly CatalogSettings _catalogSettings; - protected readonly SearchSettings _searchSettings; - - public CatalogSearchQueryFactory( - IHttpContextAccessor httpContextAccessor, - ICommonServices services, - ICatalogSearchQueryAliasMapper catalogSearchQueryAliasMapper, - CatalogSettings catalogSettings, - SearchSettings searchSettings) - : base(httpContextAccessor) - { - _services = services; - _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; - _catalogSettings = catalogSettings; - _searchSettings = searchSettings; - } + protected readonly ICommonServices _services = services; + protected readonly ICatalogSearchQueryAliasMapper _catalogSearchQueryAliasMapper = catalogSearchQueryAliasMapper; + protected readonly CatalogSettings _catalogSettings = catalogSettings; + protected readonly SearchSettings _searchSettings = searchSettings; protected override string[] Tokens => new[] { "q", "i", "s", "o", "p", "c", "m", "r", "a", "n", "d", "v" }; diff --git a/src/Smartstore.Core/Checkout/Affiliates/Filters/CheckAffiliateAttribute.cs b/src/Smartstore.Core/Checkout/Affiliates/Filters/CheckAffiliateAttribute.cs index 160578ed1d..9c588ca16a 100644 --- a/src/Smartstore.Core/Checkout/Affiliates/Filters/CheckAffiliateAttribute.cs +++ b/src/Smartstore.Core/Checkout/Affiliates/Filters/CheckAffiliateAttribute.cs @@ -14,16 +14,10 @@ public CheckAffiliateAttribute() { } - class CheckAffiliateFilter : IAsyncActionFilter + class CheckAffiliateFilter(SmartDbContext db, IWorkContext workContext) : IAsyncActionFilter { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - - public CheckAffiliateFilter(SmartDbContext db, IWorkContext workContext) - { - _db = db; - _workContext = workContext; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { diff --git a/src/Smartstore.Core/Checkout/Affiliates/Rules/AffiliateRuleOptionsProvider.cs b/src/Smartstore.Core/Checkout/Affiliates/Rules/AffiliateRuleOptionsProvider.cs index e24566ad47..ca4079aae9 100644 --- a/src/Smartstore.Core/Checkout/Affiliates/Rules/AffiliateRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Checkout/Affiliates/Rules/AffiliateRuleOptionsProvider.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Checkout.Affiliates.Rules { - public partial class AffiliateRuleOptionsProvider : IRuleOptionsProvider + public partial class AffiliateRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public AffiliateRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeSelection.cs b/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeSelection.cs index 7bca7dbc1a..a520307149 100644 --- a/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeSelection.cs +++ b/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeSelection.cs @@ -8,19 +8,15 @@ namespace Smartstore.Core.Checkout.Attributes /// /// This class can parse strings with XML or JSON format to and vice versa. /// - public class CheckoutAttributeSelection : AttributeSelection + /// + /// Creates checkout attribute selection from string as . + /// Use to access parsed attributes afterwards. + /// + /// + /// Automatically differentiates between XML and JSON. + /// + /// XML or JSON attributes string. + public class CheckoutAttributeSelection(string rawAttributes) : AttributeSelection(rawAttributes, "CheckoutAttribute") { - /// - /// Creates checkout attribute selection from string as . - /// Use to access parsed attributes afterwards. - /// - /// - /// Automatically differentiates between XML and JSON. - /// - /// XML or JSON attributes string. - public CheckoutAttributeSelection(string rawAttributes) - : base(rawAttributes, "CheckoutAttribute") - { - } } } \ No newline at end of file diff --git a/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeValue.cs b/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeValue.cs index e43d23254f..6eef840df4 100644 --- a/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeValue.cs +++ b/src/Smartstore.Core/Checkout/Attributes/Domain/CheckoutAttributeValue.cs @@ -9,13 +9,11 @@ namespace Smartstore.Core.Checkout.Attributes { internal class CheckoutAttributeValueMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(x => x.MediaFile) - .WithMany() - .HasForeignKey(x => x.MediaFileId) - .OnDelete(DeleteBehavior.SetNull); - } + .WithMany() + .HasForeignKey(x => x.MediaFileId) + .OnDelete(DeleteBehavior.SetNull); } /// diff --git a/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeFormatter.cs b/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeFormatter.cs index 57c196018e..f5bd85b50f 100644 --- a/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeFormatter.cs +++ b/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeFormatter.cs @@ -12,33 +12,22 @@ namespace Smartstore.Core.Checkout.Attributes { - public partial class CheckoutAttributeFormatter : ICheckoutAttributeFormatter + public partial class CheckoutAttributeFormatter( + ICheckoutAttributeMaterializer attributeMaterializer, + ICurrencyService currencyService, + IWorkContext workContext, + ITaxService taxService, + ITaxCalculator taxCalculator, + IWebHelper webHelper, + SmartDbContext db) : ICheckoutAttributeFormatter { - private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer; - private readonly ICurrencyService _currencyService; - private readonly ITaxService _taxService; - private readonly IWorkContext _workContext; - private readonly ITaxCalculator _taxCalculator; - private readonly IWebHelper _webHelper; - private readonly SmartDbContext _db; - - public CheckoutAttributeFormatter( - ICheckoutAttributeMaterializer attributeMaterializer, - ICurrencyService currencyService, - IWorkContext workContext, - ITaxService taxService, - ITaxCalculator taxCalculator, - IWebHelper webHelper, - SmartDbContext db) - { - _checkoutAttributeMaterializer = attributeMaterializer; - _currencyService = currencyService; - _workContext = workContext; - _taxService = taxService; - _taxCalculator = taxCalculator; - _webHelper = webHelper; - _db = db; - } + private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer = attributeMaterializer; + private readonly ICurrencyService _currencyService = currencyService; + private readonly ITaxService _taxService = taxService; + private readonly IWorkContext _workContext = workContext; + private readonly ITaxCalculator _taxCalculator = taxCalculator; + private readonly IWebHelper _webHelper = webHelper; + private readonly SmartDbContext _db = db; public async Task FormatAttributesAsync( CheckoutAttributeSelection selection, diff --git a/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeMaterializer.cs b/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeMaterializer.cs index 6599ae10e8..55aaa517c9 100644 --- a/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeMaterializer.cs +++ b/src/Smartstore.Core/Checkout/Attributes/Services/CheckoutAttributeMaterializer.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Checkout.Attributes { - public partial class CheckoutAttributeMaterializer : ICheckoutAttributeMaterializer + public partial class CheckoutAttributeMaterializer(SmartDbContext db) : ICheckoutAttributeMaterializer { - private readonly SmartDbContext _db; - - public CheckoutAttributeMaterializer(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task> MaterializeCheckoutAttributesAsync(CheckoutAttributeSelection selection) { diff --git a/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutBootstrappingExtensions.cs b/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutBootstrappingExtensions.cs index eaab2b7aa5..e7b54509ed 100644 --- a/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutBootstrappingExtensions.cs +++ b/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutBootstrappingExtensions.cs @@ -11,9 +11,8 @@ public static class CheckoutBootstrappingExtensions /// data is committed (but only if state was loaded and changed during the request). /// Should be registered right after the session middleware. /// - public static IApplicationBuilder UseCheckoutState(this IApplicationBuilder app) - { - return app.Use(async (context, next) => + public static IApplicationBuilder UseCheckoutState(this IApplicationBuilder app) => + app.Use(async (context, next) => { var accessor = context.RequestServices.GetService(); @@ -29,6 +28,6 @@ public static IApplicationBuilder UseCheckoutState(this IApplicationBuilder app) } } }); - } + } } diff --git a/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutStarter.cs b/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutStarter.cs index e7c978773c..52665e4a6d 100644 --- a/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutStarter.cs +++ b/src/Smartstore.Core/Checkout/Bootstrapping/CheckoutStarter.cs @@ -105,6 +105,7 @@ private static void DiscoverCheckoutHandlers(ContainerBuilder builder, IApplicat builder.Register>(c => { var cc = c.Resolve(); + return key => cc.ResolveKeyed(key); }); } diff --git a/src/Smartstore.Core/Checkout/Cart/Consumers/ValidatingCartEventConsumer.cs b/src/Smartstore.Core/Checkout/Cart/Consumers/ValidatingCartEventConsumer.cs index b82b6ec308..02bccd8b9f 100644 --- a/src/Smartstore.Core/Checkout/Cart/Consumers/ValidatingCartEventConsumer.cs +++ b/src/Smartstore.Core/Checkout/Cart/Consumers/ValidatingCartEventConsumer.cs @@ -6,24 +6,16 @@ namespace Smartstore.Core.Checkout.Cart { - internal class ValidatingCartEventConsumer : IConsumer + internal class ValidatingCartEventConsumer( + IOrderProcessingService orderProcessingService, + ILocalizationService localizationService, + ICurrencyService currencyService, + IWorkContext workContext) : IConsumer { - private readonly IOrderProcessingService _orderProcessingService; - private readonly ILocalizationService _localizationService; - private readonly ICurrencyService _currencyService; - private readonly IWorkContext _workContext; - - public ValidatingCartEventConsumer( - IOrderProcessingService orderProcessingService, - ILocalizationService localizationService, - ICurrencyService currencyService, - IWorkContext workContext) - { - _orderProcessingService = orderProcessingService; - _localizationService = localizationService; - _currencyService = currencyService; - _workContext = workContext; - } + private readonly IOrderProcessingService _orderProcessingService = orderProcessingService; + private readonly ILocalizationService _localizationService = localizationService; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IWorkContext _workContext = workContext; public async Task HandleEventAsync(ValidatingCartEvent message) { diff --git a/src/Smartstore.Core/Checkout/Cart/Domain/OrganizedShoppingCartItem.cs b/src/Smartstore.Core/Checkout/Cart/Domain/OrganizedShoppingCartItem.cs index 29220f1c64..4dfad68575 100644 --- a/src/Smartstore.Core/Checkout/Cart/Domain/OrganizedShoppingCartItem.cs +++ b/src/Smartstore.Core/Checkout/Cart/Domain/OrganizedShoppingCartItem.cs @@ -3,25 +3,22 @@ /// /// Represents an organized shopping cart item. /// - public partial class OrganizedShoppingCartItem : IEquatable + public partial class OrganizedShoppingCartItem( + ShoppingCartItem item, + bool? active = null) : IEquatable { - public OrganizedShoppingCartItem(ShoppingCartItem item, bool? active = null) - { - Item = Guard.NotNull(item); - Active = active ?? item.Active; - } /// /// Gets the shopping cart item. /// - public ShoppingCartItem Item { get; } + public ShoppingCartItem Item { get; } = Guard.NotNull(item); /// /// Gets a value indicating whether the cart item is active. /// May differ from and has precedence over it. /// Always true if is false. /// - public bool Active { get; } + public bool Active { get; } = active ?? item.Active; /// /// Gets or sets the list of child items. diff --git a/src/Smartstore.Core/Checkout/Cart/Extensions/ShoppingCartItemQueryExtensions.cs b/src/Smartstore.Core/Checkout/Cart/Extensions/ShoppingCartItemQueryExtensions.cs index effe8d6b96..15952ac87f 100644 --- a/src/Smartstore.Core/Checkout/Cart/Extensions/ShoppingCartItemQueryExtensions.cs +++ b/src/Smartstore.Core/Checkout/Cart/Extensions/ShoppingCartItemQueryExtensions.cs @@ -100,13 +100,10 @@ public static Task CountCartItemsAsync(this IQueryable qu /// of shopping cart items. /// A value indicating whether to only load active/inactive items. null to load all items. /// Sub total of all open wish lists. - public static Task GetOpenCartTypeSubTotalAsync(this IQueryable query, + public static Task GetOpenCartTypeSubTotalAsync(this IQueryable query, ShoppingCartType cartType = ShoppingCartType.ShoppingCart, - bool? active = null) - { - return query + bool? active = null) => query .Where(x => x.ShoppingCartTypeId == (int)cartType && x.Product != null && (active == null || x.Active == active.Value)) .SumAsync(x => (decimal?)(x.Product.Price * x.Quantity) ?? decimal.Zero); - } } } diff --git a/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartService.cs b/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartService.cs index ec69705f38..de2a9906d1 100644 --- a/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartService.cs +++ b/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartService.cs @@ -18,56 +18,38 @@ namespace Smartstore.Core.Checkout.Cart /// /// Shopping cart service methods. /// - public partial class ShoppingCartService : IShoppingCartService + public partial class ShoppingCartService( + SmartDbContext db, + IWorkContext workContext, + IStoreContext storeContext, + IRequestCache requestCache, + IEventPublisher eventPublisher, + IShoppingCartValidator cartValidator, + IRoundingHelper roundingHelper, + IProductAttributeMaterializer productAttributeMaterializer, + ICheckoutAttributeMaterializer checkoutAttributeMaterializer, + Lazy checkoutFactory, + ICurrencyService currencyService, + RewardPointsSettings rewardPointsSettings, + ShoppingCartSettings shoppingCartSettings) : IShoppingCartService { // 0 = CustomerId, 1 = CartType, 2 = StoreId, 3 = Active. const string CartItemsKey = "shoppingcartitems:{0}-{1}-{2}-{3}"; const string CartItemsPatternKey = "shoppingcartitems:*"; - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly IRequestCache _requestCache; - private readonly IEventPublisher _eventPublisher; - private readonly IShoppingCartValidator _cartValidator; - private readonly IRoundingHelper _roundingHelper; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer; - private readonly Lazy _checkoutFactory; - private readonly ShoppingCartSettings _shoppingCartSettings; - private readonly RewardPointsSettings _rewardPointsSettings; - private readonly Currency _primaryCurrency; - - public ShoppingCartService( - SmartDbContext db, - IWorkContext workContext, - IStoreContext storeContext, - IRequestCache requestCache, - IEventPublisher eventPublisher, - IShoppingCartValidator cartValidator, - IRoundingHelper roundingHelper, - IProductAttributeMaterializer productAttributeMaterializer, - ICheckoutAttributeMaterializer checkoutAttributeMaterializer, - Lazy checkoutFactory, - ICurrencyService currencyService, - RewardPointsSettings rewardPointsSettings, - ShoppingCartSettings shoppingCartSettings) - { - _db = db; - _workContext = workContext; - _storeContext = storeContext; - _requestCache = requestCache; - _eventPublisher = eventPublisher; - _cartValidator = cartValidator; - _roundingHelper = roundingHelper; - _productAttributeMaterializer = productAttributeMaterializer; - _checkoutAttributeMaterializer = checkoutAttributeMaterializer; - _checkoutFactory = checkoutFactory; - _rewardPointsSettings = rewardPointsSettings; - _shoppingCartSettings = shoppingCartSettings; - - _primaryCurrency = currencyService.PrimaryCurrency; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly IRequestCache _requestCache = requestCache; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly IShoppingCartValidator _cartValidator = cartValidator; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer = checkoutAttributeMaterializer; + private readonly Lazy _checkoutFactory = checkoutFactory; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; + private readonly RewardPointsSettings _rewardPointsSettings = rewardPointsSettings; + private readonly Currency _primaryCurrency = currencyService.PrimaryCurrency; public Localizer T { get; set; } = NullLocalizer.Instance; @@ -104,7 +86,7 @@ public virtual async Task AddToCartAsync(AddToCartContext ctx) // This is called when customer adds a product to cart ctx.Customer ??= _workContext.CurrentCustomer; ctx.StoreId ??= _storeContext.CurrentStore.Id; - + if (ctx.Customer.IsBot()) { ctx.Warnings.Add(T("Common.Error.BotsNotPermitted")); @@ -377,7 +359,7 @@ public virtual async Task DeleteCartAsync(ShoppingCart cart, bool resetChec public virtual Task GetCartAsync( Customer customer = null, - ShoppingCartType cartType = ShoppingCartType.ShoppingCart, + ShoppingCartType cartType = ShoppingCartType.ShoppingCart, int storeId = 0, bool? activeOnly = true) { @@ -494,9 +476,9 @@ public virtual async Task MigrateCartAsync(Customer fromCustomer, Customer } public virtual async Task> UpdateCartItemAsync( - Customer customer, + Customer customer, int cartItemId, - int? quantity, + int? quantity, bool? active, bool resetCheckoutData = false) { @@ -795,14 +777,13 @@ await AddItemToCartAsync(new() } } - private async Task LoadCartItemCollection(Customer customer, bool force = false) - { + private async Task LoadCartItemCollection(Customer customer, bool force = false) => await _db.LoadCollectionAsync(customer, x => x.ShoppingCartItems, force, x => { return x.Include(y => y.Product) .ThenInclude(y => y.ProductVariantAttributes); }); - } + private OrganizedShoppingCartItem CreateOrganizedCartItem(ShoppingCartItem item) => new(item, !_shoppingCartSettings.AllowActivatableCartItems || item.Active); diff --git a/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartValidator.cs b/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartValidator.cs index 83f3f0fe09..d5b20f4512 100644 --- a/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartValidator.cs +++ b/src/Smartstore.Core/Checkout/Cart/Services/ShoppingCartValidator.cs @@ -18,51 +18,34 @@ namespace Smartstore.Core.Checkout.Cart /// /// Shopping cart validation methods. /// - public partial class ShoppingCartValidator : IShoppingCartValidator + public partial class ShoppingCartValidator( + SmartDbContext db, + IAclService aclService, + IWorkContext workContext, + IStoreContext storeContext, + ICurrencyService currencyService, + ShoppingCartSettings cartSettings, + IPermissionService permissionService, + IStoreMappingService storeMappingService, + ILocalizationService localizationService, + IProductAttributeMaterializer productAttributeMaterializer, + ICheckoutAttributeMaterializer checkoutAttributeMaterializer, + IRuleProviderFactory ruleProviderFactory, + IEventPublisher eventPublisher) : IShoppingCartValidator { - private readonly SmartDbContext _db; - private readonly IAclService _aclService; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly ICurrencyService _currencyService; - private readonly ShoppingCartSettings _cartSettings; - private readonly IPermissionService _permissionService; - private readonly IStoreMappingService _storeMappingService; - private readonly ILocalizationService _localizationService; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer; - private readonly IRuleProviderFactory _ruleProviderFactory; - private readonly IEventPublisher _eventPublisher; - - public ShoppingCartValidator( - SmartDbContext db, - IAclService aclService, - IWorkContext workContext, - IStoreContext storeContext, - ICurrencyService currencyService, - ShoppingCartSettings cartSettings, - IPermissionService permissionService, - IStoreMappingService storeMappingService, - ILocalizationService localizationService, - IProductAttributeMaterializer productAttributeMaterializer, - ICheckoutAttributeMaterializer checkoutAttributeMaterializer, - IRuleProviderFactory ruleProviderFactory, - IEventPublisher eventPublisher) - { - _db = db; - _aclService = aclService; - _workContext = workContext; - _storeContext = storeContext; - _currencyService = currencyService; - _cartSettings = cartSettings; - _permissionService = permissionService; - _storeMappingService = storeMappingService; - _localizationService = localizationService; - _productAttributeMaterializer = productAttributeMaterializer; - _checkoutAttributeMaterializer = checkoutAttributeMaterializer; - _ruleProviderFactory = ruleProviderFactory; - _eventPublisher = eventPublisher; - } + private readonly SmartDbContext _db = db; + private readonly IAclService _aclService = aclService; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly ICurrencyService _currencyService = currencyService; + private readonly ShoppingCartSettings _cartSettings = cartSettings; + private readonly IPermissionService _permissionService = permissionService; + private readonly IStoreMappingService _storeMappingService = storeMappingService; + private readonly ILocalizationService _localizationService = localizationService; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer = checkoutAttributeMaterializer; + private readonly IRuleProviderFactory _ruleProviderFactory = ruleProviderFactory; + private readonly IEventPublisher _eventPublisher = eventPublisher; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCard.cs b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCard.cs index 72b13954e9..21deaf83c5 100644 --- a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCard.cs +++ b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCard.cs @@ -8,13 +8,11 @@ namespace Smartstore.Core.Checkout.GiftCards { internal class GiftCardMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(x => x.PurchasedWithOrderItem) - .WithMany(x => x.AssociatedGiftCards) - .HasForeignKey(x => x.PurchasedWithOrderItemId) - .OnDelete(DeleteBehavior.SetNull); - } + .WithMany(x => x.AssociatedGiftCards) + .HasForeignKey(x => x.PurchasedWithOrderItemId) + .OnDelete(DeleteBehavior.SetNull); } /// diff --git a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardCouponCodeConverter.cs b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardCouponCodeConverter.cs index 061fadc48b..99c6c7f135 100644 --- a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardCouponCodeConverter.cs +++ b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardCouponCodeConverter.cs @@ -132,14 +132,9 @@ public override object ConvertTo(CultureInfo culture, string format, object valu /// This class is needed for to explicitly define converter from /// to string and vice versa. /// - public class GiftCardCouponCode + public class GiftCardCouponCode(string value) { - public GiftCardCouponCode(string value) - { - Value = value; - } - - public string Value { get; init; } + public string Value { get; init; } = value; public static explicit operator string(GiftCardCouponCode code) => code.Value; public static explicit operator GiftCardCouponCode(string code) => new(code); diff --git a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardInfo.cs b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardInfo.cs index 453c11aef8..a9c1aa6406 100644 --- a/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardInfo.cs +++ b/src/Smartstore.Core/Checkout/GiftCards/Domain/GiftCardInfo.cs @@ -79,10 +79,7 @@ public override int GetHashCode() SenderEmail?.ToLower(), Message?.ToLower()); - public override bool Equals(object obj) - { - return Equals(obj as GiftCardInfo); - } + public override bool Equals(object obj) => Equals(obj as GiftCardInfo); protected virtual bool Equals(GiftCardInfo other) { diff --git a/src/Smartstore.Core/Checkout/GiftCards/Services/GiftCardService.cs b/src/Smartstore.Core/Checkout/GiftCards/Services/GiftCardService.cs index cd873cd04e..f809a2dd1a 100644 --- a/src/Smartstore.Core/Checkout/GiftCards/Services/GiftCardService.cs +++ b/src/Smartstore.Core/Checkout/GiftCards/Services/GiftCardService.cs @@ -6,16 +6,10 @@ namespace Smartstore.Core.Checkout.GiftCards { - public partial class GiftCardService : IGiftCardService + public partial class GiftCardService(SmartDbContext db, ICurrencyService currencyService) : IGiftCardService { - private readonly SmartDbContext _db; - private readonly Currency _primaryCurrency; - - public GiftCardService(SmartDbContext db, ICurrencyService currencyService) - { - _db = db; - _primaryCurrency = currencyService.PrimaryCurrency; - } + private readonly SmartDbContext _db = db; + private readonly Currency _primaryCurrency = currencyService.PrimaryCurrency; public virtual async Task> GetValidGiftCardsAsync(int storeId = 0, Customer customer = null) { diff --git a/src/Smartstore.Core/Checkout/Orders/Domain/CheckoutState.cs b/src/Smartstore.Core/Checkout/Orders/Domain/CheckoutState.cs index 47f3b9eef7..cd3cdd1915 100644 --- a/src/Smartstore.Core/Checkout/Orders/Domain/CheckoutState.cs +++ b/src/Smartstore.Core/Checkout/Orders/Domain/CheckoutState.cs @@ -78,10 +78,7 @@ public T GetCustomState(Func factory = null) /// The type of the custom state object to remove. /// true if the state object existed and was removed, false otherwise. public bool RemoveCustomState() - where T : ObservableObject - { - return CustomProperties.Remove(typeof(T).Name); - } + where T : ObservableObject => CustomProperties.Remove(typeof(T).Name); /// /// Use this dictionary for any custom data required along checkout flow diff --git a/src/Smartstore.Core/Checkout/Orders/Domain/OrderNote.cs b/src/Smartstore.Core/Checkout/Orders/Domain/OrderNote.cs index db7031ded1..0ad4b059ea 100644 --- a/src/Smartstore.Core/Checkout/Orders/Domain/OrderNote.cs +++ b/src/Smartstore.Core/Checkout/Orders/Domain/OrderNote.cs @@ -6,13 +6,11 @@ namespace Smartstore.Core.Checkout.Orders { internal class OrderNoteMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(x => x.Order) - .WithMany(x => x.OrderNotes) - .HasForeignKey(x => x.OrderId) - .OnDelete(DeleteBehavior.Cascade); - } + .WithMany(x => x.OrderNotes) + .HasForeignKey(x => x.OrderId) + .OnDelete(DeleteBehavior.Cascade); } /// diff --git a/src/Smartstore.Core/Checkout/Orders/Events/CreateAttachmentsConsumer.cs b/src/Smartstore.Core/Checkout/Orders/Events/CreateAttachmentsConsumer.cs index a91769b930..d0ab172344 100644 --- a/src/Smartstore.Core/Checkout/Orders/Events/CreateAttachmentsConsumer.cs +++ b/src/Smartstore.Core/Checkout/Orders/Events/CreateAttachmentsConsumer.cs @@ -7,16 +7,10 @@ namespace Smartstore.Core.Checkout.Orders.Events { - internal class CreateAttachmentsConsumer : IConsumer + internal class CreateAttachmentsConsumer(PdfInvoiceHttpClient client, PdfSettings pdfSettings) : IConsumer { - private readonly PdfInvoiceHttpClient _client; - private readonly PdfSettings _pdfSettings; - - public CreateAttachmentsConsumer(PdfInvoiceHttpClient client, PdfSettings pdfSettings) - { - _client = client; - _pdfSettings = pdfSettings; - } + private readonly PdfInvoiceHttpClient _client = client; + private readonly PdfSettings _pdfSettings = pdfSettings; public ILogger Logger { get; set; } = NullLogger.Instance; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Checkout/Orders/Events/OrderEvents.cs b/src/Smartstore.Core/Checkout/Orders/Events/OrderEvents.cs index 7473daa034..4527c6a856 100644 --- a/src/Smartstore.Core/Checkout/Orders/Events/OrderEvents.cs +++ b/src/Smartstore.Core/Checkout/Orders/Events/OrderEvents.cs @@ -1,32 +1,17 @@ namespace Smartstore.Core.Checkout.Orders.Events { - public class OrderPaidEvent + public class OrderPaidEvent(Order order) { - public OrderPaidEvent(Order order) - { - Order = Guard.NotNull(order); - } - - public Order Order { get; init; } + public Order Order { get; init; } = Guard.NotNull(order); } - public class OrderPlacedEvent + public class OrderPlacedEvent(Order order) { - public OrderPlacedEvent(Order order) - { - Order = Guard.NotNull(order); - } - - public Order Order { get; init; } + public Order Order { get; init; } = Guard.NotNull(order); } - public class OrderUpdatedEvent + public class OrderUpdatedEvent(Order order) { - public OrderUpdatedEvent(Order order) - { - Order = Guard.NotNull(order); - } - - public Order Order { get; init; } + public Order Order { get; init; } = Guard.NotNull(order); } } \ No newline at end of file diff --git a/src/Smartstore.Core/Checkout/Orders/Extensions/OrderEventPublisherExtensions.cs b/src/Smartstore.Core/Checkout/Orders/Extensions/OrderEventPublisherExtensions.cs index ae46689bc5..0c7ca08ffc 100644 --- a/src/Smartstore.Core/Checkout/Orders/Extensions/OrderEventPublisherExtensions.cs +++ b/src/Smartstore.Core/Checkout/Orders/Extensions/OrderEventPublisherExtensions.cs @@ -11,35 +11,33 @@ public static class OrderEventPublisherExtensions /// /// The event publisher. /// The order instance. - public static Task PublishOrderPaidAsync(this IEventPublisher eventPublisher, Order order) - { - return order != null + public static Task PublishOrderPaidAsync(this IEventPublisher eventPublisher, Order order) => + order != null ? eventPublisher.PublishAsync(new OrderPaidEvent(order)) : Task.CompletedTask; - } + /// /// Publishes the order placed event. /// /// The event publisher. /// The order instance. - public static Task PublishOrderPlacedAsync(this IEventPublisher eventPublisher, Order order) - { - return order != null + public static Task PublishOrderPlacedAsync(this IEventPublisher eventPublisher, Order order) => + + order != null ? eventPublisher.PublishAsync(new OrderPlacedEvent(order)) : Task.CompletedTask; - } + /// /// Publishes the order updated event. /// /// The event publisher. /// The order instance. - public static Task PublishOrderUpdatedAsync(this IEventPublisher eventPublisher, Order order) - { - return order != null + public static Task PublishOrderUpdatedAsync(this IEventPublisher eventPublisher, Order order) => + order != null ? eventPublisher.PublishAsync(new OrderUpdatedEvent(order)) : Task.CompletedTask; - } + } } \ No newline at end of file diff --git a/src/Smartstore.Core/Checkout/Orders/Hooks/OrderItemHook.cs b/src/Smartstore.Core/Checkout/Orders/Hooks/OrderItemHook.cs index 8c0fbc0412..c7b6d8544a 100644 --- a/src/Smartstore.Core/Checkout/Orders/Hooks/OrderItemHook.cs +++ b/src/Smartstore.Core/Checkout/Orders/Hooks/OrderItemHook.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Checkout.Orders { - internal class OrderItemHook : AsyncDbSaveHook + internal class OrderItemHook(SmartDbContext db, IEventPublisher eventPublisher) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IEventPublisher _eventPublisher; - - public OrderItemHook(SmartDbContext db, IEventPublisher eventPublisher) - { - _db = db; - _eventPublisher = eventPublisher; - } + private readonly SmartDbContext _db = db; + private readonly IEventPublisher _eventPublisher = eventPublisher; public override Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Checkout/Orders/Hooks/OrderNoteHook.cs b/src/Smartstore.Core/Checkout/Orders/Hooks/OrderNoteHook.cs index 0f7ca9dc5c..4139c5adcb 100644 --- a/src/Smartstore.Core/Checkout/Orders/Hooks/OrderNoteHook.cs +++ b/src/Smartstore.Core/Checkout/Orders/Hooks/OrderNoteHook.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Checkout.Orders { - internal class OrderNoteHook : AsyncDbSaveHook + internal class OrderNoteHook(SmartDbContext db, IEventPublisher eventPublisher) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IEventPublisher _eventPublisher; - - public OrderNoteHook(SmartDbContext db, IEventPublisher eventPublisher) - { - _db = db; - _eventPublisher = eventPublisher; - } + private readonly SmartDbContext _db = db; + private readonly IEventPublisher _eventPublisher = eventPublisher; public override Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Checkout/Orders/Hooks/ReturnRequestHook.cs b/src/Smartstore.Core/Checkout/Orders/Hooks/ReturnRequestHook.cs index 4455d101e6..f0f633f051 100644 --- a/src/Smartstore.Core/Checkout/Orders/Hooks/ReturnRequestHook.cs +++ b/src/Smartstore.Core/Checkout/Orders/Hooks/ReturnRequestHook.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Checkout.Orders { - internal class ReturnRequestHook : AsyncDbSaveHook + internal class ReturnRequestHook(SmartDbContext db, IEventPublisher eventPublisher) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IEventPublisher _eventPublisher; - - public ReturnRequestHook(SmartDbContext db, IEventPublisher eventPublisher) - { - _db = db; - _eventPublisher = eventPublisher; - } + private readonly SmartDbContext _db = db; + private readonly IEventPublisher _eventPublisher = eventPublisher; protected override Task OnDeletedAsync(ReturnRequest entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutFactory.cs b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutFactory.cs index fe6b888137..3929157425 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutFactory.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutFactory.cs @@ -54,10 +54,7 @@ public virtual CheckoutRequirements GetRequirements() return requirements; } - public virtual CheckoutStep[] GetCheckoutSteps() - { - return _handlers.Select(Convert).ToArray(); - } + public virtual CheckoutStep[] GetCheckoutSteps() => _handlers.Select(Convert).ToArray(); public virtual CheckoutStep GetCheckoutStep(string action, string controller = "Checkout", string area = null) { diff --git a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutResult.cs b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutResult.cs index 54040b3e89..be8bf64b98 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutResult.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutResult.cs @@ -4,20 +4,10 @@ namespace Smartstore.Core.Checkout.Orders { - public partial class CheckoutResult + public partial class CheckoutResult(bool success, CheckoutError[]? errors = null, bool skipPage = false) { - public CheckoutResult(bool success, CheckoutError[]? errors = null, bool skipPage = false) - { - Success = success; - Errors = errors ?? []; - SkipPage = skipPage; - } - public CheckoutResult(CheckoutError[] errors, string? viewPath = null, bool success = false) - : this(success, errors) - { - ViewPath = viewPath; - } + : this(success, errors) => ViewPath = viewPath; public CheckoutResult(IActionResult actionResult, string? viewPath = null) : this(false) @@ -31,19 +21,19 @@ public CheckoutResult(IActionResult actionResult, string? viewPath = null) /// If true, the next handler is called. Otherwise the customer is redirected to or /// the page belonging to current checkout step. /// - public bool Success { get; } + public bool Success { get; } = success; /// /// Gets a list of errors. Typically these are added to the model state by the caller /// to display them on current checkout page. /// - public CheckoutError[] Errors { get; } + public CheckoutError[] Errors { get; } = errors ?? []; /// /// Gets a value indicating whether the current checkout page should be skipped. /// Only applicable if was called. /// - public bool SkipPage { get; } + public bool SkipPage { get; } = skipPage; /// /// Gets an where the customer is to be redirected. diff --git a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutStep.cs b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutStep.cs index b00c725cf6..2ef81d6c11 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutStep.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutStep.cs @@ -44,6 +44,7 @@ public partial class CheckoutStep(CheckoutHandler handler, string? viewPath = nu Guard.NotNull(context); var md = Handler.Metadata; + return context.UrlHelper.Action(md.DefaultAction, md.Controller, md.Area.HasValue() ? new { area = md.Area } : null); } } diff --git a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutWorkflow.cs b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutWorkflow.cs index 200abb1965..d77ea1b55b 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/CheckoutWorkflow.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/CheckoutWorkflow.cs @@ -14,53 +14,36 @@ namespace Smartstore.Core.Checkout.Orders { - public partial class CheckoutWorkflow : ICheckoutWorkflow + public partial class CheckoutWorkflow( + SmartDbContext db, + IStoreContext storeContext, + INotifier notifier, + ILogger logger, + IWebHelper webHelper, + IEventPublisher eventPublisher, + IShoppingCartValidator shoppingCartValidator, + IOrderProcessingService orderProcessingService, + IPaymentService paymentService, + ICheckoutFactory checkoutFactory, + ICheckoutStateAccessor checkoutStateAccessor, + OrderSettings orderSettings, + ShoppingCartSettings shoppingCartSettings) : ICheckoutWorkflow { const int _maxWarnings = 3; - private readonly SmartDbContext _db; - private readonly IStoreContext _storeContext; - private readonly INotifier _notifier; - private readonly ILogger _logger; - private readonly IWebHelper _webHelper; - private readonly IEventPublisher _eventPublisher; - private readonly IShoppingCartValidator _shoppingCartValidator; - private readonly IOrderProcessingService _orderProcessingService; - private readonly IPaymentService _paymentService; - private readonly ICheckoutFactory _checkoutFactory; - private readonly ICheckoutStateAccessor _checkoutStateAccessor; - private readonly OrderSettings _orderSettings; - private readonly ShoppingCartSettings _shoppingCartSettings; - - public CheckoutWorkflow( - SmartDbContext db, - IStoreContext storeContext, - INotifier notifier, - ILogger logger, - IWebHelper webHelper, - IEventPublisher eventPublisher, - IShoppingCartValidator shoppingCartValidator, - IOrderProcessingService orderProcessingService, - IPaymentService paymentService, - ICheckoutFactory checkoutFactory, - ICheckoutStateAccessor checkoutStateAccessor, - OrderSettings orderSettings, - ShoppingCartSettings shoppingCartSettings) - { - _db = db; - _storeContext = storeContext; - _notifier = notifier; - _logger = logger; - _webHelper = webHelper; - _eventPublisher = eventPublisher; - _shoppingCartValidator = shoppingCartValidator; - _orderProcessingService = orderProcessingService; - _paymentService = paymentService; - _checkoutFactory = checkoutFactory; - _checkoutStateAccessor = checkoutStateAccessor; - _orderSettings = orderSettings; - _shoppingCartSettings = shoppingCartSettings; - } + private readonly SmartDbContext _db = db; + private readonly IStoreContext _storeContext = storeContext; + private readonly INotifier _notifier = notifier; + private readonly ILogger _logger = logger; + private readonly IWebHelper _webHelper = webHelper; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly IShoppingCartValidator _shoppingCartValidator = shoppingCartValidator; + private readonly IOrderProcessingService _orderProcessingService = orderProcessingService; + private readonly IPaymentService _paymentService = paymentService; + private readonly ICheckoutFactory _checkoutFactory = checkoutFactory; + private readonly ICheckoutStateAccessor _checkoutStateAccessor = checkoutStateAccessor; + private readonly OrderSettings _orderSettings = orderSettings; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Checkout/Orders/Services/DefaultCheckoutStateAccessor.cs b/src/Smartstore.Core/Checkout/Orders/Services/DefaultCheckoutStateAccessor.cs index 09c0f6dade..da42de5d35 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/DefaultCheckoutStateAccessor.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/DefaultCheckoutStateAccessor.cs @@ -4,19 +4,14 @@ namespace Smartstore.Core.Checkout.Orders { - public class DefaultCheckoutStateAccessor : ICheckoutStateAccessor + public class DefaultCheckoutStateAccessor(IHttpContextAccessor httpContextAccessor) : ICheckoutStateAccessor { const string CheckoutStateSessionKey = ".Smart.CheckoutState"; private CheckoutState _state; private bool _dirty; - private readonly IHttpContextAccessor _httpContextAccessor; - - public DefaultCheckoutStateAccessor(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/BillingAddressHandler.cs b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/BillingAddressHandler.cs index 88fc888bfd..51e3f8b109 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/BillingAddressHandler.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/BillingAddressHandler.cs @@ -6,21 +6,14 @@ namespace Smartstore.Core.Checkout.Orders.Handlers { [CheckoutStep(10, CheckoutActionNames.BillingAddress, CheckoutActionNames.SelectBillingAddress)] - public class BillingAddressHandler : ICheckoutHandler + public class BillingAddressHandler( + SmartDbContext db, + ICheckoutStateAccessor checkoutStateAccessor, + ShoppingCartSettings shoppingCartSettings) : ICheckoutHandler { - private readonly SmartDbContext _db; - private readonly ICheckoutStateAccessor _checkoutStateAccessor; - private readonly ShoppingCartSettings _shoppingCartSettings; - - public BillingAddressHandler( - SmartDbContext db, - ICheckoutStateAccessor checkoutStateAccessor, - ShoppingCartSettings shoppingCartSettings) - { - _db = db; - _checkoutStateAccessor = checkoutStateAccessor; - _shoppingCartSettings = shoppingCartSettings; - } + private readonly SmartDbContext _db = db; + private readonly ICheckoutStateAccessor _checkoutStateAccessor = checkoutStateAccessor; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; public async Task ProcessAsync(CheckoutContext context) { diff --git a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/PaymentMethodHandler.cs b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/PaymentMethodHandler.cs index d052321a36..94af09bdca 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/PaymentMethodHandler.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/PaymentMethodHandler.cs @@ -8,30 +8,20 @@ namespace Smartstore.Core.Checkout.Orders.Handlers { [CheckoutStep(40, CheckoutActionNames.PaymentMethod)] - public class PaymentMethodHandler : ICheckoutHandler + public class PaymentMethodHandler( + SmartDbContext db, + IPaymentService paymentService, + IOrderCalculationService orderCalculationService, + ICheckoutStateAccessor checkoutStateAccessor, + PaymentSettings paymentSettings, + ShoppingCartSettings shoppingCartSettings) : ICheckoutHandler { - private readonly SmartDbContext _db; - private readonly IPaymentService _paymentService; - private readonly IOrderCalculationService _orderCalculationService; - private readonly ICheckoutStateAccessor _checkoutStateAccessor; - private readonly PaymentSettings _paymentSettings; - private readonly ShoppingCartSettings _shoppingCartSettings; - - public PaymentMethodHandler( - SmartDbContext db, - IPaymentService paymentService, - IOrderCalculationService orderCalculationService, - ICheckoutStateAccessor checkoutStateAccessor, - PaymentSettings paymentSettings, - ShoppingCartSettings shoppingCartSettings) - { - _db = db; - _paymentService = paymentService; - _orderCalculationService = orderCalculationService; - _checkoutStateAccessor = checkoutStateAccessor; - _paymentSettings = paymentSettings; - _shoppingCartSettings = shoppingCartSettings; - } + private readonly SmartDbContext _db = db; + private readonly IPaymentService _paymentService = paymentService; + private readonly IOrderCalculationService _orderCalculationService = orderCalculationService; + private readonly ICheckoutStateAccessor _checkoutStateAccessor = checkoutStateAccessor; + private readonly PaymentSettings _paymentSettings = paymentSettings; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; public async Task ProcessAsync(CheckoutContext context) { diff --git a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingAddressHandler.cs b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingAddressHandler.cs index e406718139..d2bfd1f68f 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingAddressHandler.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingAddressHandler.cs @@ -6,21 +6,14 @@ namespace Smartstore.Core.Checkout.Orders.Handlers { [CheckoutStep(20, CheckoutActionNames.ShippingAddress, CheckoutActionNames.SelectShippingAddress)] - public class ShippingAddressHandler : ICheckoutHandler + public class ShippingAddressHandler( + SmartDbContext db, + ICheckoutStateAccessor checkoutStateAccessor, + ShoppingCartSettings shoppingCartSettings) : ICheckoutHandler { - private readonly SmartDbContext _db; - private readonly ICheckoutStateAccessor _checkoutStateAccessor; - private readonly ShoppingCartSettings _shoppingCartSettings; - - public ShippingAddressHandler( - SmartDbContext db, - ICheckoutStateAccessor checkoutStateAccessor, - ShoppingCartSettings shoppingCartSettings) - { - _db = db; - _checkoutStateAccessor = checkoutStateAccessor; - _shoppingCartSettings = shoppingCartSettings; - } + private readonly SmartDbContext _db = db; + private readonly ICheckoutStateAccessor _checkoutStateAccessor = checkoutStateAccessor; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; public async Task ProcessAsync(CheckoutContext context) { diff --git a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingMethodHandler.cs b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingMethodHandler.cs index b0c4d843ad..3a592f2697 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingMethodHandler.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/Handlers/ShippingMethodHandler.cs @@ -6,21 +6,14 @@ namespace Smartstore.Core.Checkout.Orders.Handlers { [CheckoutStep(30, CheckoutActionNames.ShippingMethod)] - public class ShippingMethodHandler : ICheckoutHandler + public class ShippingMethodHandler( + IShippingService shippingService, + ShippingSettings shippingSettings, + ShoppingCartSettings shoppingCartSettings) : ICheckoutHandler { - private readonly IShippingService _shippingService; - private readonly ShippingSettings _shippingSettings; - private readonly ShoppingCartSettings _shoppingCartSettings; - - public ShippingMethodHandler( - IShippingService shippingService, - ShippingSettings shippingSettings, - ShoppingCartSettings shoppingCartSettings) - { - _shippingService = shippingService; - _shippingSettings = shippingSettings; - _shoppingCartSettings = shoppingCartSettings; - } + private readonly IShippingService _shippingService = shippingService; + private readonly ShippingSettings _shippingSettings = shippingSettings; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; public async Task ProcessAsync(CheckoutContext context) { diff --git a/src/Smartstore.Core/Checkout/Orders/Services/OrderCalculationService.cs b/src/Smartstore.Core/Checkout/Orders/Services/OrderCalculationService.cs index fa06908770..bee5e1bc29 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/OrderCalculationService.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/OrderCalculationService.cs @@ -19,76 +19,50 @@ namespace Smartstore.Core.Checkout.Orders { - public partial class OrderCalculationService : IOrderCalculationService + public partial class OrderCalculationService( + SmartDbContext db, + IPriceCalculationService priceCalculationService, + IProductService productService, + IDiscountService discountService, + IShippingService shippingService, + IGiftCardService giftCardService, + ICurrencyService currencyService, + IRoundingHelper roundingHelper, + IRequestCache requestCache, + IProviderManager providerManager, + ICheckoutAttributeMaterializer checkoutAttributeMaterializer, + IWorkContext workContext, + IStoreContext storeContext, + ITaxService taxService, + ITaxCalculator taxCalculator, + TaxSettings taxSettings, + RewardPointsSettings rewardPointsSettings, + PriceSettings priceSettings, + ShippingSettings shippingSettings) : IOrderCalculationService { const string CartTaxingInfoKey = "CartTaxingInfos"; - private readonly SmartDbContext _db; - private readonly IPriceCalculationService _priceCalculationService; - private readonly IProductService _productService; - private readonly IDiscountService _discountService; - private readonly IShippingService _shippingService; - private readonly IGiftCardService _giftCardService; - private readonly ICurrencyService _currencyService; - private readonly IRoundingHelper _roundingHelper; - private readonly IRequestCache _requestCache; - private readonly IProviderManager _providerManager; - private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly ITaxService _taxService; - private readonly ITaxCalculator _taxCalculator; - private readonly TaxSettings _taxSettings; - private readonly RewardPointsSettings _rewardPointsSettings; - private readonly PriceSettings _priceSettings; - private readonly ShippingSettings _shippingSettings; - private readonly Currency _primaryCurrency; - private readonly Currency _workingCurrency; - - public OrderCalculationService( - SmartDbContext db, - IPriceCalculationService priceCalculationService, - IProductService productService, - IDiscountService discountService, - IShippingService shippingService, - IGiftCardService giftCardService, - ICurrencyService currencyService, - IRoundingHelper roundingHelper, - IRequestCache requestCache, - IProviderManager providerManager, - ICheckoutAttributeMaterializer checkoutAttributeMaterializer, - IWorkContext workContext, - IStoreContext storeContext, - ITaxService taxService, - ITaxCalculator taxCalculator, - TaxSettings taxSettings, - RewardPointsSettings rewardPointsSettings, - PriceSettings priceSettings, - ShippingSettings shippingSettings) - { - _db = db; - _priceCalculationService = priceCalculationService; - _productService = productService; - _discountService = discountService; - _shippingService = shippingService; - _giftCardService = giftCardService; - _currencyService = currencyService; - _roundingHelper = roundingHelper; - _requestCache = requestCache; - _providerManager = providerManager; - _checkoutAttributeMaterializer = checkoutAttributeMaterializer; - _workContext = workContext; - _storeContext = storeContext; - _taxService = taxService; - _taxCalculator = taxCalculator; - _taxSettings = taxSettings; - _rewardPointsSettings = rewardPointsSettings; - _priceSettings = priceSettings; - _shippingSettings = shippingSettings; - - _primaryCurrency = currencyService.PrimaryCurrency; - _workingCurrency = workContext.WorkingCurrency; - } + private readonly SmartDbContext _db = db; + private readonly IPriceCalculationService _priceCalculationService = priceCalculationService; + private readonly IProductService _productService = productService; + private readonly IDiscountService _discountService = discountService; + private readonly IShippingService _shippingService = shippingService; + private readonly IGiftCardService _giftCardService = giftCardService; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IRequestCache _requestCache = requestCache; + private readonly IProviderManager _providerManager = providerManager; + private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer = checkoutAttributeMaterializer; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly ITaxService _taxService = taxService; + private readonly ITaxCalculator _taxCalculator = taxCalculator; + private readonly TaxSettings _taxSettings = taxSettings; + private readonly RewardPointsSettings _rewardPointsSettings = rewardPointsSettings; + private readonly PriceSettings _priceSettings = priceSettings; + private readonly ShippingSettings _shippingSettings = shippingSettings; + private readonly Currency _primaryCurrency = currencyService.PrimaryCurrency; + private readonly Currency _workingCurrency = workContext.WorkingCurrency; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Checkout/Orders/Services/OrderProcessingService.cs b/src/Smartstore.Core/Checkout/Orders/Services/OrderProcessingService.cs index bbd11e4da9..bf37d0b734 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/OrderProcessingService.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/OrderProcessingService.cs @@ -23,107 +23,70 @@ namespace Smartstore.Core.Checkout.Orders { - public partial class OrderProcessingService : IOrderProcessingService + public partial class OrderProcessingService( + SmartDbContext db, + IWorkContext workContext, + IWebHelper webHelper, + ILocalizationService localizationService, + ICurrencyService currencyService, + IRoundingHelper roundingHelper, + IPaymentService paymentService, + IProductService productService, + IProductAttributeMaterializer productAttributeMaterializer, + IProductAttributeFormatter productAttributeFormatter, + IPriceCalculationService priceCalculationService, + IOrderCalculationService orderCalculationService, + ITaxCalculator taxCalculator, + IShoppingCartService shoppingCartService, + IShoppingCartValidator shoppingCartValidator, + IShippingService shippingService, + IGiftCardService giftCardService, + INewsletterSubscriptionService newsletterSubscriptionService, + ICheckoutAttributeFormatter checkoutAttributeFormatter, + IEncryptor encryptor, + IMessageFactory messageFactory, + IEventPublisher eventPublisher, + IActivityLogger activityLogger, + RewardPointsSettings rewardPointsSettings, + CatalogSettings catalogSettings, + OrderSettings orderSettings, + ShoppingCartSettings shoppingCartSettings, + LocalizationSettings localizationSettings, + TaxSettings taxSettings, + PaymentSettings paymentSettings) : IOrderProcessingService { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IWebHelper _webHelper; - private readonly ILocalizationService _localizationService; - private readonly ICurrencyService _currencyService; - private readonly IRoundingHelper _roundingHelper; - private readonly IPaymentService _paymentService; - private readonly IProductService _productService; - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly IProductAttributeFormatter _productAttributeFormatter; - private readonly IPriceCalculationService _priceCalculationService; - private readonly IOrderCalculationService _orderCalculationService; - private readonly ITaxCalculator _taxCalculator; - private readonly IShoppingCartService _shoppingCartService; - private readonly IShoppingCartValidator _shoppingCartValidator; - private readonly IShippingService _shippingService; - private readonly IGiftCardService _giftCardService; - private readonly INewsletterSubscriptionService _newsletterSubscriptionService; - private readonly ICheckoutAttributeFormatter _checkoutAttributeFormatter; - private readonly IEncryptor _encryptor; - private readonly IMessageFactory _messageFactory; - private readonly IEventPublisher _eventPublisher; - private readonly IActivityLogger _activityLogger; - private readonly RewardPointsSettings _rewardPointsSettings; - private readonly CatalogSettings _catalogSettings; - private readonly OrderSettings _orderSettings; - private readonly ShoppingCartSettings _shoppingCartSettings; - private readonly LocalizationSettings _localizationSettings; - private readonly TaxSettings _taxSettings; - private readonly PaymentSettings _paymentSettings; - private readonly Currency _primaryCurrency; - private readonly Currency _workingCurrency; - - public OrderProcessingService( - SmartDbContext db, - IWorkContext workContext, - IWebHelper webHelper, - ILocalizationService localizationService, - ICurrencyService currencyService, - IRoundingHelper roundingHelper, - IPaymentService paymentService, - IProductService productService, - IProductAttributeMaterializer productAttributeMaterializer, - IProductAttributeFormatter productAttributeFormatter, - IPriceCalculationService priceCalculationService, - IOrderCalculationService orderCalculationService, - ITaxCalculator taxCalculator, - IShoppingCartService shoppingCartService, - IShoppingCartValidator shoppingCartValidator, - IShippingService shippingService, - IGiftCardService giftCardService, - INewsletterSubscriptionService newsletterSubscriptionService, - ICheckoutAttributeFormatter checkoutAttributeFormatter, - IEncryptor encryptor, - IMessageFactory messageFactory, - IEventPublisher eventPublisher, - IActivityLogger activityLogger, - RewardPointsSettings rewardPointsSettings, - CatalogSettings catalogSettings, - OrderSettings orderSettings, - ShoppingCartSettings shoppingCartSettings, - LocalizationSettings localizationSettings, - TaxSettings taxSettings, - PaymentSettings paymentSettings) - { - _db = db; - _workContext = workContext; - _webHelper = webHelper; - _localizationService = localizationService; - _currencyService = currencyService; - _roundingHelper = roundingHelper; - _paymentService = paymentService; - _productService = productService; - _productAttributeMaterializer = productAttributeMaterializer; - _productAttributeFormatter = productAttributeFormatter; - _priceCalculationService = priceCalculationService; - _orderCalculationService = orderCalculationService; - _taxCalculator = taxCalculator; - _shoppingCartService = shoppingCartService; - _shoppingCartValidator = shoppingCartValidator; - _shippingService = shippingService; - _giftCardService = giftCardService; - _newsletterSubscriptionService = newsletterSubscriptionService; - _checkoutAttributeFormatter = checkoutAttributeFormatter; - _encryptor = encryptor; - _messageFactory = messageFactory; - _eventPublisher = eventPublisher; - _activityLogger = activityLogger; - _rewardPointsSettings = rewardPointsSettings; - _catalogSettings = catalogSettings; - _orderSettings = orderSettings; - _shoppingCartSettings = shoppingCartSettings; - _localizationSettings = localizationSettings; - _taxSettings = taxSettings; - _paymentSettings = paymentSettings; - - _primaryCurrency = currencyService.PrimaryCurrency; - _workingCurrency = workContext.WorkingCurrency; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IWebHelper _webHelper = webHelper; + private readonly ILocalizationService _localizationService = localizationService; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IPaymentService _paymentService = paymentService; + private readonly IProductService _productService = productService; + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly IProductAttributeFormatter _productAttributeFormatter = productAttributeFormatter; + private readonly IPriceCalculationService _priceCalculationService = priceCalculationService; + private readonly IOrderCalculationService _orderCalculationService = orderCalculationService; + private readonly ITaxCalculator _taxCalculator = taxCalculator; + private readonly IShoppingCartService _shoppingCartService = shoppingCartService; + private readonly IShoppingCartValidator _shoppingCartValidator = shoppingCartValidator; + private readonly IShippingService _shippingService = shippingService; + private readonly IGiftCardService _giftCardService = giftCardService; + private readonly INewsletterSubscriptionService _newsletterSubscriptionService = newsletterSubscriptionService; + private readonly ICheckoutAttributeFormatter _checkoutAttributeFormatter = checkoutAttributeFormatter; + private readonly IEncryptor _encryptor = encryptor; + private readonly IMessageFactory _messageFactory = messageFactory; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly IActivityLogger _activityLogger = activityLogger; + private readonly RewardPointsSettings _rewardPointsSettings = rewardPointsSettings; + private readonly CatalogSettings _catalogSettings = catalogSettings; + private readonly OrderSettings _orderSettings = orderSettings; + private readonly ShoppingCartSettings _shoppingCartSettings = shoppingCartSettings; + private readonly LocalizationSettings _localizationSettings = localizationSettings; + private readonly TaxSettings _taxSettings = taxSettings; + private readonly PaymentSettings _paymentSettings = paymentSettings; + private readonly Currency _primaryCurrency = currencyService.PrimaryCurrency; + private readonly Currency _workingCurrency = workContext.WorkingCurrency; public Localizer T { get; set; } = NullLocalizer.Instance; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Checkout/Orders/Services/OrderService.cs b/src/Smartstore.Core/Checkout/Orders/Services/OrderService.cs index a3ec5b95ce..875a24c2ac 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/OrderService.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/OrderService.cs @@ -8,32 +8,22 @@ namespace Smartstore.Core.Checkout.Orders { - public partial class OrderService : AsyncDbSaveHook, IOrderService + public partial class OrderService( + SmartDbContext db, + IWorkContext workContext, + Lazy orderProcessingService, + IRoundingHelper roundingHelper, + IEventPublisher eventPublisher, + PaymentSettings paymentSettings) : AsyncDbSaveHook, IOrderService { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly Lazy _orderProcessingService; - private readonly IRoundingHelper _roundingHelper; - private readonly IEventPublisher _eventPublisher; - private readonly PaymentSettings _paymentSettings; + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly Lazy _orderProcessingService = orderProcessingService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly PaymentSettings _paymentSettings = paymentSettings; private readonly HashSet _toCapture = new(); - public OrderService( - SmartDbContext db, - IWorkContext workContext, - Lazy orderProcessingService, - IRoundingHelper roundingHelper, - IEventPublisher eventPublisher, - PaymentSettings paymentSettings) - { - _db = db; - _workContext = workContext; - _orderProcessingService = orderProcessingService; - _roundingHelper = roundingHelper; - _eventPublisher = eventPublisher; - _paymentSettings = paymentSettings; - } - public ILogger Logger { get; set; } = NullLogger.Instance; #region Hook diff --git a/src/Smartstore.Core/Checkout/Orders/Services/PdfInvoiceHttpClient.cs b/src/Smartstore.Core/Checkout/Orders/Services/PdfInvoiceHttpClient.cs index 951561d7ad..e9e955c93b 100644 --- a/src/Smartstore.Core/Checkout/Orders/Services/PdfInvoiceHttpClient.cs +++ b/src/Smartstore.Core/Checkout/Orders/Services/PdfInvoiceHttpClient.cs @@ -12,19 +12,12 @@ public class PdfInvoiceResult public string FileName { get; init; } } - public class PdfInvoiceHttpClient + public class PdfInvoiceHttpClient(HttpClient httpClient, IUrlHelper urlHelper, Localizer localizer) { - private readonly HttpClient _httpClient; - private readonly IUrlHelper _urlHelper; + private readonly HttpClient _httpClient = httpClient; + private readonly IUrlHelper _urlHelper = urlHelper; - public PdfInvoiceHttpClient(HttpClient httpClient, IUrlHelper urlHelper, Localizer localizer) - { - _httpClient = httpClient; - _urlHelper = urlHelper; - T = localizer; - } - - public Localizer T { get; set; } = NullLocalizer.Instance; + public Localizer T { get; set; } = localizer; public async Task GetPdfInvoiceAsync(int orderId, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentException.cs b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentException.cs index a4eb4babf7..245a1dd1b0 100644 --- a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentException.cs +++ b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentException.cs @@ -28,10 +28,7 @@ public PaymentException(string? message) /// The message that describes the error. /// Payment provider that caused the exception. public PaymentException(string? message, string? provider) - : base(message) - { - Provider = provider; - } + : base(message) => Provider = provider; /// /// Initializes a new instance of the class. @@ -40,10 +37,7 @@ public PaymentException(string? message, string? provider) /// The exception that is the cause of the current exception. /// Payment provider that caused the exception. public PaymentException(string? message, Exception? innerException, string? provider) - : base(message, innerException) - { - Provider = provider; - } + : base(message, innerException) => Provider = provider; /// /// Initializes a new instance of the class. diff --git a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentMethod.cs b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentMethod.cs index b41dc9938a..293bc4a1c9 100644 --- a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentMethod.cs +++ b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentMethod.cs @@ -11,8 +11,7 @@ namespace Smartstore.Core.Checkout.Payment { internal class PaymentMethodMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder)=> builder .HasMany(c => c.RuleSets) .WithMany(c => c.PaymentMethods) @@ -35,7 +34,7 @@ public void Configure(EntityTypeBuilder builder) c.HasIndex("PaymentMethod_Id"); c.HasKey("PaymentMethod_Id", "RuleSetEntity_Id"); }); - } + } /// diff --git a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentResponse.cs b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentResponse.cs index 6e8f859b90..e68cd6b9db 100644 --- a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentResponse.cs +++ b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentResponse.cs @@ -2,9 +2,9 @@ namespace Smartstore.Core.Checkout.Payment { - public class PaymentResponse + public class PaymentResponse(HttpStatusCode status, IDictionary headers, object body) { - private readonly object _body; + private readonly object _body = body; public PaymentResponse(HttpStatusCode status) : this(status, null, null) @@ -16,16 +16,9 @@ public PaymentResponse(HttpStatusCode status, IDictionary header { } - public PaymentResponse(HttpStatusCode status, IDictionary headers, object body) - { - Headers = headers; - Status = status; - _body = body; - } - - public HttpStatusCode Status { get; } + public HttpStatusCode Status { get; } = status; - public IDictionary Headers { get; } + public IDictionary Headers { get; } = headers; public bool HasBody => _body != null; diff --git a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentValidationResult.cs b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentValidationResult.cs index 8570d1c848..8b28d7282f 100644 --- a/src/Smartstore.Core/Checkout/Payment/Domain/PaymentValidationResult.cs +++ b/src/Smartstore.Core/Checkout/Payment/Domain/PaymentValidationResult.cs @@ -29,10 +29,7 @@ public PaymentValidationResult(ValidationResult result) /// /// Whether validation succeeded /// - public bool IsValid - { - get => _errors == null || _errors.Count == 0; - } + public bool IsValid => _errors == null || _errors.Count == 0; /// /// A collection of errors @@ -65,10 +62,7 @@ public void AddToModelState(ModelStateDictionary modelState) /// /// Generates a string representation of the error messages separated by new lines. /// - public override string ToString() - { - return ToString(Environment.NewLine); - } + public override string ToString() => ToString(Environment.NewLine); /// /// Generates a string representation of the error messages separated by the specified character. diff --git a/src/Smartstore.Core/Checkout/Payment/Domain/RecurringPaymentHistory.cs b/src/Smartstore.Core/Checkout/Payment/Domain/RecurringPaymentHistory.cs index cb4e0b2876..20a2b4d0c6 100644 --- a/src/Smartstore.Core/Checkout/Payment/Domain/RecurringPaymentHistory.cs +++ b/src/Smartstore.Core/Checkout/Payment/Domain/RecurringPaymentHistory.cs @@ -5,18 +5,11 @@ namespace Smartstore.Core.Checkout.Payment { internal class RecurringPaymentHistoryMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(x => x.RecurringPayment) - .WithMany(x => x.RecurringPaymentHistory) - .HasForeignKey(x => x.RecurringPaymentId) - .OnDelete(DeleteBehavior.Cascade); - - // Entity framework issue if we have navigation property to 'Order'. - // 1. save recurring payment with an order - // 2. save recurring payment history with an order - // 3. update associated order => exception is thrown - } + .WithMany(x => x.RecurringPaymentHistory) + .HasForeignKey(x => x.RecurringPaymentId) + .OnDelete(DeleteBehavior.Cascade);// Entity framework issue if we have navigation property to 'Order'.// 1. save recurring payment with an order// 2. save recurring payment history with an order// 3. update associated order => exception is thrown } /// diff --git a/src/Smartstore.Core/Checkout/Payment/Extensions/PaymentMessageFactoryExtensions.cs b/src/Smartstore.Core/Checkout/Payment/Extensions/PaymentMessageFactoryExtensions.cs index 4d5b320b9e..9b0630bcc2 100644 --- a/src/Smartstore.Core/Checkout/Payment/Extensions/PaymentMessageFactoryExtensions.cs +++ b/src/Smartstore.Core/Checkout/Payment/Extensions/PaymentMessageFactoryExtensions.cs @@ -12,6 +12,7 @@ public static Task SendRecurringPaymentCancelledStoreOwnerN Guard.NotNull(recurringPayment, nameof(recurringPayment)); var order = recurringPayment.InitialOrder; + return factory.CreateMessageAsync( MessageContext.Create(MessageTemplateNames.RecurringPaymentCancelledStoreOwner, languageId, order?.StoreId, order?.Customer), true, diff --git a/src/Smartstore.Core/Checkout/Payment/Hooks/RecurringPaymentHook.cs b/src/Smartstore.Core/Checkout/Payment/Hooks/RecurringPaymentHook.cs index 5d0244d6ca..27896357b2 100644 --- a/src/Smartstore.Core/Checkout/Payment/Hooks/RecurringPaymentHook.cs +++ b/src/Smartstore.Core/Checkout/Payment/Hooks/RecurringPaymentHook.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Checkout.Payment.Hooks { - internal class RecurringPaymentHook : AsyncDbSaveHook + internal class RecurringPaymentHook(SmartDbContext db, IEventPublisher eventPublisher) : AsyncDbSaveHook { - private readonly SmartDbContext _db; - private readonly IEventPublisher _eventPublisher; - - public RecurringPaymentHook(SmartDbContext db, IEventPublisher eventPublisher) - { - _db = db; - _eventPublisher = eventPublisher; - } + private readonly SmartDbContext _db = db; + private readonly IEventPublisher _eventPublisher = eventPublisher; protected override Task OnInsertedAsync(RecurringPayment entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); diff --git a/src/Smartstore.Core/Checkout/Payment/Rules/PaymentMethodRuleOptionsProvider.cs b/src/Smartstore.Core/Checkout/Payment/Rules/PaymentMethodRuleOptionsProvider.cs index 4e05add35b..c24e7ec780 100644 --- a/src/Smartstore.Core/Checkout/Payment/Rules/PaymentMethodRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Checkout/Payment/Rules/PaymentMethodRuleOptionsProvider.cs @@ -5,16 +5,12 @@ namespace Smartstore.Core.Checkout.Payment.Rules { - public partial class PaymentMethodRuleOptionsProvider : IRuleOptionsProvider + public partial class PaymentMethodRuleOptionsProvider( + IProviderManager providerManager, + ILocalizationService localizationService) : IRuleOptionsProvider { - private readonly IProviderManager _providerManager; - private readonly ILocalizationService _localizationService; - - public PaymentMethodRuleOptionsProvider(IProviderManager providerManager, ILocalizationService localizationService) - { - _providerManager = providerManager; - _localizationService = localizationService; - } + private readonly IProviderManager _providerManager = providerManager; + private readonly ILocalizationService _localizationService = localizationService; public int Order => 0; diff --git a/src/Smartstore.Core/Checkout/Payment/Service/PaymentService.cs b/src/Smartstore.Core/Checkout/Payment/Service/PaymentService.cs index 87701c9cc3..0c82a1e377 100644 --- a/src/Smartstore.Core/Checkout/Payment/Service/PaymentService.cs +++ b/src/Smartstore.Core/Checkout/Payment/Service/PaymentService.cs @@ -423,6 +423,7 @@ public virtual async Task ProcessPaymentAsync(ProcessPayme } var provider = await LoadProviderOrThrow(processPaymentRequest.PaymentMethodSystemName); + return await provider.Value.ProcessPaymentAsync(processPaymentRequest); } diff --git a/src/Smartstore.Core/Checkout/Rules/CartCompositeRule.cs b/src/Smartstore.Core/Checkout/Rules/CartCompositeRule.cs index 71dcd6d68f..802a74578e 100644 --- a/src/Smartstore.Core/Checkout/Rules/CartCompositeRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/CartCompositeRule.cs @@ -2,16 +2,10 @@ namespace Smartstore.Core.Checkout.Rules { - public class CartCompositeRule : IRule + public class CartCompositeRule(RuleExpressionGroup group, CartRuleProvider cartRuleProvider) : IRule { - private readonly RuleExpressionGroup _group; - private readonly CartRuleProvider _cartRuleProvider; - - public CartCompositeRule(RuleExpressionGroup group, CartRuleProvider cartRuleProvider) - { - _group = group; - _cartRuleProvider = cartRuleProvider; - } + private readonly RuleExpressionGroup _group = group; + private readonly CartRuleProvider _cartRuleProvider = cartRuleProvider; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/CartRuleProvider.cs b/src/Smartstore.Core/Checkout/Rules/CartRuleProvider.cs index 642209fa11..17dadf9e1a 100644 --- a/src/Smartstore.Core/Checkout/Rules/CartRuleProvider.cs +++ b/src/Smartstore.Core/Checkout/Rules/CartRuleProvider.cs @@ -9,31 +9,20 @@ namespace Smartstore.Core.Checkout.Rules { - public class CartRuleProvider : RuleProviderBase, ICartRuleProvider + public class CartRuleProvider( + IComponentContext componentContext, + IRuleService ruleService, + ICurrencyService currencyService, + IWorkContext workContext, + IStoreContext storeContext, + IShoppingCartService shoppingCartService) : RuleProviderBase(RuleScope.Cart), ICartRuleProvider { - private readonly IComponentContext _componentContext; - private readonly IRuleService _ruleService; - private readonly ICurrencyService _currencyService; - private readonly IWorkContext _workContext; - private readonly IStoreContext _storeContext; - private readonly IShoppingCartService _shoppingCartService; - - public CartRuleProvider( - IComponentContext componentContext, - IRuleService ruleService, - ICurrencyService currencyService, - IWorkContext workContext, - IStoreContext storeContext, - IShoppingCartService shoppingCartService) - : base(RuleScope.Cart) - { - _componentContext = componentContext; - _ruleService = ruleService; - _currencyService = currencyService; - _workContext = workContext; - _storeContext = storeContext; - _shoppingCartService = shoppingCartService; - } + private readonly IComponentContext _componentContext = componentContext; + private readonly IRuleService _ruleService = ruleService; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IWorkContext _workContext = workContext; + private readonly IStoreContext _storeContext = storeContext; + private readonly IShoppingCartService _shoppingCartService = shoppingCartService; public Localizer T { get; set; } = NullLocalizer.Instance; @@ -47,7 +36,7 @@ public IRule GetProcessor(RuleExpression expression) throw new InvalidOperationException($"Missing cart rule descriptor for expression {expression.Id} ('{expression.RawValue.EmptyNull()}')."); } - IRule< CartRuleContext> instance; + IRule instance; if (group == null && descriptor.ProcessorType != typeof(CartCompositeRule)) { @@ -62,15 +51,14 @@ public IRule GetProcessor(RuleExpression expression) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public async Task CreateExpressionGroupAsync(int ruleSetId) - { - return await _ruleService.CreateExpressionGroupAsync(ruleSetId, this) as RuleExpressionGroup; - } + public async Task CreateExpressionGroupAsync(int ruleSetId) => + await _ruleService.CreateExpressionGroupAsync(ruleSetId, this) as RuleExpressionGroup; public override async Task VisitRuleAsync(RuleEntity rule) { var expression = new RuleExpression(); await base.ConvertRuleAsync(rule, expression); + return expression; } @@ -95,7 +83,7 @@ public override IRuleExpressionGroup VisitRuleSet(RuleSetEntity ruleSet) } public async Task RuleMatchesAsync( - int[] ruleSetIds, + int[] ruleSetIds, LogicalRuleOperator logicalOperator, Action contextAction = null) { @@ -116,7 +104,7 @@ public async Task RuleMatchesAsync( } public async Task RuleMatchesAsync( - IRulesContainer entity, + IRulesContainer entity, LogicalRuleOperator logicalOperator = LogicalRuleOperator.Or, Action contextAction = null) { @@ -143,7 +131,7 @@ public async Task RuleMatchesAsync( } public async Task RuleMatchesAsync( - RuleExpression[] expressions, + RuleExpression[] expressions, LogicalRuleOperator logicalOperator, Action contextAction = null) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/BillingCountryRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/BillingCountryRule.cs index 272499a457..c3b60858f6 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/BillingCountryRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/BillingCountryRule.cs @@ -7,6 +7,7 @@ internal class BillingCountryRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(context.Customer?.BillingAddress?.CountryId ?? 0); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CartItemFromCategoryQuantityRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CartItemFromCategoryQuantityRule.cs index 215f6de8b5..64e4c53a5d 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CartItemFromCategoryQuantityRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CartItemFromCategoryQuantityRule.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class CartItemFromCategoryQuantityRule : IRule + internal class CartItemFromCategoryQuantityRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public CartItemFromCategoryQuantityRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CartSubtotalRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CartSubtotalRule.cs index 5ce57e95d0..d15d339e85 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CartSubtotalRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CartSubtotalRule.cs @@ -5,16 +5,10 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class CartSubtotalRule : IRule + internal class CartSubtotalRule(IOrderCalculationService orderCalculationService, IRoundingHelper roundingHelper) : IRule { - private readonly IOrderCalculationService _orderCalculationService; - private readonly IRoundingHelper _roundingHelper; - - public CartSubtotalRule(IOrderCalculationService orderCalculationService, IRoundingHelper roundingHelper) - { - _orderCalculationService = orderCalculationService; - _roundingHelper = roundingHelper; - } + private readonly IOrderCalculationService _orderCalculationService = orderCalculationService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CartTotalRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CartTotalRule.cs index cbc11e0ac2..88049d041e 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CartTotalRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CartTotalRule.cs @@ -5,16 +5,10 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class CartTotalRule : IRule + internal class CartTotalRule(IOrderCalculationService orderCalculationService, IRoundingHelper roundingHelper) : IRule { - private readonly IOrderCalculationService _orderCalculationService; - private readonly IRoundingHelper _roundingHelper; - - public CartTotalRule(IOrderCalculationService orderCalculationService, IRoundingHelper roundingHelper) - { - _orderCalculationService = orderCalculationService; - _roundingHelper = roundingHelper; - } + private readonly IOrderCalculationService _orderCalculationService = orderCalculationService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { @@ -39,6 +33,7 @@ public async Task MatchAsync(CartRuleContext context, RuleExpression expre var roundedTotal = _roundingHelper.Round(cartTotal.Total?.Amount ?? decimal.Zero); var result = expression.Operator.Match(roundedTotal, expression.Value); + return result; } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CurrencyRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CurrencyRule.cs index bc13812426..ecb2be98dd 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CurrencyRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CurrencyRule.cs @@ -7,6 +7,7 @@ internal class CurrencyRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(context.WorkContext.WorkingCurrency.Id); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAffiliateRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAffiliateRule.cs index 9bc3d611a0..5966501b4a 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAffiliateRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAffiliateRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class CustomerAffiliateRule : IRule + internal class CustomerAffiliateRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public CustomerAffiliateRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAuthenticationRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAuthenticationRule.cs index 5e313c6102..eb9ff6fc7f 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAuthenticationRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/CustomerAuthenticationRule.cs @@ -4,7 +4,7 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class CustomerAuthenticationRule : IRule + internal class CustomerAuthenticationRule(SmartDbContext db) : IRule { // INFO: ExternalAuthenticationRecord.ProviderSystemName always contains the old system name, even for new logins! private readonly static FrozenDictionary _legacyAuthenticationNamesMap = new Dictionary(StringComparer.OrdinalIgnoreCase) @@ -15,12 +15,7 @@ internal class CustomerAuthenticationRule : IRule } .ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); - private readonly SmartDbContext _db; - - public CustomerAuthenticationRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/IPCountryRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/IPCountryRule.cs index 121d1f54cd..b7ffe1d51c 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/IPCountryRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/IPCountryRule.cs @@ -4,16 +4,10 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class IPCountryRule : IRule + internal class IPCountryRule(IGeoCountryLookup countryLookup, IWebHelper webHelper) : IRule { - private readonly IGeoCountryLookup _countryLookup; - private readonly IWebHelper _webHelper; - - public IPCountryRule(IGeoCountryLookup countryLookup, IWebHelper webHelper) - { - _countryLookup = countryLookup; - _webHelper = webHelper; - } + private readonly IGeoCountryLookup _countryLookup = countryLookup; + private readonly IWebHelper _webHelper = webHelper; public Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/LanguageRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/LanguageRule.cs index bb81fd6798..d21a909116 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/LanguageRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/LanguageRule.cs @@ -7,6 +7,7 @@ internal class LanguageRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(context.WorkContext.WorkingLanguage.Id); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/OrderCountRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/OrderCountRule.cs index afe9d45769..27ec30a8cc 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/OrderCountRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/OrderCountRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class OrderCountRule : IRule + internal class OrderCountRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public OrderCountRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/PaidByRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/PaidByRule.cs index e70f512b69..0a32e4a0c6 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/PaidByRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/PaidByRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class PaidByRule : IRule + internal class PaidByRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public PaidByRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromCategoryInCartRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromCategoryInCartRule.cs index d06d35281e..11720fadc5 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromCategoryInCartRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromCategoryInCartRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class ProductFromCategoryInCartRule : IRule + internal class ProductFromCategoryInCartRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public ProductFromCategoryInCartRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { @@ -29,6 +24,7 @@ public async Task MatchAsync(CartRuleContext context, RuleExpression expre } var match = expression.HasListsMatch(categoryIds.Distinct()); + return match; } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromManufacturerInCartRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromManufacturerInCartRule.cs index 45b1962091..2831545407 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromManufacturerInCartRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ProductFromManufacturerInCartRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class ProductFromManufacturerInCartRule : IRule + internal class ProductFromManufacturerInCartRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public ProductFromManufacturerInCartRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ProductInCartRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ProductInCartRule.cs index 4d3705fe4b..8a2a0aea90 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ProductInCartRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ProductInCartRule.cs @@ -12,6 +12,7 @@ public Task MatchAsync(CartRuleContext context, RuleExpression expression) .ToArray(); var match = expression.HasListsMatch(productIds); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ProductOnWishlistRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ProductOnWishlistRule.cs index 8f804f3a58..557247c0e4 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ProductOnWishlistRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ProductOnWishlistRule.cs @@ -14,6 +14,7 @@ public async Task MatchAsync(CartRuleContext context, RuleExpression expre .ToArray(); var match = expression.HasListsMatch(productIds); + return match; } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ProductReviewCountRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ProductReviewCountRule.cs index 015d5e87df..3d6eff944c 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ProductReviewCountRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ProductReviewCountRule.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class ProductReviewCountRule : IRule + internal class ProductReviewCountRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public ProductReviewCountRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedFromManufacturerRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedFromManufacturerRule.cs index 5a012b506e..e085f11c28 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedFromManufacturerRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedFromManufacturerRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class PurchasedFromManufacturerRule : IRule + internal class PurchasedFromManufacturerRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public PurchasedFromManufacturerRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedProductRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedProductRule.cs index 2f4b04505b..b723f4dcf3 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedProductRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/PurchasedProductRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class PurchasedProductRule : IRule + internal class PurchasedProductRule(SmartDbContext db) : IRule { - private readonly SmartDbContext _db; - - public PurchasedProductRule(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { @@ -48,6 +43,7 @@ public async Task MatchAsync(CartRuleContext context, RuleExpression expre } var match = expression.HasListsMatch(productIds); + return match; } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/RewardPointsBalanceRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/RewardPointsBalanceRule.cs index 5305535f38..9a0ccd7b0e 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/RewardPointsBalanceRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/RewardPointsBalanceRule.cs @@ -7,6 +7,7 @@ internal class RewardPointsBalanceRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var rewardPointsBalance = context.Customer.GetRewardPointsBalance(); + return Task.FromResult(expression.Operator.Match(rewardPointsBalance, expression.Value)); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/RuleSetRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/RuleSetRule.cs index 25528d8f4a..0c8aa88872 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/RuleSetRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/RuleSetRule.cs @@ -2,16 +2,10 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - public class RuleSetRule : IRule + public class RuleSetRule(IRuleService ruleService, IRuleProviderFactory ruleProviderFactory) : IRule { - private readonly IRuleService _ruleService; - private readonly ICartRuleProvider _cartRuleProvider; - - public RuleSetRule(IRuleService ruleService, IRuleProviderFactory ruleProviderFactory) - { - _ruleService = ruleService; - _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); - } + private readonly IRuleService _ruleService = ruleService; + private readonly ICartRuleProvider _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/ShippingCountryRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/ShippingCountryRule.cs index 567877e6f0..67adc9e997 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/ShippingCountryRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/ShippingCountryRule.cs @@ -7,6 +7,7 @@ internal class ShippingCountryRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(context.Customer?.ShippingAddress?.CountryId ?? 0); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/SpentAmountRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/SpentAmountRule.cs index dc40bf9684..2373c062d2 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/SpentAmountRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/SpentAmountRule.cs @@ -5,21 +5,14 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class SpentAmountRule : IRule + internal class SpentAmountRule( + SmartDbContext db, + ICurrencyService currencyService, + IRoundingHelper roundingHelper) : IRule { - private readonly SmartDbContext _db; - private readonly ICurrencyService _currencyService; - private readonly IRoundingHelper _roundingHelper; - - public SpentAmountRule( - SmartDbContext db, - ICurrencyService currencyService, - IRoundingHelper roundingHelper) - { - _db = db; - _currencyService = currencyService; - _roundingHelper = roundingHelper; - } + private readonly SmartDbContext _db = db; + private readonly ICurrencyService _currencyService = currencyService; + private readonly IRoundingHelper _roundingHelper = roundingHelper; public async Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/StoreRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/StoreRule.cs index 63341411f0..83516bf1c7 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/StoreRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/StoreRule.cs @@ -7,6 +7,7 @@ internal class StoreRule : IRule public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(context.Store.Id); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMajorVersionRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMajorVersionRule.cs index 5c62de0394..7812e7cebc 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMajorVersionRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMajorVersionRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class BrowserMajorVersionRule : IRule + internal class BrowserMajorVersionRule(IUserAgent userAgent) : IRule { - private readonly IUserAgent _userAgent; - - public BrowserMajorVersionRule(IUserAgent userAgent) - { - _userAgent = userAgent; - } + private readonly IUserAgent _userAgent = userAgent; public Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMinorVersionRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMinorVersionRule.cs index e0bad2b32f..fb92103543 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMinorVersionRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserMinorVersionRule.cs @@ -3,14 +3,9 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class BrowserMinorVersionRule : IRule + internal class BrowserMinorVersionRule(IUserAgent userAgent) : IRule { - private readonly IUserAgent _userAgent; - - public BrowserMinorVersionRule(IUserAgent userAgent) - { - _userAgent = userAgent; - } + private readonly IUserAgent _userAgent = userAgent; public Task MatchAsync(CartRuleContext context, RuleExpression expression) { diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserRule.cs index d8bcc2c450..e82d71cee3 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/BrowserRule.cs @@ -3,18 +3,13 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class BrowserRule : IRule + internal class BrowserRule(IUserAgent userAgent) : IRule { - private readonly IUserAgent _userAgent; + private readonly IUserAgent _userAgent = userAgent; - public BrowserRule(IUserAgent userAgent) - { - _userAgent = userAgent; - } + public static RuleValueSelectListOption[] GetDefaultOptions() => - public static RuleValueSelectListOption[] GetDefaultOptions() - { - return new[] + new[] { "Chrome", "Edge", @@ -30,11 +25,12 @@ public static RuleValueSelectListOption[] GetDefaultOptions() } .Select(x => new RuleValueSelectListOption { Value = x, Text = x }) .ToArray(); - } + public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = _userAgent.IsBrowser() && expression.HasListMatch(_userAgent.Name.NullEmpty()); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/DeviceRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/DeviceRule.cs index 19616f5ba8..1b7336ab33 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/DeviceRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/DeviceRule.cs @@ -13,17 +13,17 @@ public DeviceRule(IUserAgent userAgent) _userAgent = userAgent; } - public static RuleValueSelectListOption[] GetDefaultOptions() - { - return EngineContext.Current.Application.Services.Resolve() + public static RuleValueSelectListOption[] GetDefaultOptions() => + EngineContext.Current.Application.Services + .Resolve() .GetDetectableDevices() .Select(x => new RuleValueSelectListOption { Value = x, Text = x }) .ToArray(); - } public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = _userAgent.IsMobileDevice() && expression.HasListMatch(_userAgent.Device.Name.NullEmpty()); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/IsMobileRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/IsMobileRule.cs index 549b088240..6985895f4c 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/IsMobileRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/IsMobileRule.cs @@ -3,18 +3,14 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class IsMobileRule : IRule + internal class IsMobileRule(IUserAgent userAgent) : IRule { - private readonly IUserAgent _userAgent; - - public IsMobileRule(IUserAgent userAgent) - { - _userAgent = userAgent; - } + private readonly IUserAgent _userAgent = userAgent; public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.Operator.Match(_userAgent.IsMobileDevice(), expression.Value); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/OSRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/OSRule.cs index 325d52f9e9..ca7159466f 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/OSRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/UserAgent/OSRule.cs @@ -4,27 +4,22 @@ namespace Smartstore.Core.Checkout.Rules.Impl { - internal class OSRule : IRule + internal class OSRule(IUserAgent userAgent) : IRule { - private readonly IUserAgent _userAgent; + private readonly IUserAgent _userAgent = userAgent; - public OSRule(IUserAgent userAgent) - { - _userAgent = userAgent; - } - - public static RuleValueSelectListOption[] GetDefaultOptions() - { - return EngineContext.Current.Application.Services.Resolve() + public static RuleValueSelectListOption[] GetDefaultOptions() => + EngineContext.Current.Application.Services + .Resolve() .GetDetectablePlatforms() .Concat(new[] { "Unknown" }) .Select(x => new RuleValueSelectListOption { Value = x, Text = x }) .ToArray(); - } public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch(_userAgent.Platform.Name.NullEmpty()); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Rules/Impl/WeekdayRule.cs b/src/Smartstore.Core/Checkout/Rules/Impl/WeekdayRule.cs index 1ee07ede48..8df98c27c7 100644 --- a/src/Smartstore.Core/Checkout/Rules/Impl/WeekdayRule.cs +++ b/src/Smartstore.Core/Checkout/Rules/Impl/WeekdayRule.cs @@ -23,6 +23,7 @@ public static RuleValueSelectListOption[] GetDefaultValues(Language language) public Task MatchAsync(CartRuleContext context, RuleExpression expression) { var match = expression.HasListMatch((int)DateTime.Now.DayOfWeek); + return Task.FromResult(match); } } diff --git a/src/Smartstore.Core/Checkout/Shipping/Domain/Shipment.cs b/src/Smartstore.Core/Checkout/Shipping/Domain/Shipment.cs index 07a6073b13..38be857e2a 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Domain/Shipment.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Domain/Shipment.cs @@ -7,13 +7,11 @@ namespace Smartstore.Core.Checkout.Shipping { internal class ShipmentMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(x => x.Order) - .WithMany(x => x.Shipments) - .HasForeignKey(x => x.OrderId) - .OnDelete(DeleteBehavior.Cascade); - } + .WithMany(x => x.Shipments) + .HasForeignKey(x => x.OrderId) + .OnDelete(DeleteBehavior.Cascade); } /// diff --git a/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingMethod.cs b/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingMethod.cs index 3329be4b47..e65f4c6b31 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingMethod.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingMethod.cs @@ -11,8 +11,8 @@ namespace Smartstore.Core.Checkout.Shipping { internal class ShippingMethodMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder)=> + builder .HasMany(x => x.RuleSets) .WithMany(x => x.ShippingMethods) @@ -35,7 +35,7 @@ public void Configure(EntityTypeBuilder builder) c.HasIndex("ShippingMethod_Id"); c.HasKey("ShippingMethod_Id", "RuleSetEntity_Id"); }); - } + } /// diff --git a/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingOption.cs b/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingOption.cs index 1d4768ff1f..7ab8e17541 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingOption.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Domain/ShippingOption.cs @@ -63,15 +63,9 @@ public ITypeConverter GetConverter(Type type) } } - public class ShippingOptionConverter : DefaultTypeConverter + public class ShippingOptionConverter(bool forList) : DefaultTypeConverter(typeof(object)) { - private readonly bool _forList; - - public ShippingOptionConverter(bool forList) - : base(typeof(object)) - { - _forList = forList; - } + private readonly bool _forList = forList; public override bool CanConvertFrom(Type type) => type == typeof(string); diff --git a/src/Smartstore.Core/Checkout/Shipping/Extensions/ShipmentEventPublisherExtensions.cs b/src/Smartstore.Core/Checkout/Shipping/Extensions/ShipmentEventPublisherExtensions.cs index 9d1cf34306..4afadc8351 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Extensions/ShipmentEventPublisherExtensions.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Extensions/ShipmentEventPublisherExtensions.cs @@ -11,12 +11,11 @@ public static class ShipmentEventPublisherExtensions /// /// The event publisher. /// The shipment the tracking number that was added to. - public static Task PublishTrackingNumberAddedAsync(this IEventPublisher eventPublisher, Shipment shipment) - { - return shipment != null + public static Task PublishTrackingNumberAddedAsync(this IEventPublisher eventPublisher, Shipment shipment) => + shipment != null ? eventPublisher.PublishAsync(new TrackingNumberAddedEvent(shipment)) : Task.CompletedTask; - } + /// /// Publishes the tracking number changed event. @@ -24,11 +23,10 @@ public static Task PublishTrackingNumberAddedAsync(this IEventPublisher eventPub /// The event publisher. /// The shipment for which the tracking number has changed. /// The old tracking number of the shipment. - public static Task PublishTrackingNumberChangedAsync(this IEventPublisher eventPublisher, Shipment shipment, string oldTrackingNumber) - { - return shipment != null + public static Task PublishTrackingNumberChangedAsync(this IEventPublisher eventPublisher, Shipment shipment, string oldTrackingNumber) => + shipment != null ? eventPublisher.PublishAsync(new TrackingNumberChangedEvent(shipment, oldTrackingNumber)) : Task.CompletedTask; - } + } } diff --git a/src/Smartstore.Core/Checkout/Shipping/Hooks/ShipmentHook.cs b/src/Smartstore.Core/Checkout/Shipping/Hooks/ShipmentHook.cs index 4464173ad3..b04b176cd2 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Hooks/ShipmentHook.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Hooks/ShipmentHook.cs @@ -8,16 +8,10 @@ namespace Smartstore.Core.Checkout.Shipping.Hooks /// Shipment hook /// [Important] - internal partial class ShipmentHook : AsyncDbSaveHook + internal partial class ShipmentHook(IEventPublisher eventPublisher, SmartDbContext db) : AsyncDbSaveHook { - private readonly IEventPublisher _eventPublisher; - private readonly SmartDbContext _db; - - public ShipmentHook(IEventPublisher eventPublisher, SmartDbContext db) - { - _eventPublisher = eventPublisher; - _db = db; - } + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly SmartDbContext _db = db; public override async Task OnBeforeSaveAsync(IHookedEntity entry, CancellationToken cancelToken) { @@ -64,26 +58,22 @@ protected override async Task OnDeletedAsync(Shipment entity, IHooke /// Shipment item hook /// [Important] - internal partial class ShipmentItemHook : AsyncDbSaveHook + internal partial class ShipmentItemHook(IEventPublisher eventPublisher, SmartDbContext db) : AsyncDbSaveHook { - private readonly IEventPublisher _eventPublisher; - private readonly SmartDbContext _db; - - public ShipmentItemHook(IEventPublisher eventPublisher, SmartDbContext db) - { - _eventPublisher = eventPublisher; - _db = db; - } + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly SmartDbContext _db = db; protected override async Task OnInsertingAsync(ShipmentItem entity, IHookedEntity entry, CancellationToken cancelToken) { await _eventPublisher.PublishOrderUpdatedAsync(entity.Shipment.Order); + return HookResult.Ok; } protected override async Task OnUpdatingAsync(ShipmentItem entity, IHookedEntity entry, CancellationToken cancelToken) { await _eventPublisher.PublishOrderUpdatedAsync(entity.Shipment.Order); + return HookResult.Ok; } diff --git a/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingMethodRuleOptionsProvider.cs b/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingMethodRuleOptionsProvider.cs index 3e7313affe..130a540a82 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingMethodRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingMethodRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Checkout.Shipping.Rules { - public partial class ShippingMethodRuleOptionsProvider : IRuleOptionsProvider + public partial class ShippingMethodRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public ShippingMethodRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingRateComputationMethodRuleOptionsProvider.cs b/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingRateComputationMethodRuleOptionsProvider.cs index ee57f78892..025cba8d41 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingRateComputationMethodRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Rules/ShippingRateComputationMethodRuleOptionsProvider.cs @@ -5,16 +5,12 @@ namespace Smartstore.Core.Checkout.Shipping.Rules { - public partial class ShippingRateComputationMethodRuleOptionsProvider : IRuleOptionsProvider + public partial class ShippingRateComputationMethodRuleOptionsProvider( + IProviderManager providerManager, + ILocalizationService localizationService) : IRuleOptionsProvider { - private readonly IProviderManager _providerManager; - private readonly ILocalizationService _localizationService; - - public ShippingRateComputationMethodRuleOptionsProvider(IProviderManager providerManager, ILocalizationService localizationService) - { - _providerManager = providerManager; - _localizationService = localizationService; - } + private readonly IProviderManager _providerManager = providerManager; + private readonly ILocalizationService _localizationService = localizationService; public int Order => 0; diff --git a/src/Smartstore.Core/Checkout/Shipping/Services/ShippingService.cs b/src/Smartstore.Core/Checkout/Shipping/Services/ShippingService.cs index 9605bb7c19..a7cf2e511b 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Services/ShippingService.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Services/ShippingService.cs @@ -15,39 +15,26 @@ namespace Smartstore.Core.Checkout.Shipping { - public partial class ShippingService : IShippingService + public partial class ShippingService( + IProductAttributeMaterializer productAttributeMaterializer, + ICheckoutAttributeMaterializer checkoutAttributeMaterializer, + IRuleProviderFactory ruleProviderFactory, + ShippingSettings shippingSettings, + IProviderManager providerManager, + ISettingFactory settingFactory, + IRoundingHelper roundingHelper, + IStoreContext storeContext, + SmartDbContext db) : IShippingService { - private readonly IProductAttributeMaterializer _productAttributeMaterializer; - private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer; - private readonly ICartRuleProvider _cartRuleProvider; - private readonly ShippingSettings _shippingSettings; - private readonly IProviderManager _providerManager; - private readonly ISettingFactory _settingFactory; - private readonly IRoundingHelper _roundingHelper; - private readonly IStoreContext _storeContext; - private readonly SmartDbContext _db; - - public ShippingService( - IProductAttributeMaterializer productAttributeMaterializer, - ICheckoutAttributeMaterializer checkoutAttributeMaterializer, - IRuleProviderFactory ruleProviderFactory, - ShippingSettings shippingSettings, - IProviderManager providerManager, - ISettingFactory settingFactory, - IRoundingHelper roundingHelper, - IStoreContext storeContext, - SmartDbContext db) - { - _productAttributeMaterializer = productAttributeMaterializer; - _checkoutAttributeMaterializer = checkoutAttributeMaterializer; - _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); - _shippingSettings = shippingSettings; - _providerManager = providerManager; - _settingFactory = settingFactory; - _roundingHelper = roundingHelper; - _storeContext = storeContext; - _db = db; - } + private readonly IProductAttributeMaterializer _productAttributeMaterializer = productAttributeMaterializer; + private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer = checkoutAttributeMaterializer; + private readonly ICartRuleProvider _cartRuleProvider = ruleProviderFactory.GetProvider(RuleScope.Cart); + private readonly ShippingSettings _shippingSettings = shippingSettings; + private readonly IProviderManager _providerManager = providerManager; + private readonly ISettingFactory _settingFactory = settingFactory; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly IStoreContext _storeContext = storeContext; + private readonly SmartDbContext _db = db; public Localizer T { get; set; } = NullLocalizer.Instance; public ILogger Logger { get; set; } = NullLogger.Instance; @@ -146,8 +133,8 @@ public virtual async Task GetCartTotalWeightAsync(ShoppingCart cart, bo } public virtual ShippingOptionRequest CreateShippingOptionRequest( - ShoppingCart cart, - Address shippingAddress, + ShoppingCart cart, + Address shippingAddress, int storeId, bool matchRules = true) { @@ -324,15 +311,11 @@ private async Task GetCartWeight(OrganizedShoppingCartItem[] cart, bool return cartWeight; - bool IgnoreCartItem(OrganizedShoppingCartItem cartItem) - { - return !includeFreeShippingProducts && cartItem.Item.Product.IsFreeShipping; - } + bool IgnoreCartItem(OrganizedShoppingCartItem cartItem) => + !includeFreeShippingProducts && cartItem.Item.Product.IsFreeShipping; - static string CreateAttributeKey(int productVariantAttributeId, int productVariantAttributeValueId) - { - return productVariantAttributeId + "-" + productVariantAttributeValueId; - } + static string CreateAttributeKey(int productVariantAttributeId, int productVariantAttributeValueId) => + productVariantAttributeId + "-" + productVariantAttributeValueId; } } } \ No newline at end of file diff --git a/src/Smartstore.Core/Checkout/Shipping/Tracking/CompositeShipmentTracker.cs b/src/Smartstore.Core/Checkout/Shipping/Tracking/CompositeShipmentTracker.cs index 319a4d762b..1a55c5219f 100644 --- a/src/Smartstore.Core/Checkout/Shipping/Tracking/CompositeShipmentTracker.cs +++ b/src/Smartstore.Core/Checkout/Shipping/Tracking/CompositeShipmentTracker.cs @@ -5,18 +5,13 @@ namespace Smartstore.Core.Checkout.Shipping /// /// General shipment tracker (finds an appropriate tracker by tracking number). /// - internal partial class CompositeShipmentTracker : IShipmentTracker + internal partial class CompositeShipmentTracker(ITypeScanner typeScanner) : IShipmentTracker { // TODO: (mg) (core) Implement a shipment tracker for DHL! private static Type[] _trackerTypes = null; private readonly static object _lock = new(); - private readonly ITypeScanner _typeScanner; - - public CompositeShipmentTracker(ITypeScanner typeScanner) - { - _typeScanner = typeScanner; - } + private readonly ITypeScanner _typeScanner = typeScanner; /// /// Gets all trackers. The result gets cached. diff --git a/src/Smartstore.Core/Checkout/Tax/Domain/Tax.cs b/src/Smartstore.Core/Checkout/Tax/Domain/Tax.cs index ad03903a08..e225f47e27 100644 --- a/src/Smartstore.Core/Checkout/Tax/Domain/Tax.cs +++ b/src/Smartstore.Core/Checkout/Tax/Domain/Tax.cs @@ -6,65 +6,60 @@ namespace Smartstore.Core.Checkout.Tax /// /// Represents tax info. /// - public readonly struct Tax + /// + /// Initializes a new instance of the structure. + /// + /// The tax rate. + /// The calculated tax amount. + /// The origin price. + /// The calculated bet price. + /// The calculated gross price. + /// A value indicating whether includes tax already. + /// A value indicating whether the result price should be gross (including tax). + public readonly struct Tax(TaxRate rate, + decimal amount, + decimal price, + decimal priceNet, + decimal priceGross, + bool isGrossPrice, + bool inclusive) { public readonly static Tax Zero; - /// - /// Initializes a new instance of the structure. - /// - /// The tax rate. - /// The calculated tax amount. - /// The origin price. - /// The calculated bet price. - /// The calculated gross price. - /// A value indicating whether includes tax already. - /// A value indicating whether the result price should be gross (including tax). - public Tax(TaxRate rate, decimal amount, decimal price, decimal priceNet, decimal priceGross, bool isGrossPrice, bool inclusive) - { - Rate = rate; - Amount = amount; - IsGrossPrice = isGrossPrice; - Inclusive = inclusive; - PriceNet = priceNet; - PriceGross = priceGross; - Price = price; - } - /// /// The tax rate used for calculation. /// - public TaxRate Rate { get; } + public TaxRate Rate { get; } = rate; /// /// The unrounded tax amount. /// - public decimal Amount { get; } + public decimal Amount { get; } = amount; /// /// Whether source price is gross (including tax) /// - public bool IsGrossPrice { get; } + public bool IsGrossPrice { get; } = isGrossPrice; /// /// Whether result price is gross (including tax) /// - public bool Inclusive { get; } + public bool Inclusive { get; } = inclusive; /// /// The unrounded net price. /// - public decimal PriceNet { get; } + public decimal PriceNet { get; } = priceNet; /// /// The unrounded gross price. /// - public decimal PriceGross { get; } + public decimal PriceGross { get; } = priceGross; /// /// The rounded price, either net or gross according to . /// - public decimal Price { get; } + public decimal Price { get; } = price; [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() diff --git a/src/Smartstore.Core/Checkout/Tax/Domain/TaxRate.cs b/src/Smartstore.Core/Checkout/Tax/Domain/TaxRate.cs index ecde9000f3..cd42b2af24 100644 --- a/src/Smartstore.Core/Checkout/Tax/Domain/TaxRate.cs +++ b/src/Smartstore.Core/Checkout/Tax/Domain/TaxRate.cs @@ -3,25 +3,19 @@ /// /// Represents the tax rate resolution result. /// - public readonly struct TaxRate + public readonly struct TaxRate(decimal rate, int taxCategoryId) { public readonly static TaxRate Zero; - public TaxRate(decimal rate, int taxCategoryId) - { - Rate = rate; - TaxCategoryId = taxCategoryId; - } - /// /// The tax rate /// - public decimal Rate { get; } + public decimal Rate { get; } = rate; /// /// The tax category id /// - public int TaxCategoryId { get; } + public int TaxCategoryId { get; } = taxCategoryId; public static implicit operator decimal(TaxRate rate) => rate.Rate; public static implicit operator double(TaxRate rate) => Convert.ToDouble(rate.Rate); diff --git a/src/Smartstore.Core/Checkout/Tax/Domain/VatCheckResult.cs b/src/Smartstore.Core/Checkout/Tax/Domain/VatCheckResult.cs index 017f9ab586..3414046288 100644 --- a/src/Smartstore.Core/Checkout/Tax/Domain/VatCheckResult.cs +++ b/src/Smartstore.Core/Checkout/Tax/Domain/VatCheckResult.cs @@ -3,26 +3,20 @@ /// /// Represents the result of VAT number check. /// - public partial class VatCheckResult + public partial class VatCheckResult(VatNumberStatus status, string vatNumber) { - public VatCheckResult(VatNumberStatus status, string vatNumber) - { - Status = status; - VatNumber = vatNumber; - } - public static implicit operator VatNumberStatus(VatCheckResult obj) => obj.Status; /// /// Gets or sets the VAT number status. /// - public VatNumberStatus Status { get; private set; } + public VatNumberStatus Status { get; private set; } = status; /// /// Gets or sets the VAT number to be checked (including the two letter country ISO code). /// - public string VatNumber { get; private set; } + public string VatNumber { get; private set; } = vatNumber; /// /// Gets or sets the two letter country ISO code of the returned by the VAT service. @@ -45,9 +39,7 @@ public static implicit operator VatNumberStatus(VatCheckResult obj) /// public Exception Exception { get; init; } - public override string ToString() - { - return $"VAT:{VatNumber} {Status}. name:{Name} country:{CountryCode} address:{Address}"; - } + public override string ToString() => + $"VAT:{VatNumber} {Status}. name:{Name} country:{CountryCode} address:{Address}"; } } \ No newline at end of file diff --git a/src/Smartstore.Core/Checkout/Tax/Extensions/ITaxServiceExtensions.cs b/src/Smartstore.Core/Checkout/Tax/Extensions/ITaxServiceExtensions.cs index 4f11f5b35a..4b784fb2ff 100644 --- a/src/Smartstore.Core/Checkout/Tax/Extensions/ITaxServiceExtensions.cs +++ b/src/Smartstore.Core/Checkout/Tax/Extensions/ITaxServiceExtensions.cs @@ -38,6 +38,7 @@ public static Money ApplyTaxFormat(this ITaxService taxService, return source; var format = taxService.GetTaxFormat(displayTaxSuffix, priceIncludesTax, PricingTarget.Product, language); + return source.WithPostFormat(format); } @@ -71,6 +72,7 @@ public static Money ApplyShippingChargeTaxFormat(this ITaxService taxService, return source; var format = taxService.GetTaxFormat(displayTaxSuffix, priceIncludesTax, PricingTarget.ShippingCharge, language); + return source.WithPostFormat(format); } @@ -104,6 +106,7 @@ public static Money ApplyPaymentFeeTaxFormat(this ITaxService taxService, return source; var format = taxService.GetTaxFormat(displayTaxSuffix, priceIncludesTax, PricingTarget.PaymentFee, language); + return source.WithPostFormat(format); } } diff --git a/src/Smartstore.Core/Checkout/Tax/Services/TaxCalculator.cs b/src/Smartstore.Core/Checkout/Tax/Services/TaxCalculator.cs index b350b76107..c4f98c06a8 100644 --- a/src/Smartstore.Core/Checkout/Tax/Services/TaxCalculator.cs +++ b/src/Smartstore.Core/Checkout/Tax/Services/TaxCalculator.cs @@ -7,27 +7,18 @@ namespace Smartstore.Core.Checkout.Tax { - public class TaxCalculator : ITaxCalculator + public class TaxCalculator( + SmartDbContext db, + IWorkContext workContext, + IRoundingHelper roundingHelper, + ITaxService taxService, + TaxSettings taxSettings) : ITaxCalculator { - private readonly SmartDbContext _db; - private readonly IWorkContext _workContext; - private readonly IRoundingHelper _roundingHelper; - private readonly ITaxService _taxService; - private readonly TaxSettings _taxSettings; - - public TaxCalculator( - SmartDbContext db, - IWorkContext workContext, - IRoundingHelper roundingHelper, - ITaxService taxService, - TaxSettings taxSettings) - { - _db = db; - _workContext = workContext; - _roundingHelper = roundingHelper; - _taxService = taxService; - _taxSettings = taxSettings; - } + private readonly SmartDbContext _db = db; + private readonly IWorkContext _workContext = workContext; + private readonly IRoundingHelper _roundingHelper = roundingHelper; + private readonly ITaxService _taxService = taxService; + private readonly TaxSettings _taxSettings = taxSettings; public virtual Task CalculateProductTaxAsync( Product product, diff --git a/src/Smartstore.Core/Checkout/Tax/Services/ViesTaxationHttpClient.cs b/src/Smartstore.Core/Checkout/Tax/Services/ViesTaxationHttpClient.cs index 2edf2b64c6..96026795df 100644 --- a/src/Smartstore.Core/Checkout/Tax/Services/ViesTaxationHttpClient.cs +++ b/src/Smartstore.Core/Checkout/Tax/Services/ViesTaxationHttpClient.cs @@ -4,14 +4,9 @@ namespace Smartstore.Core.Checkout.Tax { - public class ViesTaxationHttpClient + public class ViesTaxationHttpClient(HttpClient httpClient) { - private readonly HttpClient _httpClient; - - public ViesTaxationHttpClient(HttpClient httpClient) - { - _httpClient = httpClient; - } + private readonly HttpClient _httpClient = httpClient; public async Task CheckVatAsync(string vatNumber, string countryCode, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Common/Domain/Address.cs b/src/Smartstore.Core/Common/Domain/Address.cs index 8e6f00aed4..6e28b18769 100644 --- a/src/Smartstore.Core/Common/Domain/Address.cs +++ b/src/Smartstore.Core/Common/Domain/Address.cs @@ -139,30 +139,29 @@ public StateProvince StateProvince private ICollection Customers { get; set; } #pragma warning restore IDE0051 // Remove unused private members - public object Clone() - { - var addr = new Address - { - Salutation = this.Salutation, - Title = this.Title, - FirstName = this.FirstName, - LastName = this.LastName, - Email = this.Email, - Company = this.Company, - Country = this.Country, - CountryId = this.CountryId, - StateProvince = this.StateProvince, - StateProvinceId = this.StateProvinceId, - City = this.City, - Address1 = this.Address1, - Address2 = this.Address2, - ZipPostalCode = this.ZipPostalCode, - PhoneNumber = this.PhoneNumber, - FaxNumber = this.FaxNumber, - CreatedOnUtc = this.CreatedOnUtc, - }; - return addr; - } + public object Clone() => + new Address + { + Salutation = this.Salutation, + Title = this.Title, + FirstName = this.FirstName, + LastName = this.LastName, + Email = this.Email, + Company = this.Company, + Country = this.Country, + CountryId = this.CountryId, + StateProvince = this.StateProvince, + StateProvinceId = this.StateProvinceId, + City = this.City, + Address1 = this.Address1, + Address2 = this.Address2, + ZipPostalCode = this.ZipPostalCode, + PhoneNumber = this.PhoneNumber, + FaxNumber = this.FaxNumber, + CreatedOnUtc = this.CreatedOnUtc, + }; + + public static string DefaultAddressFormat => @"{{ Salutation }} {{ Title }} {{ FirstName }} {{ LastName }} {{ Company }} @@ -173,20 +172,11 @@ public object Clone() #region IEquatable - public static bool operator ==(Address x, Address y) - { - return Equals(x, y); - } + public static bool operator ==(Address x, Address y) => Equals(x, y); - public static bool operator !=(Address x, Address y) - { - return !Equals(x, y); - } + public static bool operator !=(Address x, Address y) => !Equals(x, y); - public override bool Equals(object obj) - { - return ((IEquatable
)this).Equals(obj as Address); - } + public override bool Equals(object obj) => ((IEquatable
)this).Equals(obj as Address); bool IEquatable
.Equals(Address other) { @@ -232,10 +222,7 @@ public override int GetHashCode() return combiner.CombinedHash; } - public override string ToString() - { - return $"Address (Id: {Id}, {Company}, {FirstName} {LastName}, {Address1} {Address2}, {ZipPostalCode} {City}, StateProvinceId: {StateProvinceId}, CountryId: {CountryId})"; - } + public override string ToString() => $"Address (Id: {Id}, {Company}, {FirstName} {LastName}, {Address1} {Address2}, {ZipPostalCode} {City}, StateProvinceId: {StateProvinceId}, CountryId: {CountryId})"; #endregion } diff --git a/src/Smartstore.Core/Common/Domain/MeasureDimension.cs b/src/Smartstore.Core/Common/Domain/MeasureDimension.cs index 9fa211c07c..b626d14452 100644 --- a/src/Smartstore.Core/Common/Domain/MeasureDimension.cs +++ b/src/Smartstore.Core/Common/Domain/MeasureDimension.cs @@ -7,10 +7,8 @@ namespace Smartstore.Core.Common { internal class MeasureDimensionMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.Property(c => c.Ratio).HasPrecision(18, 8); - } } /// diff --git a/src/Smartstore.Core/Common/Domain/MeasureWeight.cs b/src/Smartstore.Core/Common/Domain/MeasureWeight.cs index ead50b2bab..b2bd06f35c 100644 --- a/src/Smartstore.Core/Common/Domain/MeasureWeight.cs +++ b/src/Smartstore.Core/Common/Domain/MeasureWeight.cs @@ -6,10 +6,8 @@ namespace Smartstore.Core.Common { internal class MeasureWeightMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.Property(c => c.Ratio).HasPrecision(18, 8); - } } /// diff --git a/src/Smartstore.Core/Common/Domain/Money.cs b/src/Smartstore.Core/Common/Domain/Money.cs index 67bbe4c99d..123820e0b0 100644 --- a/src/Smartstore.Core/Common/Domain/Money.cs +++ b/src/Smartstore.Core/Common/Domain/Money.cs @@ -76,7 +76,7 @@ public decimal Amount /// internal decimal RoundedAmount { - get => decimal.Round(Amount, DecimalDigits, + get => decimal.Round(Amount, DecimalDigits, Currency == null || Currency.MidpointRounding == CurrencyMidpointRounding.AwayFromZero ? MidpointRounding.AwayFromZero : MidpointRounding.ToEven); } @@ -274,7 +274,7 @@ public string ToString(bool? showCurrency = null, bool useISOCodeAsSymbol = fals { if (Currency == null) { - return postFormat == null + return postFormat == null ? RoundedAmount.ToStringInvariant() : string.Format(postFormat, RoundedAmount.ToStringInvariant()); } @@ -593,9 +593,7 @@ public override bool CanWrite public override Money ReadJson(JsonReader reader, Type objectType, Money existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotSupportedException(); - public override void WriteJson(JsonWriter writer, Money value, JsonSerializer serializer) - { + public override void WriteJson(JsonWriter writer, Money value, JsonSerializer serializer) => serializer.Serialize(writer, value.ToString()); - } } } diff --git a/src/Smartstore.Core/Common/Extensions/CurrencyExtensions.cs b/src/Smartstore.Core/Common/Extensions/CurrencyExtensions.cs index 64da736b28..f72dd4e9a9 100644 --- a/src/Smartstore.Core/Common/Extensions/CurrencyExtensions.cs +++ b/src/Smartstore.Core/Common/Extensions/CurrencyExtensions.cs @@ -14,6 +14,7 @@ public static bool HasDomainEnding(this Currency currency, string domain) return false; var endings = currency.DomainEndings.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + return endings.Any(x => domain.EndsWith(x, StringComparison.InvariantCultureIgnoreCase)); } diff --git a/src/Smartstore.Core/Common/Extensions/DateTimeHelperExtensions.cs b/src/Smartstore.Core/Common/Extensions/DateTimeHelperExtensions.cs index 64f72b212f..fd66b39d12 100644 --- a/src/Smartstore.Core/Common/Extensions/DateTimeHelperExtensions.cs +++ b/src/Smartstore.Core/Common/Extensions/DateTimeHelperExtensions.cs @@ -20,10 +20,8 @@ public static DateTime ConvertToUserTime(this IDateTimeHelper helper, DateTime d /// Converts the date to current user date and time /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static DateTime ConvertToUserTime(this IDateTimeHelper helper, DateTime dt) - { - return helper.ConvertToUserTime(dt, dt.Kind); - } + public static DateTime ConvertToUserTime(this IDateTimeHelper helper, DateTime dt) => + helper.ConvertToUserTime(dt, dt.Kind); /// /// Converts the date and time to Coordinated Universal Time (UTC) @@ -33,6 +31,7 @@ public static DateTime ConvertToUtcTime(this IDateTimeHelper helper, DateTime dt { sourceTimeZone ??= helper.CurrentTimeZone; dt = DateTime.SpecifyKind(dt, sourceDateTimeKind); + return helper.ConvertToUtcTime(dt, sourceTimeZone); } @@ -40,9 +39,7 @@ public static DateTime ConvertToUtcTime(this IDateTimeHelper helper, DateTime dt /// Converts the date and time to Coordinated Universal Time (UTC) /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static DateTime ConvertToUtcTime(this IDateTimeHelper helper, DateTime dt) - { - return helper.ConvertToUtcTime(dt, dt.Kind); - } + public static DateTime ConvertToUtcTime(this IDateTimeHelper helper, DateTime dt) => + helper.ConvertToUtcTime(dt, dt.Kind); } } diff --git a/src/Smartstore.Core/Common/Hooks/AssignedEntitiesHook.cs b/src/Smartstore.Core/Common/Hooks/AssignedEntitiesHook.cs index 724ca34803..ba4ba572b7 100644 --- a/src/Smartstore.Core/Common/Hooks/AssignedEntitiesHook.cs +++ b/src/Smartstore.Core/Common/Hooks/AssignedEntitiesHook.cs @@ -10,7 +10,7 @@ namespace Smartstore.Core.Common.Hooks /// Without explicit deletion these assigned entities (like LocalizedProperty or MediaTrack) would remain in the database forever. /// [Important] - internal class AssignedEntitiesHook : AsyncDbSaveHook + internal class AssignedEntitiesHook(SmartDbContext db) : AsyncDbSaveHook { private static readonly FrozenSet _candidateTypes = new Type[] { @@ -20,14 +20,9 @@ internal class AssignedEntitiesHook : AsyncDbSaveHook typeof(SpecificationAttribute) }.ToFrozenSet(); - private readonly SmartDbContext _db; + private readonly SmartDbContext _db = db; private readonly List _assignedItems = []; - public AssignedEntitiesHook(SmartDbContext db) - { - _db = db; - } - protected override Task OnDeletingAsync(BaseEntity entity, IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(_candidateTypes.Contains(entry.EntityType) ? HookResult.Ok : HookResult.Void); diff --git a/src/Smartstore.Core/Common/Hooks/MeasureDimensionHook.cs b/src/Smartstore.Core/Common/Hooks/MeasureDimensionHook.cs index 01dc4c8de8..ac8d9e8aee 100644 --- a/src/Smartstore.Core/Common/Hooks/MeasureDimensionHook.cs +++ b/src/Smartstore.Core/Common/Hooks/MeasureDimensionHook.cs @@ -5,16 +5,11 @@ namespace Smartstore.Core.Common.Hooks { - internal class MeasureDimensionHook : AsyncDbSaveHook + internal class MeasureDimensionHook(MeasureSettings measureSettings) : AsyncDbSaveHook { - private readonly MeasureSettings _measureSettings; + private readonly MeasureSettings _measureSettings = measureSettings; private string _hookErrorMessage; - public MeasureDimensionHook(MeasureSettings measureSettings) - { - _measureSettings = measureSettings; - } - public Localizer T { get; set; } = NullLocalizer.Instance; protected override Task OnDeletingAsync(MeasureDimension entity, IHookedEntity entry, CancellationToken cancelToken) diff --git a/src/Smartstore.Core/Common/Hooks/QuantityUnitHook.cs b/src/Smartstore.Core/Common/Hooks/QuantityUnitHook.cs index 20d8d957dd..1b8e087599 100644 --- a/src/Smartstore.Core/Common/Hooks/QuantityUnitHook.cs +++ b/src/Smartstore.Core/Common/Hooks/QuantityUnitHook.cs @@ -8,16 +8,11 @@ namespace Smartstore.Core.Common.Hooks { [Important] - internal class QuantityUnitHook : AsyncDbSaveHook + internal class QuantityUnitHook(SmartDbContext db) : AsyncDbSaveHook { - private readonly SmartDbContext _db; + private readonly SmartDbContext _db = db; private string _hookErrorMessage; - public QuantityUnitHook(SmartDbContext db) - { - _db = db; - } - public Localizer T { get; set; } = NullLocalizer.Instance; /// diff --git a/src/Smartstore.Core/Common/JsonConverters/UTCDateTimeConverter.cs b/src/Smartstore.Core/Common/JsonConverters/UTCDateTimeConverter.cs index 8dec763e52..d38c99a0bc 100644 --- a/src/Smartstore.Core/Common/JsonConverters/UTCDateTimeConverter.cs +++ b/src/Smartstore.Core/Common/JsonConverters/UTCDateTimeConverter.cs @@ -9,20 +9,13 @@ public class UTCDateTimeConverter : DateTimeConverterBase { private readonly DateTimeConverterBase _innerConverter; - public UTCDateTimeConverter(DateTimeConverterBase innerConverter) - { + public UTCDateTimeConverter(DateTimeConverterBase innerConverter) => _innerConverter = Guard.NotNull(innerConverter, nameof(innerConverter)); - } - public override bool CanConvert(Type objectType) - { - return _innerConverter.CanConvert(objectType); - } + public override bool CanConvert(Type objectType) => _innerConverter.CanConvert(objectType); - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - return _innerConverter.ReadJson(reader, objectType, existingValue, serializer); - } + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => + _innerConverter.ReadJson(reader, objectType, existingValue, serializer); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { diff --git a/src/Smartstore.Core/Common/Rules/CommonRuleOptionsProvider.cs b/src/Smartstore.Core/Common/Rules/CommonRuleOptionsProvider.cs index 13894452a6..bf5120bb6f 100644 --- a/src/Smartstore.Core/Common/Rules/CommonRuleOptionsProvider.cs +++ b/src/Smartstore.Core/Common/Rules/CommonRuleOptionsProvider.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Common.Rules { - public partial class CommonRuleOptionsProvider : IRuleOptionsProvider + public partial class CommonRuleOptionsProvider(SmartDbContext db) : IRuleOptionsProvider { - private readonly SmartDbContext _db; - - public CommonRuleOptionsProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public int Order => 0; diff --git a/src/Smartstore.Core/Common/Services/AddressService.cs b/src/Smartstore.Core/Common/Services/AddressService.cs index 0bd5c5806a..994cc79f92 100644 --- a/src/Smartstore.Core/Common/Services/AddressService.cs +++ b/src/Smartstore.Core/Common/Services/AddressService.cs @@ -7,27 +7,18 @@ namespace Smartstore.Core.Common.Services { - public partial class AddressService : AsyncDbSaveHook
, IAddressService + public partial class AddressService( + SmartDbContext db, + ICommonServices services, + ITemplateEngine templateEngine, + IMessageModelProvider messageModelProvider, + AddressSettings addressSettings) : AsyncDbSaveHook
, IAddressService { - private readonly SmartDbContext _db; - private readonly ICommonServices _services; - private readonly ITemplateEngine _templateEngine; - private readonly IMessageModelProvider _messageModelProvider; - private readonly AddressSettings _addressSettings; - - public AddressService( - SmartDbContext db, - ICommonServices services, - ITemplateEngine templateEngine, - IMessageModelProvider messageModelProvider, - AddressSettings addressSettings) - { - _db = db; - _services = services; - _addressSettings = addressSettings; - _templateEngine = templateEngine; - _messageModelProvider = messageModelProvider; - } + private readonly SmartDbContext _db = db; + private readonly ICommonServices _services = services; + private readonly ITemplateEngine _templateEngine = templateEngine; + private readonly IMessageModelProvider _messageModelProvider = messageModelProvider; + private readonly AddressSettings _addressSettings = addressSettings; #region Hook diff --git a/src/Smartstore.Core/Common/Services/CurrencyService.cs b/src/Smartstore.Core/Common/Services/CurrencyService.cs index a19dcb1a4a..d3ee4a67f2 100644 --- a/src/Smartstore.Core/Common/Services/CurrencyService.cs +++ b/src/Smartstore.Core/Common/Services/CurrencyService.cs @@ -10,41 +10,30 @@ namespace Smartstore.Core.Common.Services { [Important] - public partial class CurrencyService : AsyncDbSaveHook, ICurrencyService + public partial class CurrencyService( + SmartDbContext db, + ICacheManager cache, + IProviderManager providerManager, + IWorkContext workContext, + CurrencySettings currencySettings, + ISettingFactory settingFactory, + IRoundingHelper roundingHelper) : AsyncDbSaveHook, ICurrencyService { // 0 = exchange rate currency code. // 1 = provider system name. const string LiveCurrencyRatesKey = "live.currency.rates:{0}-{1}"; - private readonly SmartDbContext _db; - private readonly ICacheManager _cache; - private readonly IProviderManager _providerManager; - private readonly IWorkContext _workContext; - private readonly CurrencySettings _currencySettings; - private readonly ISettingFactory _settingFactory; - private readonly IRoundingHelper _roundingHelper; + private readonly SmartDbContext _db = db; + private readonly ICacheManager _cache = cache; + private readonly IProviderManager _providerManager = providerManager; + private readonly IWorkContext _workContext = workContext; + private readonly CurrencySettings _currencySettings = currencySettings; + private readonly ISettingFactory _settingFactory = settingFactory; + private readonly IRoundingHelper _roundingHelper = roundingHelper; private Currency _primaryCurrency; private Currency _primaryExchangeCurrency; - public CurrencyService( - SmartDbContext db, - ICacheManager cache, - IProviderManager providerManager, - IWorkContext workContext, - CurrencySettings currencySettings, - ISettingFactory settingFactory, - IRoundingHelper roundingHelper) - { - _db = db; - _cache = cache; - _providerManager = providerManager; - _workContext = workContext; - _currencySettings = currencySettings; - _settingFactory = settingFactory; - _roundingHelper = roundingHelper; - } - public Localizer T { get; set; } = NullLocalizer.Instance; #region Hook diff --git a/src/Smartstore.Core/Common/Services/DateTimeHelper.cs b/src/Smartstore.Core/Common/Services/DateTimeHelper.cs index 918aaa6f5b..0157fab15a 100644 --- a/src/Smartstore.Core/Common/Services/DateTimeHelper.cs +++ b/src/Smartstore.Core/Common/Services/DateTimeHelper.cs @@ -8,27 +8,19 @@ namespace Smartstore.Core.Common.Services { - public partial class DateTimeHelper : IDateTimeHelper + public partial class DateTimeHelper( + SmartDbContext db, + ISettingService settingService, + IWorkContext workContext, + DateTimeSettings dateTimeSettings) : IDateTimeHelper { - private readonly SmartDbContext _db; - private readonly ISettingService _settingService; - private readonly IWorkContext _workContext; - private readonly DateTimeSettings _dateTimeSettings; + private readonly SmartDbContext _db = db; + private readonly ISettingService _settingService = settingService; + private readonly IWorkContext _workContext = workContext; + private readonly DateTimeSettings _dateTimeSettings = dateTimeSettings; private TimeZoneInfo _cachedUserTimeZone; - public DateTimeHelper( - SmartDbContext db, - ISettingService settingService, - IWorkContext workContext, - DateTimeSettings dateTimeSettings) - { - _db = db; - _settingService = settingService; - _workContext = workContext; - _dateTimeSettings = dateTimeSettings; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public virtual TimeZoneInfo FindTimeZoneById(string id) { diff --git a/src/Smartstore.Core/Common/Services/DeliveryTimeService.cs b/src/Smartstore.Core/Common/Services/DeliveryTimeService.cs index c941300106..69a36b36da 100644 --- a/src/Smartstore.Core/Common/Services/DeliveryTimeService.cs +++ b/src/Smartstore.Core/Common/Services/DeliveryTimeService.cs @@ -12,26 +12,18 @@ namespace Smartstore.Core.Common.Services { [Important] - public partial class DeliveryTimeService : AsyncDbSaveHook, IDeliveryTimeService + public partial class DeliveryTimeService( + SmartDbContext db, + IDateTimeHelper dateTimeHelper, + ShippingSettings shippingSettings, + CatalogSettings catalogSettings) : AsyncDbSaveHook, IDeliveryTimeService { private readonly static ConcurrentDictionary _monthDayFormats = new(StringComparer.OrdinalIgnoreCase); - private readonly SmartDbContext _db; - private readonly IDateTimeHelper _dateTimeHelper; - private readonly ShippingSettings _shippingSettings; - private readonly CatalogSettings _catalogSettings; - - public DeliveryTimeService( - SmartDbContext db, - IDateTimeHelper dateTimeHelper, - ShippingSettings shippingSettings, - CatalogSettings catalogSettings) - { - _db = db; - _dateTimeHelper = dateTimeHelper; - _shippingSettings = shippingSettings; - _catalogSettings = catalogSettings; - } + private readonly SmartDbContext _db = db; + private readonly IDateTimeHelper _dateTimeHelper = dateTimeHelper; + private readonly ShippingSettings _shippingSettings = shippingSettings; + private readonly CatalogSettings _catalogSettings = catalogSettings; public Localizer T { get; set; } = NullLocalizer.Instance; diff --git a/src/Smartstore.Core/Common/Services/EcbExchangeRateProvider.cs b/src/Smartstore.Core/Common/Services/EcbExchangeRateProvider.cs index 1f9c30ff0e..1384400c4a 100644 --- a/src/Smartstore.Core/Common/Services/EcbExchangeRateProvider.cs +++ b/src/Smartstore.Core/Common/Services/EcbExchangeRateProvider.cs @@ -11,14 +11,9 @@ namespace Smartstore.Core.Common.Services [SystemName("CurrencyExchange.ECB")] [FriendlyName("ECB currency exchange rate provider")] [Order(0)] - internal class EcbExchangeRateProvider : IExchangeRateProvider + internal class EcbExchangeRateProvider(IHttpClientFactory httpClientFactory) : IExchangeRateProvider { - private readonly IHttpClientFactory _httpClientFactory; - - public EcbExchangeRateProvider(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } + private readonly IHttpClientFactory _httpClientFactory = httpClientFactory; public virtual async Task> GetCurrencyLiveRatesAsync(string exchangeRateCurrencyCode) { diff --git a/src/Smartstore.Core/Common/Services/GenericAttributeService.cs b/src/Smartstore.Core/Common/Services/GenericAttributeService.cs index e8ee241dae..0518fd4146 100644 --- a/src/Smartstore.Core/Common/Services/GenericAttributeService.cs +++ b/src/Smartstore.Core/Common/Services/GenericAttributeService.cs @@ -6,22 +6,15 @@ namespace Smartstore.Core.Common.Services { - public partial class GenericAttributeService : AsyncDbSaveHook, IGenericAttributeService + public partial class GenericAttributeService(SmartDbContext db, IStoreContext storeContext, IEventPublisher eventPublisher) : AsyncDbSaveHook, IGenericAttributeService { - private readonly SmartDbContext _db; - private readonly IStoreContext _storeContext; - private readonly IEventPublisher _eventPublisher; + private readonly SmartDbContext _db = db; + private readonly IStoreContext _storeContext = storeContext; + private readonly IEventPublisher _eventPublisher = eventPublisher; // Key = (EntityName, EntityId) private readonly Dictionary<(string, int), GenericAttributeCollection> _collectionCache = new(); - public GenericAttributeService(SmartDbContext db, IStoreContext storeContext, IEventPublisher eventPublisher) - { - _db = db; - _storeContext = storeContext; - _eventPublisher = eventPublisher; - } - #region Hook public override Task OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) diff --git a/src/Smartstore.Core/Common/Services/MeasureService.cs b/src/Smartstore.Core/Common/Services/MeasureService.cs index 48a7edf862..9710848cba 100644 --- a/src/Smartstore.Core/Common/Services/MeasureService.cs +++ b/src/Smartstore.Core/Common/Services/MeasureService.cs @@ -3,16 +3,10 @@ namespace Smartstore.Core.Common.Services { - public partial class MeasureService : IMeasureService + public partial class MeasureService(SmartDbContext db, MeasureSettings measureSettings) : IMeasureService { - private readonly SmartDbContext _db; - private readonly MeasureSettings _measureSettings; - - public MeasureService(SmartDbContext db, MeasureSettings measureSettings) - { - _db = db; - _measureSettings = measureSettings; - } + private readonly SmartDbContext _db = db; + private readonly MeasureSettings _measureSettings = measureSettings; public virtual async Task ConvertDimensionAsync(decimal quantity, MeasureDimension source, MeasureDimension target, bool round = true) { diff --git a/src/Smartstore.Core/Common/Services/RoundingHelper.cs b/src/Smartstore.Core/Common/Services/RoundingHelper.cs index 61c6698a5b..ade62f47f6 100644 --- a/src/Smartstore.Core/Common/Services/RoundingHelper.cs +++ b/src/Smartstore.Core/Common/Services/RoundingHelper.cs @@ -4,28 +4,21 @@ namespace Smartstore.Core.Common.Services { - public partial class RoundingHelper : IRoundingHelper + public partial class RoundingHelper(IWorkContext workContext, CurrencySettings currencySettings) : IRoundingHelper { - private readonly IWorkContext _workContext; - private readonly CurrencySettings _currencySettings; - - public RoundingHelper(IWorkContext workContext, CurrencySettings currencySettings) - { - _workContext = workContext; - _currencySettings = currencySettings; - } + private readonly IWorkContext _workContext = workContext; + private readonly CurrencySettings _currencySettings = currencySettings; public virtual decimal Round(decimal amount, Currency currency = null) { currency ??= _workContext.WorkingCurrency; + return Round(amount, currency.RoundNumDecimals, currency.MidpointRounding); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public virtual decimal Round(decimal amount, int decimals, CurrencyMidpointRounding midpointRounding = CurrencyMidpointRounding.AwayFromZero) - { - return decimal.Round(amount, decimals, Convert(midpointRounding)); - } + public virtual decimal Round(decimal amount, int decimals, CurrencyMidpointRounding midpointRounding = CurrencyMidpointRounding.AwayFromZero) => + decimal.Round(amount, decimals, Convert(midpointRounding)); public virtual bool IsShoppingCartRoundingEnabled(Currency currency = null, TaxDisplayType? taxDisplayType = null) { diff --git a/src/Smartstore.Core/Common/Tasks/TempFileCleanupTask.cs b/src/Smartstore.Core/Common/Tasks/TempFileCleanupTask.cs index 04f4c1880a..49fb69f8c6 100644 --- a/src/Smartstore.Core/Common/Tasks/TempFileCleanupTask.cs +++ b/src/Smartstore.Core/Common/Tasks/TempFileCleanupTask.cs @@ -5,14 +5,9 @@ namespace Smartstore.Core.Common.Tasks /// /// Task to cleanup temporary files. /// - public partial class TempFileCleanupTask : ITask + public partial class TempFileCleanupTask(IApplicationContext appContext) : ITask { - private readonly IApplicationContext _appContext; - - public TempFileCleanupTask(IApplicationContext appContext) - { - _appContext = appContext; - } + private readonly IApplicationContext _appContext = appContext; public Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Common/Tasks/UpdateExchangeRateTask.cs b/src/Smartstore.Core/Common/Tasks/UpdateExchangeRateTask.cs index b850ba90ff..a0c5e89eca 100644 --- a/src/Smartstore.Core/Common/Tasks/UpdateExchangeRateTask.cs +++ b/src/Smartstore.Core/Common/Tasks/UpdateExchangeRateTask.cs @@ -8,21 +8,14 @@ namespace Smartstore.Core.Common.Tasks /// /// A task that periodically updates exchange rates. /// - public partial class UpdateExchangeRateTask : ITask + public partial class UpdateExchangeRateTask( + SmartDbContext db, + ICurrencyService currencyService, + CurrencySettings currencySettings) : ITask { - private readonly SmartDbContext _db; - private readonly ICurrencyService _currencyService; - private readonly CurrencySettings _currencySettings; - - public UpdateExchangeRateTask( - SmartDbContext db, - ICurrencyService currencyService, - CurrencySettings currencySettings) - { - _db = db; - _currencyService = currencyService; - _currencySettings = currencySettings; - } + private readonly SmartDbContext _db = db; + private readonly ICurrencyService _currencyService = currencyService; + private readonly CurrencySettings _currencySettings = currencySettings; public async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Content/Blocks/BlockHandlerBase.cs b/src/Smartstore.Core/Content/Blocks/BlockHandlerBase.cs index 22d48113a5..7946bbc8be 100644 --- a/src/Smartstore.Core/Content/Blocks/BlockHandlerBase.cs +++ b/src/Smartstore.Core/Content/Blocks/BlockHandlerBase.cs @@ -23,10 +23,7 @@ public abstract class BlockHandlerBase : IBlockHandler where TBl public required ILocalizedEntityService LocalizedEntityService { protected get; set; } - public virtual TBlock Create(IBlockEntity entity) - { - return Activator.CreateInstance(); - } + public virtual TBlock Create(IBlockEntity entity) => Activator.CreateInstance(); protected virtual TBlock Load(IBlockEntity entity, StoryViewMode viewMode) { @@ -87,38 +84,31 @@ public virtual Task SaveAsync(TBlock block, IBlockEntity entity) return Task.CompletedTask; } - public virtual Task AfterSaveAsync(IBlockContainer container, IBlockEntity entity) - { + public virtual Task AfterSaveAsync(IBlockContainer container, IBlockEntity entity) => // Default impl does nothing. - return Task.CompletedTask; - } + Task.CompletedTask; public virtual void BeforeRender(IBlockContainer container, StoryViewMode viewMode, IBlockHtmlParts htmlParts) { // Default impl does nothing. } - public virtual Task CloneAsync(IBlockEntity sourceEntity, IBlockEntity clonedEntity) - { - return Task.FromResult(sourceEntity.Model); - } + public virtual Task CloneAsync(IBlockEntity sourceEntity, IBlockEntity clonedEntity) => + Task.FromResult(sourceEntity.Model); - public Task RenderAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper) - { - return RenderCoreAsync(element, templates, htmlHelper, htmlHelper.ViewContext.Writer); - } + public Task RenderAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper) => + RenderCoreAsync(element, templates, htmlHelper, htmlHelper.ViewContext.Writer); public async Task ToHtmlContentAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper) { using var writer = new StringWriter(CultureInfo.CurrentCulture); await RenderCoreAsync(element, templates, htmlHelper, writer); + return new HtmlString(writer.ToString()); } - protected virtual Task RenderCoreAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper, TextWriter textWriter) - { - return RenderByViewAsync(element, templates, htmlHelper, textWriter); - } + protected virtual Task RenderCoreAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper, TextWriter textWriter) => + RenderByViewAsync(element, templates, htmlHelper, textWriter); protected virtual Task RenderByViewAsync(IBlockContainer element, IEnumerable templates, IHtmlHelper htmlHelper, TextWriter textWriter) { @@ -172,10 +162,7 @@ protected virtual async Task RenderByWidgetAsync(IBlockContainer element, IEnume content.WriteTo(textWriter, HtmlEncoder.Default); } - protected virtual Widget GetWidget(IBlockContainer element, IHtmlHelper htmlHelper, string template) - { - throw new NotImplementedException(); - } + protected virtual Widget GetWidget(IBlockContainer element, IHtmlHelper htmlHelper, string template) => throw new NotImplementedException(); private static ActionContext GetActionContextFor(IBlockContainer element, ActionContext originalContext) { diff --git a/src/Smartstore.Core/Content/Blocks/StoryAssetAttribute.cs b/src/Smartstore.Core/Content/Blocks/StoryAssetAttribute.cs index ca9d21e97e..6ac471a822 100644 --- a/src/Smartstore.Core/Content/Blocks/StoryAssetAttribute.cs +++ b/src/Smartstore.Core/Content/Blocks/StoryAssetAttribute.cs @@ -4,17 +4,13 @@ /// Specifies whether a property refers to an asset to be included in the story export. ///
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public sealed class StoryAssetAttribute : Attribute + public sealed class StoryAssetAttribute(StoryAssetKind kind) : Attribute { - public StoryAssetAttribute(StoryAssetKind kind) - { - Kind = kind; - } /// /// The asset property kind. /// - public StoryAssetKind Kind { get; private set; } + public StoryAssetKind Kind { get; private set; } = kind; } public enum StoryAssetKind From 6e7d9f00d17cc893d0d71b307f7076a8461c74ee Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Fri, 28 Jun 2024 15:13:00 +0400 Subject: [PATCH 2/2] Refactor your C# code with primary constructors --- .../Content/Media/Album/AlbumRegistry.cs | 36 +++------ .../Content/Media/Album/FolderService.cs | 15 +--- .../Content/Media/Album/MediaFolderInfo.cs | 34 +++----- .../Content/Media/Album/MediaFolderNode.cs | 5 +- .../Media/Album/SystemAlbumProvider.cs | 10 +-- .../Media/Bootstrapping/MediaStarter.cs | 5 +- .../Content/Media/Domain/Download.cs | 15 ++-- .../Content/Media/DownloadService.cs | 12 +-- .../DupeDetectors/CachingMediaDupeDetector.cs | 13 +-- .../DupeDetectors/DefaultMediaDupeDetector.cs | 15 +--- .../DupeDetectors/MediaDupeDetectorBase.cs | 5 +- .../DupeDetectors/MediaDupeDetectorFactory.cs | 12 +-- .../Extensions/IFolderServiceExtensions.cs | 29 +++---- .../Extensions/IMediaServiceExtensions.cs | 12 +-- .../MediaDisplayHelperExtensions.cs | 7 +- .../Content/Media/FileBatchSource.cs | 8 +- .../Filters/MaxMediaFileSizeAttribute.cs | 15 +--- .../Content/Media/Handlers/ImageHandler.cs | 19 ++--- .../Content/Media/Hooks/ImageOffloaderHook.cs | 36 +++------ .../Content/Media/IDownloadService.cs | 6 +- .../Content/Media/Icons/IconExplorer.cs | 9 +-- .../Content/Media/Imaging/CachedImage.cs | 9 +-- .../Media/Imaging/DefaultImageProcessor.cs | 18 ++--- .../Imaging/Events/ImageProcessedEvent.cs | 12 +-- .../Imaging/Events/ImageProcessingEvent.cs | 12 +-- .../Imaging/Events/ImageQueryCreatedEvent.cs | 22 +++-- .../Imaging/Events/ImageUploadedEvent.cs | 11 +-- .../Media/Imaging/Events/MediaSavedEvent.cs | 11 +-- .../Content/Media/Imaging/ImageCache.cs | 15 +--- .../Content/Media/MediaExceptionFactory.cs | 35 ++------ .../Content/Media/MediaHelper.cs | 9 +-- .../Content/Media/MediaLegacyMiddleware.cs | 4 +- .../Content/Media/MediaService.cs | 81 +++++++------------ .../Media/MediaServiceFileSystemAdapter.cs | 42 ++++------ .../Media/MediaTypes/MediaTypeResolver.cs | 12 +-- .../Content/Media/Search/MediaSearcher.cs | 12 +-- .../Storage/DatabaseMediaStorageProvider.cs | 9 +-- .../Storage/FileSystemMediaStorageProvider.cs | 14 ++-- .../Content/Media/Storage/MediaMover.cs | 15 +--- .../Media/Tasks/TransientMediaClearTask.cs | 12 +-- .../Media/Tracking/MediaTrackerHook.cs | 9 +-- .../Tracking/TrackedMediaPropertyTable.cs | 32 +++----- .../Menus/Consumers/CatalogMenuInvalidator.cs | 26 +++--- 43 files changed, 227 insertions(+), 513 deletions(-) diff --git a/src/Smartstore.Core/Content/Media/Album/AlbumRegistry.cs b/src/Smartstore.Core/Content/Media/Album/AlbumRegistry.cs index a043ae381b..e9ed1af639 100644 --- a/src/Smartstore.Core/Content/Media/Album/AlbumRegistry.cs +++ b/src/Smartstore.Core/Content/Media/Album/AlbumRegistry.cs @@ -3,31 +3,20 @@ namespace Smartstore.Core.Content.Media { - public class AlbumRegistry : IAlbumRegistry + public class AlbumRegistry( + SmartDbContext db, + ICacheManager cache, + IEnumerable> albumProviders, + IEnumerable> trackDetectors) : IAlbumRegistry { internal const string AlbumInfosKey = "media:albums:all"; - private readonly SmartDbContext _db; - private readonly ICacheManager _cache; - private readonly IEnumerable> _albumProviders; - private readonly IEnumerable> _trackDetectors; + private readonly SmartDbContext _db = db; + private readonly ICacheManager _cache = cache; + private readonly IEnumerable> _albumProviders = albumProviders; + private readonly IEnumerable> _trackDetectors = trackDetectors; - public AlbumRegistry( - SmartDbContext db, - ICacheManager cache, - IEnumerable> albumProviders, - IEnumerable> trackDetectors) - { - _db = db; - _cache = cache; - _albumProviders = albumProviders; - _trackDetectors = trackDetectors; - } - - public virtual IReadOnlyCollection GetAllAlbums() - { - return GetAlbumDictionary().Values; - } + public virtual IReadOnlyCollection GetAllAlbums() => GetAlbumDictionary().Values; public IEnumerable GetAlbumNames(bool withTrackDetectors = false) { @@ -158,9 +147,6 @@ private AlbumInfo GetAlbumValidated(string albumName, bool throwWhenSystemAlbum) return album; } - public Task ClearCacheAsync() - { - return _cache.RemoveAsync(AlbumInfosKey); - } + public Task ClearCacheAsync() => _cache.RemoveAsync(AlbumInfosKey); } } diff --git a/src/Smartstore.Core/Content/Media/Album/FolderService.cs b/src/Smartstore.Core/Content/Media/Album/FolderService.cs index 6de049babc..3c8c5bbfa1 100644 --- a/src/Smartstore.Core/Content/Media/Album/FolderService.cs +++ b/src/Smartstore.Core/Content/Media/Album/FolderService.cs @@ -6,22 +6,15 @@ namespace Smartstore.Core.Content.Media { [Important(HookImportance.Essential)] - public partial class FolderService : AsyncDbSaveHook, IFolderService + public partial class FolderService(IAlbumRegistry albumRegistry, SmartDbContext db, ICacheManager cache) : AsyncDbSaveHook, IFolderService { internal static TimeSpan FolderTreeCacheDuration = TimeSpan.FromHours(3); internal const string FolderTreeKey = "mediafolder:tree"; - private readonly IAlbumRegistry _albumRegistry; - private readonly SmartDbContext _db; - private readonly ICacheManager _cache; - - public FolderService(IAlbumRegistry albumRegistry, SmartDbContext db, ICacheManager cache) - { - _albumRegistry = albumRegistry; - _db = db; - _cache = cache; - } + private readonly IAlbumRegistry _albumRegistry = albumRegistry; + private readonly SmartDbContext _db = db; + private readonly ICacheManager _cache = cache; #region Invalidation Hook diff --git a/src/Smartstore.Core/Content/Media/Album/MediaFolderInfo.cs b/src/Smartstore.Core/Content/Media/Album/MediaFolderInfo.cs index 8d1ea050b1..e003628038 100644 --- a/src/Smartstore.Core/Content/Media/Album/MediaFolderInfo.cs +++ b/src/Smartstore.Core/Content/Media/Album/MediaFolderInfo.cs @@ -8,31 +8,21 @@ namespace Smartstore.Core.Content.Media { - public partial class MediaFolderInfo : IDirectory + public partial class MediaFolderInfo( + TreeNode node, + IMediaService mediaService, + IMediaSearcher mediaSearcher, + IFolderService folderService, + MediaExceptionFactory exceptionFactory) : IDirectory { - private readonly IMediaService _mediaService; - private readonly IMediaSearcher _mediaSearcher; - private readonly IFolderService _folderService; - private readonly MediaExceptionFactory _exceptionFactory; - private readonly DateTimeOffset _now; - - public MediaFolderInfo( - TreeNode node, - IMediaService mediaService, - IMediaSearcher mediaSearcher, - IFolderService folderService, - MediaExceptionFactory exceptionFactory) - { - Node = node; - _mediaService = mediaService; - _mediaSearcher = mediaSearcher; - _folderService = folderService; - _exceptionFactory = exceptionFactory; - _now = DateTimeOffset.UtcNow; - } + private readonly IMediaService _mediaService = mediaService; + private readonly IMediaSearcher _mediaSearcher = mediaSearcher; + private readonly IFolderService _folderService = folderService; + private readonly MediaExceptionFactory _exceptionFactory = exceptionFactory; + private readonly DateTimeOffset _now = DateTimeOffset.UtcNow; [IgnoreDataMember] - public TreeNode Node { get; } + public TreeNode Node { get; } = node; [JsonProperty("filesCount")] public int FilesCount => Node.Value.FilesCount; diff --git a/src/Smartstore.Core/Content/Media/Album/MediaFolderNode.cs b/src/Smartstore.Core/Content/Media/Album/MediaFolderNode.cs index 28e3c3ba7a..45c6defe1f 100644 --- a/src/Smartstore.Core/Content/Media/Album/MediaFolderNode.cs +++ b/src/Smartstore.Core/Content/Media/Album/MediaFolderNode.cs @@ -4,10 +4,7 @@ namespace Smartstore.Core.Content.Media { public class MediaFolderNode : IKeyedNode { - object IKeyedNode.GetNodeKey() - { - return Id; - } + object IKeyedNode.GetNodeKey() => Id; /// /// Whether the folder is a root album node diff --git a/src/Smartstore.Core/Content/Media/Album/SystemAlbumProvider.cs b/src/Smartstore.Core/Content/Media/Album/SystemAlbumProvider.cs index 849268907c..bdef001cf1 100644 --- a/src/Smartstore.Core/Content/Media/Album/SystemAlbumProvider.cs +++ b/src/Smartstore.Core/Content/Media/Album/SystemAlbumProvider.cs @@ -13,15 +13,9 @@ namespace Smartstore.Core.Content.Media { - public class SystemAlbumProvider : IAlbumProvider, IMediaTrackDetector + public class SystemAlbumProvider(SmartDbContext db) : IAlbumProvider, IMediaTrackDetector { - private readonly SmartDbContext _db; - - public SystemAlbumProvider(SmartDbContext db) - { - _db = db; - } - + private readonly SmartDbContext _db = db; public const string Catalog = "catalog"; public const string Content = "content"; public const string Downloads = "download"; diff --git a/src/Smartstore.Core/Content/Media/Bootstrapping/MediaStarter.cs b/src/Smartstore.Core/Content/Media/Bootstrapping/MediaStarter.cs index 160b96ddd7..a9d4430d77 100644 --- a/src/Smartstore.Core/Content/Media/Bootstrapping/MediaStarter.cs +++ b/src/Smartstore.Core/Content/Media/Bootstrapping/MediaStarter.cs @@ -15,10 +15,7 @@ namespace Smartstore.Core.Bootstrapping { internal class MediaStarter : StarterBase { - public MediaStarter() - { - RunAfter(); - } + public MediaStarter() => RunAfter(); public override void BuildPipeline(RequestPipelineBuilder builder) { diff --git a/src/Smartstore.Core/Content/Media/Domain/Download.cs b/src/Smartstore.Core/Content/Media/Domain/Download.cs index 409e9c28a5..afd81b9170 100644 --- a/src/Smartstore.Core/Content/Media/Domain/Download.cs +++ b/src/Smartstore.Core/Content/Media/Domain/Download.cs @@ -6,13 +6,11 @@ namespace Smartstore.Core.Content.Media { internal class DownloadMap : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder builder) - { + public void Configure(EntityTypeBuilder builder) => builder.HasOne(c => c.MediaFile) - .WithMany() - .HasForeignKey(c => c.MediaFileId) - .OnDelete(DeleteBehavior.SetNull); - } + .WithMany() + .HasForeignKey(c => c.MediaFileId) + .OnDelete(DeleteBehavior.SetNull); } /// @@ -107,9 +105,6 @@ public Download Clone() return download; } - object ICloneable.Clone() - { - return Clone(); - } + object ICloneable.Clone() => Clone(); } } \ No newline at end of file diff --git a/src/Smartstore.Core/Content/Media/DownloadService.cs b/src/Smartstore.Core/Content/Media/DownloadService.cs index 0e69b52e75..ab7281bf9c 100644 --- a/src/Smartstore.Core/Content/Media/DownloadService.cs +++ b/src/Smartstore.Core/Content/Media/DownloadService.cs @@ -5,16 +5,10 @@ namespace Smartstore.Core.Content.Media { - public partial class DownloadService : IDownloadService + public partial class DownloadService(SmartDbContext db, IMediaService mediaService) : IDownloadService { - private readonly SmartDbContext _db; - private readonly IMediaService _mediaService; - - public DownloadService(SmartDbContext db, IMediaService mediaService) - { - _db = db; - _mediaService = mediaService; - } + private readonly SmartDbContext _db = db; + private readonly IMediaService _mediaService = mediaService; public virtual async Task InsertDownloadAsync(Download download, Stream stream, string fileName) { diff --git a/src/Smartstore.Core/Content/Media/DupeDetectors/CachingMediaDupeDetector.cs b/src/Smartstore.Core/Content/Media/DupeDetectors/CachingMediaDupeDetector.cs index b5081ab945..6ea3255a89 100644 --- a/src/Smartstore.Core/Content/Media/DupeDetectors/CachingMediaDupeDetector.cs +++ b/src/Smartstore.Core/Content/Media/DupeDetectors/CachingMediaDupeDetector.cs @@ -1,18 +1,12 @@ namespace Smartstore.Core.Content.Media { - internal class CachingMediaDupeDetector : MediaDupeDetectorBase + internal class CachingMediaDupeDetector(IMediaSearcher searcher, int folderId) : MediaDupeDetectorBase { - private readonly IMediaSearcher _searcher; - private readonly int _folderId; + private readonly IMediaSearcher _searcher = searcher; + private readonly int _folderId = folderId; private Dictionary _cachedFiles; - public CachingMediaDupeDetector(IMediaSearcher searcher, int folderId) - { - _searcher = searcher; - _folderId = folderId; - } - public override async Task DetectFileAsync(string fileName, CancellationToken cancelToken = default) { if (fileName.IsEmpty()) @@ -21,6 +15,7 @@ public override async Task DetectFileAsync(string fileName, Cancellat } var files = await GetFiles(cancelToken); + return files.Get(fileName); } diff --git a/src/Smartstore.Core/Content/Media/DupeDetectors/DefaultMediaDupeDetector.cs b/src/Smartstore.Core/Content/Media/DupeDetectors/DefaultMediaDupeDetector.cs index fc8dfc2ed1..ed8fd8948c 100644 --- a/src/Smartstore.Core/Content/Media/DupeDetectors/DefaultMediaDupeDetector.cs +++ b/src/Smartstore.Core/Content/Media/DupeDetectors/DefaultMediaDupeDetector.cs @@ -1,22 +1,15 @@ namespace Smartstore.Core.Content.Media { - internal class DefaultMediaDupeDetector : MediaDupeDetectorBase + internal class DefaultMediaDupeDetector(IMediaSearcher searcher, int folderId, int fileCount) : MediaDupeDetectorBase { const int MaxCachedFileNames = 40000; - private readonly IMediaSearcher _searcher; - private readonly int _folderId; - private readonly int _fileCount; + private readonly IMediaSearcher _searcher = searcher; + private readonly int _folderId = folderId; + private readonly int _fileCount = fileCount; private HashSet _cachedFileNames; - public DefaultMediaDupeDetector(IMediaSearcher searcher, int folderId, int fileCount) - { - _searcher = searcher; - _folderId = folderId; - _fileCount = fileCount; - } - public override Task DetectFileAsync(string fileName, CancellationToken cancelToken = default) { if (fileName.IsEmpty()) diff --git a/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorBase.cs b/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorBase.cs index f3a24873f5..daeaa25b7e 100644 --- a/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorBase.cs +++ b/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorBase.cs @@ -31,9 +31,6 @@ protected string GetUniqueFileName(string title, string extension, ICollection _checkedNames.Clear(); } } diff --git a/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorFactory.cs b/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorFactory.cs index 662f08ea87..6004eed8d1 100644 --- a/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorFactory.cs +++ b/src/Smartstore.Core/Content/Media/DupeDetectors/MediaDupeDetectorFactory.cs @@ -16,19 +16,13 @@ public interface IMediaDupeDetectorFactory IMediaDupeDetector GetDetector(int folderId); } - public partial class MediaDupeDetectorFactory : IMediaDupeDetectorFactory + public partial class MediaDupeDetectorFactory(IMediaSearcher searcher, PerformanceSettings performanceSettings) : IMediaDupeDetectorFactory { - private readonly IMediaSearcher _searcher; - private readonly PerformanceSettings _performanceSettings; + private readonly IMediaSearcher _searcher = searcher; + private readonly PerformanceSettings _performanceSettings = performanceSettings; private readonly Dictionary _detectors = []; - public MediaDupeDetectorFactory(IMediaSearcher searcher, PerformanceSettings performanceSettings) - { - _searcher = searcher; - _performanceSettings = performanceSettings; - } - public IMediaDupeDetector GetDetector(int folderId) { Guard.NotZero(folderId); diff --git a/src/Smartstore.Core/Content/Media/Extensions/IFolderServiceExtensions.cs b/src/Smartstore.Core/Content/Media/Extensions/IFolderServiceExtensions.cs index 4be76eeaf4..f7134fe33c 100644 --- a/src/Smartstore.Core/Content/Media/Extensions/IFolderServiceExtensions.cs +++ b/src/Smartstore.Core/Content/Media/Extensions/IFolderServiceExtensions.cs @@ -8,44 +8,33 @@ public static class IFolderServiceExtensions /// Finds the folder node for a given object. /// /// The found folder node or null. - public static TreeNode FindNode(this IFolderService service, MediaFile mediaFile) - { - return service.GetNodeById(mediaFile?.FolderId ?? 0); - } + public static TreeNode FindNode(this IFolderService service, MediaFile mediaFile) => + service.GetNodeById(mediaFile?.FolderId ?? 0); /// /// Finds the root album node for a given object. /// /// The found album node or null. - public static TreeNode FindAlbum(this IFolderService service, MediaFile mediaFile) - { - return FindNode(service, mediaFile)?.Closest(x => x.Value.IsAlbum); - } + public static TreeNode FindAlbum(this IFolderService service, MediaFile mediaFile) => + FindNode(service, mediaFile)?.Closest(x => x.Value.IsAlbum); /// /// Finds the root album node for a given folder id. /// /// The found album node or null. - public static TreeNode FindAlbum(this IFolderService service, int folderId) - { - return service.GetNodeById(folderId)?.Closest(x => x.Value.IsAlbum); - } + public static TreeNode FindAlbum(this IFolderService service, int folderId) => + service.GetNodeById(folderId)?.Closest(x => x.Value.IsAlbum); /// /// Checks whether all passed files are contained in the same album. /// - public static bool AreInSameAlbum(this IFolderService service, params MediaFile[] files) - { - return files.Select(x => FindAlbum(service, x)).Distinct().Count() <= 1; - } + public static bool AreInSameAlbum(this IFolderService service, params MediaFile[] files) => files.Select(x => FindAlbum(service, x)).Distinct().Count() <= 1; /// /// Checks whether all passed folder ids are children of the same album. /// - public static bool AreInSameAlbum(this IFolderService service, params int[] folderIds) - { - return folderIds.Select(x => FindAlbum(service, x)).Distinct().Count() <= 1; - } + public static bool AreInSameAlbum(this IFolderService service, params int[] folderIds) => + folderIds.Select(x => FindAlbum(service, x)).Distinct().Count() <= 1; public static IEnumerable GetNodesFlattened(this IFolderService service, string path, bool includeSelf = true) { diff --git a/src/Smartstore.Core/Content/Media/Extensions/IMediaServiceExtensions.cs b/src/Smartstore.Core/Content/Media/Extensions/IMediaServiceExtensions.cs index 0d55e8592e..201029a2a8 100644 --- a/src/Smartstore.Core/Content/Media/Extensions/IMediaServiceExtensions.cs +++ b/src/Smartstore.Core/Content/Media/Extensions/IMediaServiceExtensions.cs @@ -7,16 +7,12 @@ namespace Smartstore.Core.Content.Media public static class IMediaServiceExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task SearchFilesAsync(this IMediaService service, MediaSearchQuery query, MediaLoadFlags flags = MediaLoadFlags.AsNoTracking) - { - return await service.SearchFilesAsync(query, null, flags); - } + public static async Task SearchFilesAsync(this IMediaService service, MediaSearchQuery query, MediaLoadFlags flags = MediaLoadFlags.AsNoTracking) => + await service.SearchFilesAsync(query, null, flags); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task GetUrlAsync(this IMediaService service, int? fileId, ProcessImageQuery imageQuery, string host = null, bool doFallback = true) - { - return service.GetUrl(await service.GetFileByIdAsync(fileId ?? 0, MediaLoadFlags.AsNoTracking), imageQuery, host, doFallback); - } + public static async Task GetUrlAsync(this IMediaService service, int? fileId, ProcessImageQuery imageQuery, string host = null, bool doFallback = true) => + service.GetUrl(await service.GetFileByIdAsync(fileId ?? 0, MediaLoadFlags.AsNoTracking), imageQuery, host, doFallback); public static async Task GetUrlAsync(this IMediaService service, int? fileId, int thumbnailSize, string host = null, bool doFallback = true) { diff --git a/src/Smartstore.Core/Content/Media/Extensions/MediaDisplayHelperExtensions.cs b/src/Smartstore.Core/Content/Media/Extensions/MediaDisplayHelperExtensions.cs index 07718f332e..89e47052c3 100644 --- a/src/Smartstore.Core/Content/Media/Extensions/MediaDisplayHelperExtensions.cs +++ b/src/Smartstore.Core/Content/Media/Extensions/MediaDisplayHelperExtensions.cs @@ -11,9 +11,8 @@ public class FileManagerUrlRequested public static class MediaDisplayHelperExtensions { - public static string GetFileManagerUrl(this IDisplayHelper displayHelper) - { - return displayHelper.HttpContext.GetItem("FileManagerUrl", () => + public static string GetFileManagerUrl(this IDisplayHelper displayHelper) => + displayHelper.HttpContext.GetItem("FileManagerUrl", () => { var urlHelper = displayHelper.Resolve(); var defaultUrl = urlHelper.Action("Index", "RoxyFileManager", new { area = "Admin" }); @@ -27,6 +26,6 @@ public static string GetFileManagerUrl(this IDisplayHelper displayHelper) return message.Url ?? defaultUrl; }); - } + } } diff --git a/src/Smartstore.Core/Content/Media/FileBatchSource.cs b/src/Smartstore.Core/Content/Media/FileBatchSource.cs index ff0a998d5f..f3c0cb3537 100644 --- a/src/Smartstore.Core/Content/Media/FileBatchSource.cs +++ b/src/Smartstore.Core/Content/Media/FileBatchSource.cs @@ -6,17 +6,13 @@ namespace Smartstore.Core.Content.Media { - public class FileBatchSource : Disposable + public class FileBatchSource(MediaStorageItem source) : Disposable { - public FileBatchSource(MediaStorageItem source) - { - Source = Guard.NotNull(source); - } /// /// The file source as . /// - public MediaStorageItem Source { get; } + public MediaStorageItem Source { get; } = Guard.NotNull(source); /// /// Name of file including extension. diff --git a/src/Smartstore.Core/Content/Media/Filters/MaxMediaFileSizeAttribute.cs b/src/Smartstore.Core/Content/Media/Filters/MaxMediaFileSizeAttribute.cs index ecb58e3a3e..a44695e638 100644 --- a/src/Smartstore.Core/Content/Media/Filters/MaxMediaFileSizeAttribute.cs +++ b/src/Smartstore.Core/Content/Media/Filters/MaxMediaFileSizeAttribute.cs @@ -12,25 +12,16 @@ public sealed class MaxMediaFileSizeAttribute : TypeFilterAttribute private readonly long? _maxSize; public MaxMediaFileSizeAttribute() - : base(typeof(MaxMediaFileSizeFilter)) - { - Arguments = new object[] { this }; - } + : base(typeof(MaxMediaFileSizeFilter)) => Arguments = new object[] { this }; /// /// Overrides the the maximum allowed size (in KB) of an uploaded media file for a particular action. /// If null, uses . /// public MaxMediaFileSizeAttribute(long maxSize) - : this() - { - _maxSize = maxSize; - } + : this() => _maxSize = maxSize; - internal long? MaxUploadFileSize - { - get => _maxSize; - } + internal long? MaxUploadFileSize => _maxSize; class MaxMediaFileSizeFilter : IAuthorizationFilter, IRequestFormLimitsPolicy { diff --git a/src/Smartstore.Core/Content/Media/Handlers/ImageHandler.cs b/src/Smartstore.Core/Content/Media/Handlers/ImageHandler.cs index 6b86d4fb92..a0c5fda746 100644 --- a/src/Smartstore.Core/Content/Media/Handlers/ImageHandler.cs +++ b/src/Smartstore.Core/Content/Media/Handlers/ImageHandler.cs @@ -2,20 +2,15 @@ namespace Smartstore.Core.Content.Media { - public class ImageHandler : ImageHandlerBase + public class ImageHandler( + IImageProcessor imageProcessor, + IImageCache imageCache, + MediaExceptionFactory exceptionFactory) : ImageHandlerBase(imageCache, exceptionFactory) { - private readonly IImageProcessor _imageProcessor; + private readonly IImageProcessor _imageProcessor = imageProcessor; - public ImageHandler(IImageProcessor imageProcessor, IImageCache imageCache, MediaExceptionFactory exceptionFactory) - : base(imageCache, exceptionFactory) - { - _imageProcessor = imageProcessor; - } - - protected override bool IsProcessable(MediaHandlerContext context) - { - return context.ImageQuery.NeedsProcessing(true) && _imageProcessor.Factory.IsSupportedImage(context.PathData.Extension); - } + protected override bool IsProcessable(MediaHandlerContext context) => + context.ImageQuery.NeedsProcessing(true) && _imageProcessor.Factory.IsSupportedImage(context.PathData.Extension); protected override async Task ProcessImageAsync(MediaHandlerContext context, CachedImage cachedImage, Stream inputStream) { diff --git a/src/Smartstore.Core/Content/Media/Hooks/ImageOffloaderHook.cs b/src/Smartstore.Core/Content/Media/Hooks/ImageOffloaderHook.cs index 07417196be..e9c4aeeb24 100644 --- a/src/Smartstore.Core/Content/Media/Hooks/ImageOffloaderHook.cs +++ b/src/Smartstore.Core/Content/Media/Hooks/ImageOffloaderHook.cs @@ -8,23 +8,16 @@ namespace Smartstore.Core.Content.Media.Hooks { - internal class ImageOffloaderHook : AsyncDbSaveHook + internal class ImageOffloaderHook( + Lazy imageOffloader, + Lazy db, + MediaSettings mediaSettings) : AsyncDbSaveHook { - private readonly Lazy _imageOffloader; - private readonly Lazy _db; - private readonly MediaSettings _mediaSettings; + private readonly Lazy _imageOffloader = imageOffloader; + private readonly Lazy _db = db; + private readonly MediaSettings _mediaSettings = mediaSettings; private readonly HashSet _toProcess = new(); - public ImageOffloaderHook( - Lazy imageOffloader, - Lazy db, - MediaSettings mediaSettings) - { - _imageOffloader = imageOffloader; - _db = db; - _mediaSettings = mediaSettings; - } - private static bool IsValidEntry(IHookedEntity entry) { if (entry.InitialState == EntityState.Deleted) @@ -147,15 +140,12 @@ private static string GetDescriptionPropName(Type entityType) } } - private static string GetEntityTag(BaseEntity entity) + private static string GetEntityTag(BaseEntity entity) => entity switch { - return entity switch - { - Product x => "p" + x.Id.ToStringInvariant(), - Category x => "c" + x.Id.ToStringInvariant(), - Manufacturer x => "m" + x.Id.ToStringInvariant(), - _ => "t" + entity.Id.ToStringInvariant() - }; - } + Product x => "p" + x.Id.ToStringInvariant(), + Category x => "c" + x.Id.ToStringInvariant(), + Manufacturer x => "m" + x.Id.ToStringInvariant(), + _ => "t" + entity.Id.ToStringInvariant() + }; } } diff --git a/src/Smartstore.Core/Content/Media/IDownloadService.cs b/src/Smartstore.Core/Content/Media/IDownloadService.cs index d4b653d4df..dface5609f 100644 --- a/src/Smartstore.Core/Content/Media/IDownloadService.cs +++ b/src/Smartstore.Core/Content/Media/IDownloadService.cs @@ -36,9 +36,7 @@ public interface IDownloadService public static class IDownloadServiceExtensions { - public static bool IsLicenseDownloadAllowed(this IDownloadService service, OrderItem orderItem) - { - return service.IsDownloadAllowed(orderItem) && orderItem?.LicenseDownloadId > 0; - } + public static bool IsLicenseDownloadAllowed(this IDownloadService service, OrderItem orderItem) => + service.IsDownloadAllowed(orderItem) && orderItem?.LicenseDownloadId > 0; } } \ No newline at end of file diff --git a/src/Smartstore.Core/Content/Media/Icons/IconExplorer.cs b/src/Smartstore.Core/Content/Media/Icons/IconExplorer.cs index 239f5336b0..902e0d4d7d 100644 --- a/src/Smartstore.Core/Content/Media/Icons/IconExplorer.cs +++ b/src/Smartstore.Core/Content/Media/Icons/IconExplorer.cs @@ -15,18 +15,13 @@ public interface IIconExplorer IEnumerable FindIcons(string searchTerm, bool relaxed = false); } - public class IconExplorer : IIconExplorer + public class IconExplorer(IApplicationContext appContext) : IIconExplorer { private IDictionary _icons; private readonly Multimap _searchMap = new(StringComparer.OrdinalIgnoreCase, x => new HashSet(x)); private readonly object _lock = new(); - private readonly IApplicationContext _appContext; - - public IconExplorer(IApplicationContext appContext) - { - _appContext = appContext; - } + private readonly IApplicationContext _appContext = appContext; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Content/Media/Imaging/CachedImage.cs b/src/Smartstore.Core/Content/Media/Imaging/CachedImage.cs index ef2b09ccc0..0eba138c10 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/CachedImage.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/CachedImage.cs @@ -10,21 +10,16 @@ namespace Smartstore.Core.Content.Media.Imaging /// An instance of this object is always returned, even when /// the requested image does not physically exists in the storage. /// - public class CachedImage + public class CachedImage(IFile file) { private bool? _exists; private string _mimeType; private Size? _size; - public CachedImage(IFile file) - { - File = Guard.NotNull(file, nameof(file)); - } - /// /// The abstracted file object /// - public IFile File { get; internal set; } + public IFile File { get; internal set; } = Guard.NotNull(file, nameof(file)); /// /// true when the image exists in the cache, false otherwise. diff --git a/src/Smartstore.Core/Content/Media/Imaging/DefaultImageProcessor.cs b/src/Smartstore.Core/Content/Media/Imaging/DefaultImageProcessor.cs index fc091d304c..b8d109f54f 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/DefaultImageProcessor.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/DefaultImageProcessor.cs @@ -7,23 +7,19 @@ namespace Smartstore.Core.Content.Media.Imaging { - public class DefaultImageProcessor : IImageProcessor + public class DefaultImageProcessor( + IImageFactory imageFactory, + IEventPublisher eventPublisher, + MediaSettings mediaSettings) : IImageProcessor { private static long _totalProcessingTime; - private readonly IEventPublisher _eventPublisher; - private readonly MediaSettings _mediaSettings; - - public DefaultImageProcessor(IImageFactory imageFactory, IEventPublisher eventPublisher, MediaSettings mediaSettings) - { - Factory = imageFactory; - _eventPublisher = eventPublisher; - _mediaSettings = mediaSettings; - } + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly MediaSettings _mediaSettings = mediaSettings; public ILogger Logger { get; set; } = NullLogger.Instance; - public IImageFactory Factory { get; } + public IImageFactory Factory { get; } = imageFactory; public async Task ProcessImageAsync(ProcessImageQuery query, bool disposeOutput = true) { diff --git a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessedEvent.cs b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessedEvent.cs index 64cee65ac4..a4595d93df 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessedEvent.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessedEvent.cs @@ -3,15 +3,9 @@ /// /// Published after processing finishes. /// - public class ImageProcessedEvent + public class ImageProcessedEvent(ProcessImageQuery query, ProcessImageResult result) { - public ImageProcessedEvent(ProcessImageQuery query, ProcessImageResult result) - { - Query = query; - Result = result; - } - - public ProcessImageQuery Query { get; private set; } - public ProcessImageResult Result { get; private set; } + public ProcessImageQuery Query { get; private set; } = query; + public ProcessImageResult Result { get; private set; } = result; } } diff --git a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessingEvent.cs b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessingEvent.cs index ebdd91e8c3..d1ca9c9660 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessingEvent.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageProcessingEvent.cs @@ -5,15 +5,9 @@ namespace Smartstore.Core.Content.Media.Imaging /// /// Published before processing begins, but after the source has been loaded. /// - public class ImageProcessingEvent + public class ImageProcessingEvent(ProcessImageQuery query, IImage image) { - public ImageProcessingEvent(ProcessImageQuery query, IImage image) - { - Query = query; - Image = image; - } - - public ProcessImageQuery Query { get; private set; } - public IImage Image { get; private set; } + public ProcessImageQuery Query { get; private set; } = query; + public IImage Image { get; private set; } = image; } } diff --git a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageQueryCreatedEvent.cs b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageQueryCreatedEvent.cs index 217b802dc8..1ce754b078 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageQueryCreatedEvent.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageQueryCreatedEvent.cs @@ -7,19 +7,15 @@ namespace Smartstore.Core.Content.Media.Imaging /// by the media middleware with data from HttpContent.Request.QueryString. /// This event implies that a thumbnail is about to be created. /// - public class ImageQueryCreatedEvent + public class ImageQueryCreatedEvent( + ProcessImageQuery query, + HttpContext httpContext, + string mimeType, + string extension) { - public ImageQueryCreatedEvent(ProcessImageQuery query, HttpContext httpContext, string mimeType, string extension) - { - Query = query; - HttpContext = httpContext; - MimeType = mimeType; - Extension = extension; - } - - public ProcessImageQuery Query { get; init; } - public HttpContext HttpContext { get; init; } - public string MimeType { get; init; } - public string Extension { get; init; } + public ProcessImageQuery Query { get; init; } = query; + public HttpContext HttpContext { get; init; } = httpContext; + public string MimeType { get; init; } = mimeType; + public string Extension { get; init; } = extension; } } \ No newline at end of file diff --git a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageUploadedEvent.cs b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageUploadedEvent.cs index afde87b403..b38ac218b4 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/Events/ImageUploadedEvent.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/Events/ImageUploadedEvent.cs @@ -11,23 +11,18 @@ namespace Smartstore.Core.Content.Media.Imaging /// /// A subscriber should NOT resize the image. But if you do - and you shouldn't :-) - , don't forget to set . /// - public class ImageUploadedEvent + public class ImageUploadedEvent(ProcessImageQuery query, IImageInfo info) { - public ImageUploadedEvent(ProcessImageQuery query, IImageInfo info) - { - Query = Guard.NotNull(query); - Info = Guard.NotNull(info); - } /// /// Contains the source (as byte[], Stream or path string), max size, format and default image quality instructions. /// - public ProcessImageQuery Query { get; } + public ProcessImageQuery Query { get; } = Guard.NotNull(query); /// /// Info/metadata of uploaded image. /// - public IImageInfo Info { get; } + public IImageInfo Info { get; } = Guard.NotNull(info); /// /// The processing result. If null, the original data diff --git a/src/Smartstore.Core/Content/Media/Imaging/Events/MediaSavedEvent.cs b/src/Smartstore.Core/Content/Media/Imaging/Events/MediaSavedEvent.cs index 179c4dc9ea..72532e55c0 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/Events/MediaSavedEvent.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/Events/MediaSavedEvent.cs @@ -3,22 +3,17 @@ /// /// Will be fired after a media upload has been saved. /// - public class MediaSavedEvent + public class MediaSavedEvent(MediaFileInfo mediaFileInfo, string entityType) { - public MediaSavedEvent(MediaFileInfo mediaFileInfo, string entityType) - { - MediaFileInfo = Guard.NotNull(mediaFileInfo); - EntityType = entityType; - } /// /// The media file info of the saved image. /// - public MediaFileInfo MediaFileInfo { get; } + public MediaFileInfo MediaFileInfo { get; } = Guard.NotNull(mediaFileInfo); /// /// The type of the entity that the image belongs to. /// - public string EntityType { get; } + public string EntityType { get; } = entityType; } } \ No newline at end of file diff --git a/src/Smartstore.Core/Content/Media/Imaging/ImageCache.cs b/src/Smartstore.Core/Content/Media/Imaging/ImageCache.cs index 488f7a664b..202e1bbd3c 100644 --- a/src/Smartstore.Core/Content/Media/Imaging/ImageCache.cs +++ b/src/Smartstore.Core/Content/Media/Imaging/ImageCache.cs @@ -3,21 +3,14 @@ namespace Smartstore.Core.Content.Media.Imaging { - public class ImageCache : IImageCache + public class ImageCache(MediaSettings mediaSettings, IMediaFileSystem fileSystem) : IImageCache { public const string IdFormatString = "0000000"; internal const int MaxDirLength = 4; - private readonly MediaSettings _mediaSettings; - private readonly IMediaFileSystem _fileSystem; - private readonly string _thumbsRootDir; - - public ImageCache(MediaSettings mediaSettings, IMediaFileSystem fileSystem) - { - _mediaSettings = mediaSettings; - _fileSystem = fileSystem; - _thumbsRootDir = "Thumbs/"; - } + private readonly MediaSettings _mediaSettings = mediaSettings; + private readonly IMediaFileSystem _fileSystem = fileSystem; + private readonly string _thumbsRootDir = "Thumbs/"; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Content/Media/MediaExceptionFactory.cs b/src/Smartstore.Core/Content/Media/MediaExceptionFactory.cs index d05808e408..192053a375 100644 --- a/src/Smartstore.Core/Content/Media/MediaExceptionFactory.cs +++ b/src/Smartstore.Core/Content/Media/MediaExceptionFactory.cs @@ -74,30 +74,17 @@ public class MediaExceptionFactory { public Localizer T { get; set; } = NullLocalizer.Instance; - public MediaFileNotFoundException FileNotFound(string path) - { - return new MediaFileNotFoundException(T("Admin.Media.Exception.FileNotFound", path)); - } + public MediaFileNotFoundException FileNotFound(string path) => new MediaFileNotFoundException(T("Admin.Media.Exception.FileNotFound", path)); - public MediaFolderNotFoundException FolderNotFound(string path) - { - return new MediaFolderNotFoundException(T("Admin.Media.Exception.FolderNotFound", path)); - } + public MediaFolderNotFoundException FolderNotFound(string path) => new MediaFolderNotFoundException(T("Admin.Media.Exception.FolderNotFound", path)); - public DuplicateMediaFileException DuplicateFile(string fullPath, MediaFileInfo dupeFile, string uniquePath) - { - return new DuplicateMediaFileException(T("Admin.Media.Exception.DuplicateFile", fullPath), dupeFile, uniquePath); - } + public DuplicateMediaFileException DuplicateFile(string fullPath, MediaFileInfo dupeFile, string uniquePath) => new DuplicateMediaFileException(T("Admin.Media.Exception.DuplicateFile", fullPath), dupeFile, uniquePath); public DuplicateMediaFolderException DuplicateFolder(string fullPath, MediaFolderNode dupeFolder) - { - return new DuplicateMediaFolderException(T("Admin.Media.Exception.DuplicateFolder", fullPath), dupeFolder); - } + => new DuplicateMediaFolderException(T("Admin.Media.Exception.DuplicateFolder", fullPath), dupeFolder); public NotSameAlbumException NotSameAlbum(string sourcePath, string destPath) - { - return new NotSameAlbumException(T("Admin.Media.Exception.NotSameAlbum", sourcePath, destPath)); - } + => new NotSameAlbumException(T("Admin.Media.Exception.NotSameAlbum", sourcePath, destPath)); public DeniedMediaTypeException DeniedMediaType(string fileName, string currentType, string[] acceptedTypes = null) { @@ -112,9 +99,7 @@ public DeniedMediaTypeException DeniedMediaType(string fileName, string currentT } public ExtractThumbnailException ExtractThumbnail(string path, string reason = null) - { - return new ExtractThumbnailException(T("Admin.Media.Exception.ExtractThumbnail", path, reason.NaIfEmpty())); - } + => new ExtractThumbnailException(T("Admin.Media.Exception.ExtractThumbnail", path, reason.NaIfEmpty())); public ExtractThumbnailException ExtractThumbnail(string path, Exception innerException) { @@ -123,13 +108,7 @@ public ExtractThumbnailException ExtractThumbnail(string path, Exception innerEx } public MaxMediaFileSizeExceededException MaxFileSizeExceeded(string fileName, long fileSize, long maxSize) - { - return new MaxMediaFileSizeExceededException(T( - "Admin.Media.Exception.MaxFileSizeExceeded", - fileName.NaIfEmpty(), - Prettifier.HumanizeBytes(fileSize), - Prettifier.HumanizeBytes(maxSize))); - } + => new MaxMediaFileSizeExceededException(T("Admin.Media.Exception.MaxFileSizeExceeded", fileName.NaIfEmpty(), Prettifier.HumanizeBytes(fileSize), Prettifier.HumanizeBytes(maxSize))); public DeleteTrackedFileException DeleteTrackedFile(MediaFile file, Exception innerException) { diff --git a/src/Smartstore.Core/Content/Media/MediaHelper.cs b/src/Smartstore.Core/Content/Media/MediaHelper.cs index 2aed392190..3f3a2e4c2f 100644 --- a/src/Smartstore.Core/Content/Media/MediaHelper.cs +++ b/src/Smartstore.Core/Content/Media/MediaHelper.cs @@ -1,6 +1,6 @@ namespace Smartstore.Core.Content.Media { - public partial class MediaHelper + public partial class MediaHelper(IFolderService folderService) { #region Static @@ -70,12 +70,7 @@ public static bool CheckUniqueFileName(string title, string ext, ICollection _matchers = new(3); - public MediaLegacyMiddleware(RequestDelegate next, IMediaStorageConfiguration mediaStorageConfiguration) - { + public MediaLegacyMiddleware(RequestDelegate next, IMediaStorageConfiguration mediaStorageConfiguration) => _matchers.AddRange(BuildTemplateMatchers(mediaStorageConfiguration.PublicPath)); - } private static IEnumerable BuildTemplateMatchers(string publicPath) { diff --git a/src/Smartstore.Core/Content/Media/MediaService.cs b/src/Smartstore.Core/Content/Media/MediaService.cs index 718213da11..58c6998589 100644 --- a/src/Smartstore.Core/Content/Media/MediaService.cs +++ b/src/Smartstore.Core/Content/Media/MediaService.cs @@ -16,57 +16,38 @@ namespace Smartstore.Core.Content.Media { - public partial class MediaService : IMediaService + public partial class MediaService( + SmartDbContext db, + IFolderService folderService, + IMediaSearcher searcher, + IMediaTypeResolver typeResolver, + IMediaUrlGenerator urlGenerator, + IEventPublisher eventPublisher, + ILanguageService languageService, + ILocalizedEntityService localizedEntityService, + MediaSettings mediaSettings, + IImageProcessor imageProcessor, + IImageCache imageCache, + MediaExceptionFactory exceptionFactory, + IMediaDupeDetectorFactory dupeDetectorFactory, + Func storageProvider, + MediaHelper helper) : IMediaService { - private readonly SmartDbContext _db; - private readonly IFolderService _folderService; - private readonly IMediaSearcher _searcher; - private readonly IMediaTypeResolver _typeResolver; - private readonly IMediaUrlGenerator _urlGenerator; - private readonly IEventPublisher _eventPublisher; - private readonly ILanguageService _languageService; - private readonly ILocalizedEntityService _localizedEntityService; - private readonly MediaSettings _mediaSettings; - private readonly IImageProcessor _imageProcessor; - private readonly IImageCache _imageCache; - private readonly MediaExceptionFactory _exceptionFactory; - private readonly IMediaDupeDetectorFactory _dupeDetectorFactory; - private readonly IMediaStorageProvider _storageProvider; - private readonly MediaHelper _helper; - - public MediaService( - SmartDbContext db, - IFolderService folderService, - IMediaSearcher searcher, - IMediaTypeResolver typeResolver, - IMediaUrlGenerator urlGenerator, - IEventPublisher eventPublisher, - ILanguageService languageService, - ILocalizedEntityService localizedEntityService, - MediaSettings mediaSettings, - IImageProcessor imageProcessor, - IImageCache imageCache, - MediaExceptionFactory exceptionFactory, - IMediaDupeDetectorFactory dupeDetectorFactory, - Func storageProvider, - MediaHelper helper) - { - _db = db; - _folderService = folderService; - _searcher = searcher; - _typeResolver = typeResolver; - _urlGenerator = urlGenerator; - _eventPublisher = eventPublisher; - _languageService = languageService; - _localizedEntityService = localizedEntityService; - _mediaSettings = mediaSettings; - _imageProcessor = imageProcessor; - _imageCache = imageCache; - _exceptionFactory = exceptionFactory; - _dupeDetectorFactory = dupeDetectorFactory; - _storageProvider = storageProvider(); - _helper = helper; - } + private readonly SmartDbContext _db = db; + private readonly IFolderService _folderService = folderService; + private readonly IMediaSearcher _searcher = searcher; + private readonly IMediaTypeResolver _typeResolver = typeResolver; + private readonly IMediaUrlGenerator _urlGenerator = urlGenerator; + private readonly IEventPublisher _eventPublisher = eventPublisher; + private readonly ILanguageService _languageService = languageService; + private readonly ILocalizedEntityService _localizedEntityService = localizedEntityService; + private readonly MediaSettings _mediaSettings = mediaSettings; + private readonly IImageProcessor _imageProcessor = imageProcessor; + private readonly IImageCache _imageCache = imageCache; + private readonly MediaExceptionFactory _exceptionFactory = exceptionFactory; + private readonly IMediaDupeDetectorFactory _dupeDetectorFactory = dupeDetectorFactory; + private readonly IMediaStorageProvider _storageProvider = storageProvider(); + private readonly MediaHelper _helper = helper; public Localizer T { get; set; } = NullLocalizer.Instance; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Content/Media/MediaServiceFileSystemAdapter.cs b/src/Smartstore.Core/Content/Media/MediaServiceFileSystemAdapter.cs index 28227674b5..177ea7c060 100644 --- a/src/Smartstore.Core/Content/Media/MediaServiceFileSystemAdapter.cs +++ b/src/Smartstore.Core/Content/Media/MediaServiceFileSystemAdapter.cs @@ -10,38 +10,26 @@ namespace Smartstore.Core.Content.Media /// /// A media service implementation that emulates file system. /// - public partial class MediaServiceFileSystemAdapter : FileSystemBase, IMediaFileSystem + public partial class MediaServiceFileSystemAdapter( + IMediaService mediaService, + IMediaSearcher mediaSearcher, + IFolderService folderService, + IMediaStorageConfiguration storageConfig, + MediaHelper mediaHelper, + MediaExceptionFactory exceptionFactory) : FileSystemBase, IMediaFileSystem { - private readonly IMediaService _mediaService; - private readonly IMediaSearcher _mediaSearcher; - private readonly IFolderService _folderService; - private readonly MediaHelper _mediaHelper; - private readonly IMediaStorageProvider _storageProvider; - private readonly MediaExceptionFactory _exceptionFactory; - private readonly string _mediaRootPath; - - public MediaServiceFileSystemAdapter( - IMediaService mediaService, - IMediaSearcher mediaSearcher, - IFolderService folderService, - IMediaStorageConfiguration storageConfig, - MediaHelper mediaHelper, - MediaExceptionFactory exceptionFactory) - { - _mediaService = mediaService; - _mediaSearcher = mediaSearcher; - _folderService = folderService; - _mediaHelper = mediaHelper; - _storageProvider = mediaService.StorageProvider; - _exceptionFactory = exceptionFactory; - _mediaRootPath = storageConfig.PublicPath; - StorageConfiguration = storageConfig; - } + private readonly IMediaService _mediaService = mediaService; + private readonly IMediaSearcher _mediaSearcher = mediaSearcher; + private readonly IFolderService _folderService = folderService; + private readonly MediaHelper _mediaHelper = mediaHelper; + private readonly IMediaStorageProvider _storageProvider = mediaService.StorageProvider; + private readonly MediaExceptionFactory _exceptionFactory = exceptionFactory; + private readonly string _mediaRootPath = storageConfig.PublicPath; protected string Fix(string path) => path.Replace('\\', '/'); - public IMediaStorageConfiguration StorageConfiguration { get; } + public IMediaStorageConfiguration StorageConfiguration { get; } = storageConfig; public bool IsCloudStorage => _storageProvider.IsCloudStorage; diff --git a/src/Smartstore.Core/Content/Media/MediaTypes/MediaTypeResolver.cs b/src/Smartstore.Core/Content/Media/MediaTypes/MediaTypeResolver.cs index da875fb405..f16ecff814 100644 --- a/src/Smartstore.Core/Content/Media/MediaTypes/MediaTypeResolver.cs +++ b/src/Smartstore.Core/Content/Media/MediaTypes/MediaTypeResolver.cs @@ -7,12 +7,12 @@ namespace Smartstore.Core.Content.Media { - public partial class MediaTypeResolver : AsyncDbSaveHook, IMediaTypeResolver + public partial class MediaTypeResolver(ICacheManager cache, MediaSettings mediaSettings) : AsyncDbSaveHook, IMediaTypeResolver { const string MapCacheKey = "media:exttypemap"; - private readonly ICacheManager _cache; - private readonly MediaSettings _mediaSettings; + private readonly ICacheManager _cache = cache; + private readonly MediaSettings _mediaSettings = mediaSettings; private static readonly HashSet _mapInvalidatorSettingKeys = new(StringComparer.OrdinalIgnoreCase) { @@ -24,12 +24,6 @@ public partial class MediaTypeResolver : AsyncDbSaveHook, IMediaTypeRes TypeHelper.NameOf(x => x.BinTypes, true) }; - public MediaTypeResolver(ICacheManager cache, MediaSettings mediaSettings) - { - _cache = cache; - _mediaSettings = mediaSettings; - } - public ILogger Logger { get; set; } = NullLogger.Instance; #region Invalidation Hook diff --git a/src/Smartstore.Core/Content/Media/Search/MediaSearcher.cs b/src/Smartstore.Core/Content/Media/Search/MediaSearcher.cs index cdc34240c5..eee8504ae8 100644 --- a/src/Smartstore.Core/Content/Media/Search/MediaSearcher.cs +++ b/src/Smartstore.Core/Content/Media/Search/MediaSearcher.cs @@ -6,16 +6,10 @@ namespace Smartstore.Core.Content.Media { - public class MediaSearcher : IMediaSearcher + public class MediaSearcher(SmartDbContext db, Work folderService) : IMediaSearcher { - private readonly SmartDbContext _db; - private readonly Work _folderService; - - public MediaSearcher(SmartDbContext db, Work folderService) - { - _db = db; - _folderService = folderService; - } + private readonly SmartDbContext _db = db; + private readonly Work _folderService = folderService; public virtual IPagedList SearchFiles(MediaSearchQuery query, MediaLoadFlags flags = MediaLoadFlags.AsNoTracking) { diff --git a/src/Smartstore.Core/Content/Media/Storage/DatabaseMediaStorageProvider.cs b/src/Smartstore.Core/Content/Media/Storage/DatabaseMediaStorageProvider.cs index 98b47ca305..f9249dee1c 100644 --- a/src/Smartstore.Core/Content/Media/Storage/DatabaseMediaStorageProvider.cs +++ b/src/Smartstore.Core/Content/Media/Storage/DatabaseMediaStorageProvider.cs @@ -10,14 +10,9 @@ namespace Smartstore.Core.Content.Media.Storage [SystemName("MediaStorage.SmartStoreDatabase")] [FriendlyName("Database")] [Order(0)] - public class DatabaseMediaStorageProvider : IMediaStorageProvider, IMediaSender, IMediaReceiver + public class DatabaseMediaStorageProvider(SmartDbContext db) : IMediaStorageProvider, IMediaSender, IMediaReceiver { - private readonly SmartDbContext _db; - - public DatabaseMediaStorageProvider(SmartDbContext db) - { - _db = db; - } + private readonly SmartDbContext _db = db; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Content/Media/Storage/FileSystemMediaStorageProvider.cs b/src/Smartstore.Core/Content/Media/Storage/FileSystemMediaStorageProvider.cs index 1ca94a923f..0ee105790f 100644 --- a/src/Smartstore.Core/Content/Media/Storage/FileSystemMediaStorageProvider.cs +++ b/src/Smartstore.Core/Content/Media/Storage/FileSystemMediaStorageProvider.cs @@ -11,20 +11,16 @@ namespace Smartstore.Core.Content.Media.Storage [SystemName("MediaStorage.SmartStoreFileSystem")] [FriendlyName("File system")] [Order(1)] - public class FileSystemMediaStorageProvider : IMediaStorageProvider, IMediaSender, IMediaReceiver + public class FileSystemMediaStorageProvider( + IMediaFileSystem fileSystem, + AsyncRunner asyncRunner) : IMediaStorageProvider, IMediaSender, IMediaReceiver { const string MediaRootPath = "Storage"; - private readonly IMediaFileSystem _fileSystem; - private readonly AsyncRunner _asyncRunner; + private readonly IMediaFileSystem _fileSystem = fileSystem; + private readonly AsyncRunner _asyncRunner = asyncRunner; private readonly Dictionary _pathCache = []; - public FileSystemMediaStorageProvider(IMediaFileSystem fileSystem, AsyncRunner asyncRunner) - { - _fileSystem = fileSystem; - _asyncRunner = asyncRunner; - } - public ILogger Logger { get; set; } = NullLogger.Instance; public static string SystemName => "MediaStorage.SmartStoreFileSystem"; diff --git a/src/Smartstore.Core/Content/Media/Storage/MediaMover.cs b/src/Smartstore.Core/Content/Media/Storage/MediaMover.cs index 851668e093..cb5380cbc3 100644 --- a/src/Smartstore.Core/Content/Media/Storage/MediaMover.cs +++ b/src/Smartstore.Core/Content/Media/Storage/MediaMover.cs @@ -7,20 +7,13 @@ namespace Smartstore.Core.Content.Media.Storage { - public class MediaMover : IMediaMover + public class MediaMover(SmartDbContext db, INotifier notifier, ISettingService settingService) : IMediaMover { private const int PAGE_SIZE = 50; - private readonly SmartDbContext _db; - private readonly INotifier _notifier; - private readonly ISettingService _settingService; - - public MediaMover(SmartDbContext db, INotifier notifier, ISettingService settingService) - { - _db = db; - _notifier = notifier; - _settingService = settingService; - } + private readonly SmartDbContext _db = db; + private readonly INotifier _notifier = notifier; + private readonly ISettingService _settingService = settingService; public Localizer T { get; set; } = NullLocalizer.Instance; public ILogger Logger { get; set; } = NullLogger.Instance; diff --git a/src/Smartstore.Core/Content/Media/Tasks/TransientMediaClearTask.cs b/src/Smartstore.Core/Content/Media/Tasks/TransientMediaClearTask.cs index 1e0f76ad7b..83db36840f 100644 --- a/src/Smartstore.Core/Content/Media/Tasks/TransientMediaClearTask.cs +++ b/src/Smartstore.Core/Content/Media/Tasks/TransientMediaClearTask.cs @@ -10,16 +10,10 @@ namespace Smartstore.Core.Content.Media.Tasks /// Represents a task for deleting transient media from the database /// (files and downloads which have been uploaded but never assigned to an entity). /// - public partial class TransientMediaClearTask : ITask + public partial class TransientMediaClearTask(SmartDbContext db, IMediaService mediaService) : ITask { - private readonly SmartDbContext _db; - private readonly IMediaService _mediaService; - - public TransientMediaClearTask(SmartDbContext db, IMediaService mediaService) - { - _db = db; - _mediaService = mediaService; - } + private readonly SmartDbContext _db = db; + private readonly IMediaService _mediaService = mediaService; public virtual async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { diff --git a/src/Smartstore.Core/Content/Media/Tracking/MediaTrackerHook.cs b/src/Smartstore.Core/Content/Media/Tracking/MediaTrackerHook.cs index 5d6891927a..52885f13b5 100644 --- a/src/Smartstore.Core/Content/Media/Tracking/MediaTrackerHook.cs +++ b/src/Smartstore.Core/Content/Media/Tracking/MediaTrackerHook.cs @@ -4,7 +4,7 @@ namespace Smartstore.Core.Content.Media { [Important] - internal sealed class MediaTrackerHook : AsyncDbSaveHook + internal sealed class MediaTrackerHook(Lazy mediaTracker) : AsyncDbSaveHook { // Track items for the current (SaveChanges) unit. private readonly HashSet _actionsUnit = new(); @@ -15,12 +15,7 @@ internal sealed class MediaTrackerHook : AsyncDbSaveHook // Entities that are not saved yet but contain effective changes. We won't track if an error occurred during save. private readonly Dictionary> _actionsTemp = new(); - private readonly Lazy _mediaTracker; - - public MediaTrackerHook(Lazy mediaTracker) - { - _mediaTracker = mediaTracker; - } + private readonly Lazy _mediaTracker = mediaTracker; internal static bool Silent { get; set; } diff --git a/src/Smartstore.Core/Content/Media/Tracking/TrackedMediaPropertyTable.cs b/src/Smartstore.Core/Content/Media/Tracking/TrackedMediaPropertyTable.cs index 3ec314df28..4e4a0486e1 100644 --- a/src/Smartstore.Core/Content/Media/Tracking/TrackedMediaPropertyTable.cs +++ b/src/Smartstore.Core/Content/Media/Tracking/TrackedMediaPropertyTable.cs @@ -4,37 +4,25 @@ public class TrackedMediaPropertyTable { private readonly IList _propertyList = new List(); - protected internal TrackedMediaPropertyTable(string album) - { - Album = album; - } + protected internal TrackedMediaPropertyTable(string album) => Album = album; - public void Register(Expression> foreignKeyProperty) where T : BaseEntity - { + public void Register(Expression> foreignKeyProperty) where T : BaseEntity => RegisterInternal(typeof(T), foreignKeyProperty.ExtractPropertyInfo().Name); - } - public void Register(Expression> foreignKeyProperty) where T : BaseEntity - { + public void Register(Expression> foreignKeyProperty) where T : BaseEntity => RegisterInternal(typeof(T), foreignKeyProperty.ExtractPropertyInfo().Name); - } internal string Album { get; set; } - private void RegisterInternal(Type entityType, string propertyName) + private void RegisterInternal(Type entityType, string propertyName) => + _propertyList.Add(new TrackedMediaProperty { - _propertyList.Add(new TrackedMediaProperty - { - Name = propertyName, - EntityType = entityType, - Album = Album, - }); - } + Name = propertyName, + EntityType = entityType, + Album = Album, + }); - internal TrackedMediaProperty[] GetProperties() - { - return _propertyList.ToArray(); - } + internal TrackedMediaProperty[] GetProperties() => _propertyList.ToArray(); } public class TrackedMediaProperty diff --git a/src/Smartstore.Core/Content/Menus/Consumers/CatalogMenuInvalidator.cs b/src/Smartstore.Core/Content/Menus/Consumers/CatalogMenuInvalidator.cs index 6d07971009..335ff14564 100644 --- a/src/Smartstore.Core/Content/Menus/Consumers/CatalogMenuInvalidator.cs +++ b/src/Smartstore.Core/Content/Menus/Consumers/CatalogMenuInvalidator.cs @@ -9,28 +9,20 @@ namespace Smartstore.Core.Content.Menus /// /// Invalidates all menus that contain the /// - internal class CatalogMenuInvalidator : IConsumer + internal class CatalogMenuInvalidator( + IMenuService menuService, + CatalogSettings catalogSettings, + ICacheManager cache, + SmartDbContext db) : IConsumer { - private readonly IMenuService _menuService; - private readonly CatalogSettings _catalogSettings; - private readonly ICacheManager _cache; - private readonly SmartDbContext _db; + private readonly IMenuService _menuService = menuService; + private readonly CatalogSettings _catalogSettings = catalogSettings; + private readonly ICacheManager _cache = cache; + private readonly SmartDbContext _db = db; private List _invalidated = new(); private List _countsResetted = new(); - public CatalogMenuInvalidator( - IMenuService menuService, - CatalogSettings catalogSettings, - ICacheManager cache, - SmartDbContext db) - { - _menuService = menuService; - _catalogSettings = catalogSettings; - _cache = cache; - _db = db; - } - public async Task HandleAsync(CategoryTreeChangedEvent eventMessage) { var affectedMenuNames = await _db.MenuItems