Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Add store-scoped payment management to Grand.Web.Store (#714)
Krzysztof Pajak0755a5017ac9
diff --git a/.github/workflows/aspnetcore.yml b/.github/workflows/aspnetcore.ymlindex 6e5b25712..f9fcb6cf7 100644--- a/.github/workflows/aspnetcore.yml+++ b/.github/workflows/aspnetcore.yml@@ -49,7 +49,11 @@ jobs:run: dotnet test ./src/Tests/Grand.Infrastructure.Tests/Grand.Infrastructure.Tests.csproj- name: Grand.SharedKernel.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.SharedKernel.Tests/Grand.SharedKernel.Tests.csproj+ - name: Grand.Mapping.Tests Unit Tests+ run: dotnet test ./src/Tests/Grand.Mapping.Tests/Grand.Mapping.Tests.csproj- name: Grand.Web.Common.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csproj- name: Grand.Web.Admin.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.Web.Admin.Tests/Grand.Web.Admin.Tests.csproj+ - name: Grand.Web.Store.Tests Unit Tests+ run: dotnet test ./src/Tests/Grand.Web.Store.Tests/Grand.Web.Store.Tests.csprojdiff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 0b647f0a3..054110238 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -8,7 +8,7 @@ on:jobs:build:name: Build and analyze- runs-on: windows-latest+ runs-on: ubuntu-lateststeps:- name: Set up JDK 17uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0@@ -18,30 +18,37 @@ jobs:- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1with:fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis+ - name: Setup .NET Core+ uses: actions/setup-dotnet@v4+ with:+ dotnet-version: 10.0.x+ - name: Install .NET Aspire workload+ run: dotnet workload install aspire- name: Cache SonarQube Cloud packagesuses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0with:- path: ~\sonar\cache+ path: ~/.sonar/cachekey: ${{ runner.os }}-sonarrestore-keys: ${{ runner.os }}-sonar- name: Cache SonarQube Cloud scannerid: cache-sonar-scanneruses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0with:- path: ${{ runner.temp }}\scanner+ path: ./.sonar/scannerkey: ${{ runner.os }}-sonar-scannerrestore-keys: ${{ runner.os }}-sonar-scanner- name: Install SonarQube Cloud scannerif: steps.cache-sonar-scanner.outputs.cache-hit != 'true'- shell: powershellrun: |- New-Item -Path ${{ runner.temp }}\scanner -ItemType Directory- dotnet tool update dotnet-sonarscanner --tool-path ${{ runner.temp }}\scanner+ mkdir -p ./.sonar/scanner+ dotnet tool update dotnet-sonarscanner --tool-path ./.sonar/scanner+ - name: Start Docker for Mongodb+ run: docker run -d -p 27017:27017 mongo- name: Build and analyzeenv:SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}- shell: powershellrun: |- ${{ runner.temp }}\scanner\dotnet-sonarscanner begin /k:"grandnode_grandnode2" /o:"grandnode" /d:sonar.token="${{ secrets.SONAR_TOKEN }}"- dotnet build- ${{ runner.temp }}\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"+ ./.sonar/scanner/dotnet-sonarscanner begin /k:"grandnode_grandnode2" /o:"grandnode" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml"+ dotnet build ./GrandNode.sln+ dotnet test ./GrandNode.sln --no-build --collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover+ ./.sonar/scanner/dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"diff --git a/GrandNode.sln b/GrandNode.slnindex c7d8738dc..3b6f0c8d0 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -1,7 +1,7 @@Microsoft Visual Studio Solution File, Format Version 12.00# Visual Studio Version 18-VisualStudioVersion = 18.5.11619.145 insiders+VisualStudioVersion = 18.5.11619.145MinimumVisualStudioVersion = 10.0.40219.1Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{FA350BD6-C29D-40D9-BA47-FE5FBDFC84A0}"EndProject@@ -149,6 +149,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Web.AdminShared", "srEndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Mapping.Tests", "src\Tests\Grand.Mapping.Tests\Grand.Mapping.Tests.csproj", "{396E6929-5365-4116-8AA8-DF5327247798}"EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"+EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{CEA09484-30F6-4D44-02F6-822E06DBC57C}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Web.Store.Tests", "src\Tests\Grand.Web.Store.Tests\Grand.Web.Store.Tests.csproj", "{5819B37B-4972-4BBC-B51C-57B0028EF869}"+EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{8D626EA8-CB54-BC41-363A-217881BEBA6E}"+EndProject+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web", "Web", "{03997797-E7F5-0643-168D-B8EA7178C2FE}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -891,6 +901,18 @@ Global{396E6929-5365-4116-8AA8-DF5327247798}.Release|x64.Build.0 = Release|Any CPU{396E6929-5365-4116-8AA8-DF5327247798}.Release|x86.ActiveCfg = Release|Any CPU{396E6929-5365-4116-8AA8-DF5327247798}.Release|x86.Build.0 = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|x64.ActiveCfg = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|x64.Build.0 = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|x86.ActiveCfg = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Debug|x86.Build.0 = Debug|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|Any CPU.Build.0 = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x64.ActiveCfg = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x64.Build.0 = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x86.ActiveCfg = Release|Any CPU+ {5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x86.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -956,6 +978,10 @@ Global{136F1E35-8B20-465C-8D42-30A5A0D0DA1F} = {583FFBBD-421C-4FB7-BBDA-F9CAF35A354A}{12C4A556-E62E-4EC0-BCD9-E9D4E1F3D430} = {BF4543A8-0731-4FDD-BB6B-0ADB9561F981}{396E6929-5365-4116-8AA8-DF5327247798} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}+ {CEA09484-30F6-4D44-02F6-822E06DBC57C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}+ {5819B37B-4972-4BBC-B51C-57B0028EF869} = {CEA09484-30F6-4D44-02F6-822E06DBC57C}+ {8D626EA8-CB54-BC41-363A-217881BEBA6E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}+ {03997797-E7F5-0643-168D-B8EA7178C2FE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {88B478F4-FD3B-4C24-9E84-4FAAF0254397}diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.csindex 526811426..b2a693a08 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs@@ -55,7 +55,8 @@ public class LoyaltyPointsService : ILoyaltyPointsServicequery = query.Where(rph => rph.CustomerId == customerId);if (!_loyaltyPointsSettings.PointsAccumulatedForAllStores)query = query.Where(rph => rph.StoreId == storeId);- query = query.OrderByDescending(rph => rph.CreatedOnUtc);+ //Id as tie-breaker - entries created within the same millisecond share CreatedOnUtc+ query = query.OrderByDescending(rph => rph.CreatedOnUtc).ThenByDescending(rph => rph.Id);var lastRph = await Task.FromResult(query.FirstOrDefault());return lastRph?.PointsBalance ?? 0;@@ -104,7 +105,7 @@ public class LoyaltyPointsService : ILoyaltyPointsService//filter by storeif (!string.IsNullOrEmpty(storeId))query = query.Where(rph => rph.StoreId == storeId);- query = query.OrderByDescending(rph => rph.CreatedOnUtc);+ query = query.OrderByDescending(rph => rph.CreatedOnUtc).ThenByDescending(rph => rph.Id);return await Task.FromResult(query.ToList());}diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.csindex 78abb1d21..0c2b91862 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs@@ -69,7 +69,7 @@ public class PaymentService : IPaymentServiceif (selectedShippingOption == null) return await Task.FromResult(pm);for (var i = pm.Count - 1; i >= 0; i--){- var restrictedGroupIds =await GetRestrictedShippingIds(pm[i]);+ var restrictedGroupIds =await GetRestrictedShippingIds(pm[i], storeId);if (restrictedGroupIds.Contains(selectedShippingOption.Name)) pm.Remove(pm[i]);}@@ -109,7 +109,7 @@ public class PaymentService : IPaymentServicevar filteredPaymentMethods = new List<IPaymentProvider>();foreach (var pm in paymentMethods){- var restrictedCountryIds = await GetRestrictedCountryIds(pm);+ var restrictedCountryIds = await GetRestrictedCountryIds(pm, storeId);if (!restrictedCountryIds.Contains(filterByCountryId)){filteredPaymentMethods.Add(pm);@@ -123,12 +123,12 @@ public class PaymentService : IPaymentService/// </summary>/// <param name="paymentMethod">Payment method</param>/// <returns>A list of country identifiers</returns>- public virtual async Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod)+ public virtual async Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod, string storeId = ""){ArgumentNullException.ThrowIfNull(paymentMethod);var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";- var restrictedCountryIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ var restrictedCountryIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey, storeId: storeId);return restrictedCountryIds == null ? new List<string>() : restrictedCountryIds.Ids;}@@ -137,12 +137,12 @@ public class PaymentService : IPaymentService/// </summary>/// <param name="paymentMethod">Payment method</param>/// <returns>A list of role identifiers</returns>- public virtual async Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod)+ public virtual async Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod, string storeId = ""){ArgumentNullException.ThrowIfNull(paymentMethod);var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";- var restrictedShippingIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ var restrictedShippingIds = await _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey, storeId: storeId);return restrictedShippingIds == null ? new List<string>() : restrictedShippingIds.Ids;}@@ -151,12 +151,12 @@ public class PaymentService : IPaymentService/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="countryIds">A list of country identifiers</param>- public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds)+ public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds, string storeId = ""){ArgumentNullException.ThrowIfNull(paymentMethod);var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";- await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds });+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds }, storeId);}/// <summary>@@ -177,12 +177,12 @@ public class PaymentService : IPaymentService/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="shippingIds">A list of country identifiers</param>- public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds)+ public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds, string storeId = ""){ArgumentNullException.ThrowIfNull(paymentMethod);var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";- await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds });+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds }, storeId);}/// <summary>diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.csindex 5f35ac822..838a1e4ea 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs@@ -42,29 +42,33 @@ public interface IPaymentService/// Gets a list of country identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>+ /// <param name="storeId">Store ident; pass "" for the global restriction</param>/// <returns>A list of country identifiers</returns>- Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod);+ Task<IList<string>> GetRestrictedCountryIds(IPaymentProvider paymentMethod, string storeId = "");/// <summary>/// Gets a list of shipping identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>+ /// <param name="storeId">Store ident; pass "" for the global restriction</param>/// <returns>A list of role identifiers</returns>- Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod);+ Task<IList<string>> GetRestrictedShippingIds(IPaymentProvider paymentMethod, string storeId = "");/// <summary>/// Saves a list of country identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="countryIds">A list of country identifiers</param>- Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds);+ /// <param name="storeId">Store ident; pass "" for the global restriction</param>+ Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds, string storeId = "");/// <summary>/// Saves a list of shipping identifiers in which a certain payment method is now allowed/// </summary>/// <param name="paymentMethod">Payment method</param>/// <param name="shippingIds">A list of shipping identifiers</param>- Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds);+ /// <param name="storeId">Store ident; pass "" for the global restriction</param>+ Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds, string storeId = "");/// <summary>/// Process a paymentdiff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.csindex 517e4a3b5..e761b10bf 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs@@ -68,6 +68,63 @@ public class PaymentServiceTests_settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);}+ [TestMethod]+ public async Task GetRestrictedCountryIds_WithStoreId_PassStoreIdToSettingService()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var expectedResult = new List<string> { "1", "2" };+ var expectedKey = "PaymentMethodRestictions.systemName";+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, "storeId"))+ .Returns(() => Task.FromResult(new PaymentRestrictedSettings { Ids = expectedResult }));++ var result = await _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object, "storeId");+ Assert.IsTrue(expectedResult.SequenceEqual(result));+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, "storeId"),+ Times.Once);+ }++ [TestMethod]+ public async Task GetRestrictedShippingIds_ReturnExpectedIds()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var expectedResult = new List<string> { "Ground", "Pickup" };+ var expectedKey = "PaymentMethodRestictionsShipping.systemName";+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))+ .Returns(() => Task.FromResult(new PaymentRestrictedSettings { Ids = expectedResult }));++ var result = await _paymentService.GetRestrictedShippingIds(_paymentProviderMock.Object);+ Assert.IsTrue(expectedResult.SequenceEqual(result));+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);+ }++ [TestMethod]+ public async Task GetRestrictedShippingIds_ReturnEmptyList()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var expectedKey = "PaymentMethodRestictionsShipping.systemName";+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))+ .Returns(() => Task.FromResult((PaymentRestrictedSettings)null));++ var result = await _paymentService.GetRestrictedShippingIds(_paymentProviderMock.Object);+ Assert.IsEmpty(result);+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);+ }++ [TestMethod]+ public async Task GetRestrictedShippingIds_WithStoreId_PassStoreIdToSettingService()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var expectedResult = new List<string> { "Ground" };+ var expectedKey = "PaymentMethodRestictionsShipping.systemName";+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, "storeId"))+ .Returns(() => Task.FromResult(new PaymentRestrictedSettings { Ids = expectedResult }));++ var result = await _paymentService.GetRestrictedShippingIds(_paymentProviderMock.Object, "storeId");+ Assert.IsTrue(expectedResult.SequenceEqual(result));+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, "storeId"),+ Times.Once);+ }+[TestMethod]public async Task SaveRestictedCountryIds_InvokeSettingsService(){@@ -81,6 +138,62 @@ public class PaymentServiceTestsTimes.Once);}+ [TestMethod]+ public async Task SaveRestictedCountryIds_WithStoreId_SaveSettingForStore()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var countryIds = new List<string> { "1", "2" };+ var expectedKey = "PaymentMethodRestictions.systemName";++ await _paymentService.SaveRestrictedCountryIds(_paymentProviderMock.Object, countryIds, "storeId");+ _settingService.Verify(+ s => s.SetSetting(expectedKey,+ It.Is<PaymentRestrictedSettings>(x => x.Ids.SequenceEqual(countryIds)), "storeId"),+ Times.Once);+ }++ [TestMethod]+ public async Task SaveRestrictedShippingIds_InvokeSettingsService()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var shippingIds = new List<string> { "Ground", "Pickup" };+ var expectedKey = "PaymentMethodRestictionsShipping.systemName";++ await _paymentService.SaveRestrictedShippingIds(_paymentProviderMock.Object, shippingIds);+ _settingService.Verify(+ s => s.SetSetting(expectedKey, It.IsAny<PaymentRestrictedSettings>(), It.IsAny<string>()),+ Times.Once);+ }++ [TestMethod]+ public async Task SaveRestrictedShippingIds_WithStoreId_SaveSettingForStore()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var shippingIds = new List<string> { "Ground" };+ var expectedKey = "PaymentMethodRestictionsShipping.systemName";++ await _paymentService.SaveRestrictedShippingIds(_paymentProviderMock.Object, shippingIds, "storeId");+ _settingService.Verify(+ s => s.SetSetting(expectedKey,+ It.Is<PaymentRestrictedSettings>(x => x.Ids.SequenceEqual(shippingIds)), "storeId"),+ Times.Once);+ }++ [TestMethod]+ public async Task LoadAllPaymentMethods_FilterByCountry_UseStoreScopedRestrictions()+ {+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");+ var expectedKey = "PaymentMethodRestictions.systemName";+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, "storeId"))+ .Returns(() => Task.FromResult(new PaymentRestrictedSettings { Ids = ["countryId"] }));++ var result = await _paymentService.LoadAllPaymentMethods(storeId: "storeId", filterByCountryId: "countryId");++ Assert.IsEmpty(result);+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, "storeId"),+ Times.Once);+ }+[TestMethod]public async Task ProcessPayment_OrderTotalZero_ReturnPaidPaymentStatus(){diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/PaymentControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/PaymentControllerTests.csnew file mode 100644index 000000000..172c505fd--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/PaymentControllerTests.cs@@ -0,0 +1,174 @@+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Stores;+using Grand.Domain.Directory;+using Grand.Domain.Shipping;+using Grand.Domain.Stores;+using Grand.Infrastructure;+using Grand.Infrastructure.Mapper;+using Grand.Mapping;+using Grand.Web.Admin.Controllers;+using Grand.Web.AdminShared.Mapper;+using Grand.Web.AdminShared.Models.Payments;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.Extensions.Primitives;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;+using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;++namespace Grand.Web.Admin.Tests.Controllers;++[TestClass]+public class PaymentControllerTests+{+ private const string StoreId = "storeId";++ private PaymentController _controller;+ private Mock<ICountryService> _countryServiceMock;+ private Mock<IPaymentService> _paymentServiceMock;+ private Mock<ISettingService> _settingServiceMock;+ private Mock<IShippingMethodService> _shippingMethodServiceMock;+ private Mock<ITranslationService> _translationServiceMock;++ [TestInitialize]+ public void Setup()+ {+ var mapperConfig = new MapperConfiguration(cfg =>+ {+ cfg.AddProfile<PaymentMethodProfile>();+ cfg.AddProfile<CountryProfile>();+ });+ AutoMapperConfig.Init(mapperConfig);++ _paymentServiceMock = new Mock<IPaymentService>();+ _settingServiceMock = new Mock<ISettingService>();+ _countryServiceMock = new Mock<ICountryService>();+ _shippingMethodServiceMock = new Mock<IShippingMethodService>();+ _translationServiceMock = new Mock<ITranslationService>();+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ var contextAccessorMock = new Mock<IContextAccessor>();+ contextAccessorMock.Setup(c => c.WorkContext).Returns(new Mock<IWorkContext>().Object);++ _controller = new PaymentController(+ _paymentServiceMock.Object,+ _settingServiceMock.Object,+ _countryServiceMock.Object,+ _shippingMethodServiceMock.Object,+ _translationServiceMock.Object,+ new Mock<IServiceProvider>().Object,+ contextAccessorMock.Object);++ // GetActiveStore resolves its services from HttpContext.RequestServices;+ // a single store short-circuits the group/user-field lookups+ var storeServiceMock = new Mock<IStoreService>();+ storeServiceMock.Setup(s => s.GetAllStores())+ .ReturnsAsync(new List<Store> { new() { Id = StoreId } });+ var requestServicesMock = new Mock<IServiceProvider>();+ requestServicesMock.Setup(sp => sp.GetService(typeof(IStoreService))).Returns(storeServiceMock.Object);+ requestServicesMock.Setup(sp => sp.GetService(typeof(IContextAccessor)))+ .Returns(contextAccessorMock.Object);+ requestServicesMock.Setup(sp => sp.GetService(typeof(IGroupService)))+ .Returns(new Mock<IGroupService>().Object);++ var httpContext = new DefaultHttpContext { RequestServices = requestServicesMock.Object };+ httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>());+ _controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ _controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ _controller.Url = new Mock<IUrlHelper>().Object;+ }++ private Mock<IPaymentProvider> CreatePaymentProvider(string systemName = "Payments.TestMethod")+ {+ var provider = new Mock<IPaymentProvider>();+ provider.Setup(p => p.SystemName).Returns(systemName);+ provider.Setup(p => p.FriendlyName).Returns("Test method");+ return provider;+ }++ [TestMethod]+ public async Task MethodRestrictions_Get_BuildModelFromActiveStoreScope()+ {+ var provider = CreatePaymentProvider();+ var country = new Country { Id = "countryId", Name = "Poland" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };++ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, "", ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country> { country });+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, It.IsAny<string>()))+ .ReturnsAsync(new List<ShippingMethod> { shippingMethod });+ _paymentServiceMock.Setup(p => p.GetRestrictedCountryIds(provider.Object, StoreId))+ .ReturnsAsync(new List<string> { "countryId" });+ _paymentServiceMock.Setup(p => p.GetRestrictedShippingIds(provider.Object, StoreId))+ .ReturnsAsync(new List<string> { "Ground" });++ var result = await _controller.MethodRestrictions();++ var viewResult = result as ViewResult;+ Assert.IsNotNull(viewResult);+ var model = viewResult.Model as PaymentMethodRestrictionModel;+ Assert.IsNotNull(model);+ Assert.IsTrue(model.Resticted["Payments.TestMethod"]["countryId"]);+ Assert.IsTrue(model.RestictedShipping["Payments.TestMethod"]["Ground"]);+ _paymentServiceMock.Verify(p => p.GetRestrictedCountryIds(provider.Object, StoreId), Times.Once);+ _paymentServiceMock.Verify(p => p.GetRestrictedShippingIds(provider.Object, StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodRestrictionsSave_SaveRestrictionsWithActiveStoreScope()+ {+ var provider = CreatePaymentProvider();+ var country = new Country { Id = "countryId", Name = "Poland" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };++ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, "", ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country> { country });+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, It.IsAny<string>()))+ .ReturnsAsync(new List<ShippingMethod> { shippingMethod });++ var form = new Dictionary<string, string[]> {+ ["restrict_PaymentsTestMethod"] = ["countryId"],+ ["restrictship_PaymentsTestMethod"] = ["Ground"]+ };++ var result = await _controller.MethodRestrictionsSave(form);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("MethodRestrictions", redirect.ActionName);+ _paymentServiceMock.Verify(p => p.SaveRestrictedCountryIds(provider.Object,+ It.Is<List<string>>(x => x.Single() == "countryId"), StoreId), Times.Once);+ _paymentServiceMock.Verify(p => p.SaveRestrictedShippingIds(provider.Object,+ It.Is<List<string>>(x => x.Single() == "Ground"), StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodRestrictionsSave_NoFormValues_SaveEmptyRestrictionsWithActiveStoreScope()+ {+ var provider = CreatePaymentProvider();++ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, "", ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country>());+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, It.IsAny<string>()))+ .ReturnsAsync(new List<ShippingMethod>());++ var result = await _controller.MethodRestrictionsSave(new Dictionary<string, string[]>());++ Assert.IsInstanceOfType<RedirectToActionResult>(result);+ _paymentServiceMock.Verify(p => p.SaveRestrictedCountryIds(provider.Object,+ It.Is<List<string>>(x => x.Count == 0), StoreId), Times.Once);+ _paymentServiceMock.Verify(p => p.SaveRestrictedShippingIds(provider.Object,+ It.Is<List<string>>(x => x.Count == 0), StoreId), Times.Once);+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/ProductViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/ProductViewModelServiceTests.csnew file mode 100644index 000000000..956f0b515--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Services/ProductViewModelServiceTests.cs@@ -0,0 +1,206 @@+using Grand.Business.Core.Interfaces.Catalog.Categories;+using Grand.Business.Core.Interfaces.Catalog.Collections;+using Grand.Business.Core.Interfaces.Catalog.Directory;+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Interfaces.Catalog.Prices;+using Grand.Business.Core.Interfaces.Catalog.Products;+using Grand.Business.Core.Interfaces.Catalog.Tax;+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Seo;+using Grand.Business.Core.Interfaces.Common.Stores;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.Storage;+using Grand.Domain;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using Grand.Domain.Media;+using Grand.Domain.Seo;+using Grand.Domain.Shipping;+using Grand.Domain.Stores;+using Grand.Domain.Tax;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Models.Catalog;+using Grand.Web.AdminShared.Services;+using Grand.Web.Common.Localization;+using Microsoft.AspNetCore.Mvc.Rendering;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;+using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;++namespace Grand.Web.Admin.Tests.Services;++[TestClass]+public class ProductViewModelServiceTests+{+ private const string StaffStoreId = "staffStoreId";++ private Mock<IDiscountService> _discountServiceMock;+ private Mock<IEnumTranslationService> _enumTranslationServiceMock;+ private Mock<IMeasureService> _measureServiceMock;+ private ProductViewModelService _productViewModelService;+ private Mock<IStoreService> _storeServiceMock;+ private Mock<ITaxCategoryService> _taxCategoryServiceMock;+ private Mock<ITranslationService> _translationServiceMock;+ private Mock<IWarehouseService> _warehouseServiceMock;++ [TestInitialize]+ public void Setup()+ {+ _discountServiceMock = new Mock<IDiscountService>();+ _enumTranslationServiceMock = new Mock<IEnumTranslationService>();+ _measureServiceMock = new Mock<IMeasureService>();+ _storeServiceMock = new Mock<IStoreService>();+ _taxCategoryServiceMock = new Mock<ITaxCategoryService>();+ _translationServiceMock = new Mock<ITranslationService>();+ _warehouseServiceMock = new Mock<IWarehouseService>();++ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StaffStoreId });+ var contextAccessorMock = new Mock<IContextAccessor>();+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ var currencyServiceMock = new Mock<ICurrencyService>();+ currencyServiceMock.Setup(c => c.GetCurrencyById(It.IsAny<string>())).ReturnsAsync((Currency)null);+ _measureServiceMock.Setup(m => m.GetMeasureWeightById(It.IsAny<string>())).ReturnsAsync((MeasureWeight)null);+ _measureServiceMock.Setup(m => m.GetMeasureDimensionById(It.IsAny<string>()))+ .ReturnsAsync((MeasureDimension)null);+ _measureServiceMock.Setup(m => m.GetAllMeasureWeights()).ReturnsAsync(new List<MeasureWeight>());+ _measureServiceMock.Setup(m => m.GetAllMeasureUnits()).ReturnsAsync(new List<MeasureUnit>());++ var productLayoutServiceMock = new Mock<IProductLayoutService>();+ productLayoutServiceMock.Setup(p => p.GetAllProductLayouts()).ReturnsAsync(new List<ProductLayout>());++ var deliveryDateServiceMock = new Mock<IDeliveryDateService>();+ deliveryDateServiceMock+ .Setup(d => d.GetAllDeliveryDates(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))+ .ReturnsAsync(new PagedList<DeliveryDate>());++ _warehouseServiceMock+ .Setup(w => w.GetAllWarehouses(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))+ .ReturnsAsync(new PagedList<Warehouse>());++ _taxCategoryServiceMock.Setup(t => t.GetAllTaxCategories(It.IsAny<string>()))+ .ReturnsAsync(new List<TaxCategory>());++ _discountServiceMock.Setup(d => d.GetDiscountsQuery(It.IsAny<DiscountType?>(), It.IsAny<string>(),+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync(new List<Discount>());++ _storeServiceMock.Setup(s => s.GetAllStores()).ReturnsAsync(new List<Store>());++ _enumTranslationServiceMock+ .Setup(e => e.ToSelectList(It.IsAny<ProductType>(), It.IsAny<bool>(), It.IsAny<int[]>()))+ .Returns(new SelectList(Enumerable.Empty<SelectListItem>()));++ _productViewModelService = new ProductViewModelService(+ new Mock<IProductService>().Object,+ new Mock<IInventoryManageService>().Object,+ new Mock<IPictureService>().Object,+ new Mock<IProductAttributeService>().Object,+ new Mock<IProductTagService>().Object,+ currencyServiceMock.Object,+ _measureServiceMock.Object,+ new Mock<IDateTimeService>().Object,+ new Mock<ICollectionService>().Object,+ new Mock<IProductCollectionService>().Object,+ new Mock<ICategoryService>().Object,+ new Mock<IProductCategoryService>().Object,+ new Mock<IVendorService>().Object,+ _translationServiceMock.Object,+ productLayoutServiceMock.Object,+ new Mock<ISpecificationAttributeService>().Object,+ contextAccessorMock.Object,+ new Mock<IGroupService>().Object,+ _warehouseServiceMock.Object,+ deliveryDateServiceMock.Object,+ _taxCategoryServiceMock.Object,+ _discountServiceMock.Object,+ new Mock<ICustomerService>().Object,+ _storeServiceMock.Object,+ new Mock<IOutOfStockSubscriptionService>().Object,+ new Mock<IDownloadService>().Object,+ new Mock<ILanguageService>().Object,+ new Mock<IProductAttributeFormatter>().Object,+ new Mock<IStockQuantityService>().Object,+ new CurrencySettings(),+ new MeasureSettings(),+ new TaxSettings(),+ new SeoSettings(),+ new Mock<IAuctionService>().Object,+ new Mock<IPriceFormatter>().Object,+ new Mock<ISeNameService>().Object,+ _enumTranslationServiceMock.Object);+ }++ [TestMethod]+ public async Task PrepareProductModel_UseStaffStoreIdForTaxCategories()+ {+ _taxCategoryServiceMock.Setup(t => t.GetAllTaxCategories(StaffStoreId))+ .ReturnsAsync(new List<TaxCategory> { new() { Id = "taxId", Name = "Standard" } });++ var model = new ProductModel();+ await _productViewModelService.PrepareProductModel(model, null, false, false);++ _taxCategoryServiceMock.Verify(t => t.GetAllTaxCategories(StaffStoreId), Times.Once);+ Assert.IsTrue(model.AvailableTaxCategories.Any(x => x.Value == "taxId"));+ }++ [TestMethod]+ public async Task PrepareProductModel_UseStaffStoreIdForDiscounts()+ {+ var model = new ProductModel();+ await _productViewModelService.PrepareProductModel(model, null, false, false);++ _discountServiceMock.Verify(d => d.GetDiscountsQuery(DiscountType.AssignedToSkus, StaffStoreId,+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);+ }++ [TestMethod]+ public async Task PrepareProductModel_UseModelStoreIdForWarehouses()+ {+ _warehouseServiceMock+ .Setup(w => w.GetAllWarehouses("modelStoreId", It.IsAny<int>(), It.IsAny<int>()))+ .ReturnsAsync(new PagedList<Warehouse> { new() { Id = "warehouseId", Name = "Main" } });++ var model = new ProductModel { StoreId = "modelStoreId" };+ await _productViewModelService.PrepareProductModel(model, null, false, false);++ _warehouseServiceMock.Verify(w => w.GetAllWarehouses("modelStoreId", It.IsAny<int>(), It.IsAny<int>()),+ Times.Once);+ Assert.IsTrue(model.AvailableWarehouses.Any(x => x.Value == "warehouseId"));+ }++ [TestMethod]+ public async Task PrepareProductListModel_UseStoreIdForWarehouses()+ {+ _warehouseServiceMock+ .Setup(w => w.GetAllWarehouses(StaffStoreId, It.IsAny<int>(), It.IsAny<int>()))+ .ReturnsAsync(new PagedList<Warehouse> { new() { Id = "warehouseId", Name = "Main" } });++ var model = await _productViewModelService.PrepareProductListModel(StaffStoreId);++ _warehouseServiceMock.Verify(w => w.GetAllWarehouses(StaffStoreId, It.IsAny<int>(), It.IsAny<int>()),+ Times.Once);+ Assert.IsTrue(model.AvailableWarehouses.Any(x => x.Value == "warehouseId"));+ }++ [TestMethod]+ public async Task PrepareProductListModel_FilterStoresByStoreId()+ {+ _storeServiceMock.Setup(s => s.GetAllStores()).ReturnsAsync(new List<Store> {+ new() { Id = "store1", Shortcut = "Store 1" },+ new() { Id = "store2", Shortcut = "Store 2" }+ });++ var model = await _productViewModelService.PrepareProductListModel("store1");++ Assert.IsTrue(model.AvailableStores.Any(x => x.Value == "store1"));+ Assert.IsFalse(model.AvailableStores.Any(x => x.Value == "store2"));+ }+}diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/PaymentControllerTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/PaymentControllerTests.csnew file mode 100644index 000000000..57215f31e--- /dev/null+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/PaymentControllerTests.cs@@ -0,0 +1,246 @@+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Payments;+using Grand.Domain.Shipping;+using Grand.Infrastructure;+using Grand.Infrastructure.Mapper;+using Grand.Mapping;+using Grand.Web.AdminShared.Mapper;+using Grand.Web.AdminShared.Models.Payments;+using Grand.Web.Common.DataSource;+using Grand.Web.Store.Controllers;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.Extensions.Primitives;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Store.Tests.Controllers;++[TestClass]+public class PaymentControllerTests+{+ private const string StoreId = "storeId";++ private PaymentController _controller;+ private Mock<IContextAccessor> _contextAccessorMock;+ private Mock<ICountryService> _countryServiceMock;+ private Mock<IPaymentService> _paymentServiceMock;+ private Mock<ISettingService> _settingServiceMock;+ private Mock<IShippingMethodService> _shippingMethodServiceMock;+ private Mock<ITranslationService> _translationServiceMock;++ [TestInitialize]+ public void Setup()+ {+ var mapperConfig = new MapperConfiguration(cfg =>+ {+ cfg.AddProfile<PaymentMethodProfile>();+ cfg.AddProfile<CountryProfile>();+ cfg.AddProfile<PaymentSettingsProfile>();+ });+ AutoMapperConfig.Init(mapperConfig);++ _paymentServiceMock = new Mock<IPaymentService>();+ _settingServiceMock = new Mock<ISettingService>();+ _countryServiceMock = new Mock<ICountryService>();+ _shippingMethodServiceMock = new Mock<IShippingMethodService>();+ _translationServiceMock = new Mock<ITranslationService>();+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StoreId });+ _contextAccessorMock = new Mock<IContextAccessor>();+ _contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ _controller = new PaymentController(+ _paymentServiceMock.Object,+ _settingServiceMock.Object,+ _countryServiceMock.Object,+ _shippingMethodServiceMock.Object,+ _translationServiceMock.Object,+ _contextAccessorMock.Object);++ var httpContext = new DefaultHttpContext();+ httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>());+ _controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ _controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ }++ private Mock<IPaymentProvider> CreatePaymentProvider(string systemName = "Payments.TestMethod")+ {+ var provider = new Mock<IPaymentProvider>();+ provider.Setup(p => p.SystemName).Returns(systemName);+ provider.Setup(p => p.FriendlyName).Returns("Test method");+ return provider;+ }++ [TestMethod]+ public async Task Methods_ReturnPaymentMethodsForCurrentStore()+ {+ var provider = CreatePaymentProvider();+ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, StoreId, ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId))+ .ReturnsAsync(new PaymentSettings {+ ActivePaymentProviderSystemNames = ["Payments.TestMethod"]+ });++ var result = await _controller.Methods();++ var jsonResult = result as JsonResult;+ Assert.IsNotNull(jsonResult);+ var data = (DataSourceResult)jsonResult.Value;+ Assert.AreEqual(1, data.Total);+ var model = ((IEnumerable<PaymentMethodModel>)data.Data).First();+ Assert.AreEqual("Payments.TestMethod", model.SystemName);+ Assert.IsTrue(model.IsActive);+ _paymentServiceMock.Verify(p => p.LoadAllPaymentMethods(null, StoreId, ""), Times.Once);+ _settingServiceMock.Verify(s => s.LoadSetting<PaymentSettings>(StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodUpdate_ActivateMethod_SaveSettingForCurrentStore()+ {+ var provider = CreatePaymentProvider();+ var paymentSettings = new PaymentSettings();+ _paymentServiceMock.Setup(p => p.LoadPaymentMethodBySystemName("Payments.TestMethod"))+ .Returns(provider.Object);+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId)).ReturnsAsync(paymentSettings);++ var result = await _controller.MethodUpdate(new PaymentMethodModel+ { SystemName = "Payments.TestMethod", IsActive = true });++ Assert.IsInstanceOfType<JsonResult>(result);+ Assert.Contains("Payments.TestMethod", paymentSettings.ActivePaymentProviderSystemNames);+ _settingServiceMock.Verify(s => s.SaveSetting(paymentSettings, StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodUpdate_DeactivateMethod_SaveSettingForCurrentStore()+ {+ var provider = CreatePaymentProvider();+ var paymentSettings = new PaymentSettings {+ ActivePaymentProviderSystemNames = ["Payments.TestMethod"]+ };+ _paymentServiceMock.Setup(p => p.LoadPaymentMethodBySystemName("Payments.TestMethod"))+ .Returns(provider.Object);+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId)).ReturnsAsync(paymentSettings);++ var result = await _controller.MethodUpdate(new PaymentMethodModel+ { SystemName = "Payments.TestMethod", IsActive = false });++ Assert.IsInstanceOfType<JsonResult>(result);+ Assert.DoesNotContain("Payments.TestMethod", paymentSettings.ActivePaymentProviderSystemNames);+ _settingServiceMock.Verify(s => s.SaveSetting(paymentSettings, StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodUpdate_UnknownMethod_NotSaveSetting()+ {+ _paymentServiceMock.Setup(p => p.LoadPaymentMethodBySystemName(It.IsAny<string>()))+ .Returns((IPaymentProvider)null);+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId)).ReturnsAsync(new PaymentSettings());++ var result = await _controller.MethodUpdate(new PaymentMethodModel+ { SystemName = "Payments.Unknown", IsActive = true });++ Assert.IsInstanceOfType<JsonResult>(result);+ _settingServiceMock.Verify(s => s.SaveSetting(It.IsAny<PaymentSettings>(), It.IsAny<string>()), Times.Never);+ }++ [TestMethod]+ public async Task Settings_Get_LoadSettingForCurrentStore()+ {+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId))+ .ReturnsAsync(new PaymentSettings { AllowRePostingPayments = true });++ var result = await _controller.Settings();++ var viewResult = result as ViewResult;+ Assert.IsNotNull(viewResult);+ var model = viewResult.Model as PaymentSettingsModel;+ Assert.IsNotNull(model);+ Assert.IsTrue(model.AllowRePostingPayments);+ _settingServiceMock.Verify(s => s.LoadSetting<PaymentSettings>(StoreId), Times.Once);+ }++ [TestMethod]+ public async Task Settings_Post_SaveSettingForCurrentStoreAndRedirect()+ {+ var paymentSettings = new PaymentSettings();+ _settingServiceMock.Setup(s => s.LoadSetting<PaymentSettings>(StoreId)).ReturnsAsync(paymentSettings);++ var result = await _controller.Settings(new PaymentSettingsModel { AllowRePostingPayments = true });++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("Settings", redirect.ActionName);+ _settingServiceMock.Verify(s => s.SaveSetting(It.IsAny<PaymentSettings>(), StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodRestrictions_Get_BuildModelFromStoreScopedRestrictions()+ {+ var provider = CreatePaymentProvider();+ var country = new Country { Id = "countryId", Name = "Poland" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };++ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, StoreId, ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country> { country });+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, StoreId))+ .ReturnsAsync(new List<ShippingMethod> { shippingMethod });+ _paymentServiceMock.Setup(p => p.GetRestrictedCountryIds(provider.Object, StoreId))+ .ReturnsAsync(new List<string> { "countryId" });+ _paymentServiceMock.Setup(p => p.GetRestrictedShippingIds(provider.Object, StoreId))+ .ReturnsAsync(new List<string> { "Ground" });++ var result = await _controller.MethodRestrictions();++ var viewResult = result as ViewResult;+ Assert.IsNotNull(viewResult);+ var model = viewResult.Model as PaymentMethodRestrictionModel;+ Assert.IsNotNull(model);+ Assert.IsTrue(model.Resticted["Payments.TestMethod"]["countryId"]);+ Assert.IsTrue(model.RestictedShipping["Payments.TestMethod"]["Ground"]);+ _paymentServiceMock.Verify(p => p.GetRestrictedCountryIds(provider.Object, StoreId), Times.Once);+ _paymentServiceMock.Verify(p => p.GetRestrictedShippingIds(provider.Object, StoreId), Times.Once);+ }++ [TestMethod]+ public async Task MethodRestrictionsSave_SaveRestrictionsForCurrentStore()+ {+ var provider = CreatePaymentProvider();+ var country = new Country { Id = "countryId", Name = "Poland" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };++ _paymentServiceMock.Setup(p => p.LoadAllPaymentMethods(null, StoreId, ""))+ .ReturnsAsync(new List<IPaymentProvider> { provider.Object });+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country> { country });+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, StoreId))+ .ReturnsAsync(new List<ShippingMethod> { shippingMethod });++ var form = new Dictionary<string, string[]> {+ ["restrict_PaymentsTestMethod"] = ["countryId"]+ };++ var result = await _controller.MethodRestrictionsSave(form);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("MethodRestrictions", redirect.ActionName);+ _paymentServiceMock.Verify(p => p.SaveRestrictedCountryIds(provider.Object,+ It.Is<List<string>>(x => x.Single() == "countryId"), StoreId), Times.Once);+ _paymentServiceMock.Verify(p => p.SaveRestrictedShippingIds(provider.Object,+ It.Is<List<string>>(x => x.Count == 0), StoreId), Times.Once);+ }+}diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/ShippingControllerTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/ShippingControllerTests.csnew file mode 100644index 000000000..a49a2cde4--- /dev/null+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/ShippingControllerTests.cs@@ -0,0 +1,153 @@+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Shipping;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Models.Shipping;+using Grand.Web.Store.Controllers;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.Extensions.Primitives;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Store.Tests.Controllers;++[TestClass]+public class ShippingControllerTests+{+ private const string StoreId = "storeId";++ private ShippingController _controller;+ private Mock<IContextAccessor> _contextAccessorMock;+ private Mock<ICountryService> _countryServiceMock;+ private Mock<IGroupService> _groupServiceMock;+ private Mock<IShippingMethodService> _shippingMethodServiceMock;+ private Mock<ITranslationService> _translationServiceMock;++ [TestInitialize]+ public void Setup()+ {+ _shippingMethodServiceMock = new Mock<IShippingMethodService>();+ _countryServiceMock = new Mock<ICountryService>();+ _groupServiceMock = new Mock<IGroupService>();+ _translationServiceMock = new Mock<ITranslationService>();+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StoreId });+ _contextAccessorMock = new Mock<IContextAccessor>();+ _contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ _controller = new ShippingController(+ new Mock<IShippingService>().Object,+ _shippingMethodServiceMock.Object,+ new Mock<IDeliveryDateService>().Object,+ new Mock<IWarehouseService>().Object,+ new Mock<IPickupPointService>().Object,+ _countryServiceMock.Object,+ _groupServiceMock.Object,+ new Mock<ILanguageService>().Object,+ _translationServiceMock.Object,+ new Mock<ISettingService>().Object,+ _contextAccessorMock.Object);++ var httpContext = new DefaultHttpContext();+ httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>());+ _controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ _controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ }++ private void SetupCommonData(Country country, ShippingMethod shippingMethod, CustomerGroup customerGroup)+ {+ _countryServiceMock.Setup(c => c.GetAllCountries(It.IsAny<string>(), It.IsAny<string>(), true))+ .ReturnsAsync(new List<Country> { country });+ _shippingMethodServiceMock.Setup(s => s.GetAllShippingMethods(It.IsAny<string>(), null, StoreId))+ .ReturnsAsync(new List<ShippingMethod> { shippingMethod });+ _groupServiceMock.Setup(g =>+ g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>()))+ .ReturnsAsync(new PagedList<CustomerGroup> { customerGroup });+ }++ [TestMethod]+ public async Task Restrictions_Get_BuildModelFromStoreScopedShippingMethods()+ {+ var country = new Country { Id = "countryId", Name = "Poland" };+ var customerGroup = new CustomerGroup { Name = "Guests" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };+ shippingMethod.RestrictedCountries.Add(country);+ shippingMethod.RestrictedGroups.Add(customerGroup.Id);+ SetupCommonData(country, shippingMethod, customerGroup);++ var result = await _controller.Restrictions();++ var viewResult = result as ViewResult;+ Assert.IsNotNull(viewResult);+ var model = viewResult.Model as ShippingMethodRestrictionModel;+ Assert.IsNotNull(model);+ Assert.IsTrue(model.Restricted["countryId"][shippingMethod.Id]);+ Assert.IsTrue(model.RestictedGroup[customerGroup.Id][shippingMethod.Id]);+ _shippingMethodServiceMock.Verify(s => s.GetAllShippingMethods(It.IsAny<string>(), null, StoreId),+ Times.Once);+ }++ [TestMethod]+ public async Task RestrictionSave_AddRestriction_UpdateShippingMethod()+ {+ var country = new Country { Id = "countryId", Name = "Poland" };+ var customerGroup = new CustomerGroup { Name = "Guests" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };+ SetupCommonData(country, shippingMethod, customerGroup);++ var form = new Dictionary<string, string[]> {+ [$"restrict_{shippingMethod.Id}"] = ["countryId"]+ };++ var result = await _controller.RestrictionSave(form);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("Restrictions", redirect.ActionName);+ Assert.IsTrue(shippingMethod.RestrictedCountries.Any(c => c.Id == "countryId"));+ _shippingMethodServiceMock.Verify(s => s.UpdateShippingMethod(shippingMethod), Times.Once);+ _shippingMethodServiceMock.Verify(s => s.GetAllShippingMethods(It.IsAny<string>(), null, StoreId),+ Times.Once);+ }++ [TestMethod]+ public async Task RestrictionSave_NoFormValues_ClearExistingRestrictions()+ {+ var country = new Country { Id = "countryId", Name = "Poland" };+ var customerGroup = new CustomerGroup { Name = "Guests" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };+ shippingMethod.RestrictedCountries.Add(country);+ shippingMethod.RestrictedGroups.Add(customerGroup.Id);+ SetupCommonData(country, shippingMethod, customerGroup);++ var result = await _controller.RestrictionSave(new Dictionary<string, string[]>());++ Assert.IsInstanceOfType<RedirectToActionResult>(result);+ Assert.IsEmpty(shippingMethod.RestrictedCountries);+ Assert.IsEmpty(shippingMethod.RestrictedGroups);+ _shippingMethodServiceMock.Verify(s => s.UpdateShippingMethod(shippingMethod), Times.Exactly(2));+ }++ [TestMethod]+ public async Task RestrictionSave_NoChanges_NotUpdateShippingMethod()+ {+ var country = new Country { Id = "countryId", Name = "Poland" };+ var customerGroup = new CustomerGroup { Name = "Guests" };+ var shippingMethod = new ShippingMethod { Name = "Ground" };+ SetupCommonData(country, shippingMethod, customerGroup);++ var result = await _controller.RestrictionSave(new Dictionary<string, string[]>());++ Assert.IsInstanceOfType<RedirectToActionResult>(result);+ _shippingMethodServiceMock.Verify(s => s.UpdateShippingMethod(It.IsAny<ShippingMethod>()), Times.Never);+ }+}diff --git a/src/Tests/Grand.Web.Store.Tests/Grand.Web.Store.Tests.csproj b/src/Tests/Grand.Web.Store.Tests/Grand.Web.Store.Tests.csprojnew file mode 100644index 000000000..27b6e3c8d--- /dev/null+++ b/src/Tests/Grand.Web.Store.Tests/Grand.Web.Store.Tests.csproj@@ -0,0 +1,24 @@+<Project Sdk="Microsoft.NET.Sdk">++ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" />+ <PackageReference Include="Moq" />+ <PackageReference Include="MSTest.TestAdapter" />+ <PackageReference Include="MSTest.TestFramework" />+ <PackageReference Include="coverlet.collector">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web.AdminShared\Grand.Web.AdminShared.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web.Store\Grand.Web.Store.csproj" />+ </ItemGroup>+</Project>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Payment/MethodRestrictions.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Payment/MethodRestrictions.cshtmlindex cc8e28179..740e9b75d 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Payment/MethodRestrictions.cshtml+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Payment/MethodRestrictions.cshtml@@ -20,6 +20,13 @@</button></div></div>+ <div class="x_content">+ <div class="form-horizontal">+ <div class="form-body">+ @await Component.InvokeAsync("StoreScope")+ </div>+ </div>+ </div><div class="x_content form"><vc:admin-widget widget-zone="payment_method_restrictions_top" additional-data="Model"/><admin-tabstrip name="paymentrestriction-edit">diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentController.csindex c552cd35f..60669eaff 100644--- a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs@@ -147,6 +147,8 @@ public class PaymentController : BaseAdminControllerpublic async Task<IActionResult> MethodRestrictions(){+ var storeScope = await GetActiveStore();+var model = new PaymentMethodRestrictionModel();var paymentMethods = await _paymentService.LoadAllPaymentMethods();var countries = await _countryService.GetAllCountries(showHidden: true);@@ -162,7 +164,7 @@ public class PaymentController : BaseAdminControllerforeach (var pm in paymentMethods){- var restictedCountries = await _paymentService.GetRestrictedCountryIds(pm);+ var restictedCountries = await _paymentService.GetRestrictedCountryIds(pm, storeScope);foreach (var c in countries){var resticted = restictedCountries.Contains(c.Id);@@ -171,7 +173,7 @@ public class PaymentController : BaseAdminControllermodel.Resticted[pm.SystemName][c.Id] = resticted;}- var restictedShipping = await _paymentService.GetRestrictedShippingIds(pm);+ var restictedShipping = await _paymentService.GetRestrictedShippingIds(pm, storeScope);foreach (var s in shippings){var resticted = restictedShipping.Contains(s.Name);@@ -189,6 +191,8 @@ public class PaymentController : BaseAdminController[RequestFormLimits(ValueCountLimit = 2048)]public async Task<IActionResult> MethodRestrictionsSave(IDictionary<string, string[]> model){+ var storeScope = await GetActiveStore();+var paymentMethods = await _paymentService.LoadAllPaymentMethods();var countries = await _countryService.GetAllCountries(showHidden: true);var shippings = await _shippingMethodService.GetAllShippingMethods();@@ -200,22 +204,22 @@ public class PaymentController : BaseAdminControllervar countryIdsToRestrict = countryIds.ToList();var newCountryIds =(from c in countries where countryIdsToRestrict.Contains(c.Id) select c.Id).ToList();- await _paymentService.SaveRestrictedCountryIds(pm, newCountryIds);+ await _paymentService.SaveRestrictedCountryIds(pm, newCountryIds, storeScope);}else{- await _paymentService.SaveRestrictedCountryIds(pm, new List<string>());+ await _paymentService.SaveRestrictedCountryIds(pm, new List<string>(), storeScope);}if (model.TryGetValue($"restrictship_{pm.SystemName.Replace(".", "")}", out var shipIds)){var shipIdsToRestrict = shipIds.ToList();var newShipIds = (from s in shippings where shipIdsToRestrict.Contains(s.Name) select s.Name).ToList();- await _paymentService.SaveRestrictedShippingIds(pm, newShipIds);+ await _paymentService.SaveRestrictedShippingIds(pm, newShipIds, storeScope);}else{- await _paymentService.SaveRestrictedShippingIds(pm, new List<string>());+ await _paymentService.SaveRestrictedShippingIds(pm, new List<string>(), storeScope);}}diff --git a/src/Web/Grand.Web.AdminShared/Services/ProductViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/ProductViewModelService.csindex 8a61e1b01..426490681 100644--- a/src/Web/Grand.Web.AdminShared/Services/ProductViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Services/ProductViewModelService.cs@@ -366,7 +366,7 @@ public class ProductViewModelService(}//tax categories- var taxCategories = await taxCategoryService.GetAllTaxCategories();+ var taxCategories = await taxCategoryService.GetAllTaxCategories(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);model.AvailableTaxCategories.Add(new SelectListItem {Text = translationService.GetResource("Admin.Configuration.Tax.Settings.TaxCategories.None"),Value = ""@@ -400,7 +400,7 @@ public class ProductViewModelService(model.AvailableUnits.Add(new SelectListItem { Text = un.Name, Value = un.Id, Selected = product != null && un.Id == product.UnitId });//discounts- model.AvailableDiscounts = (await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, model.StoreId))+ model.AvailableDiscounts = (await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, contextAccessor.WorkContext.CurrentCustomer.StaffStoreId)).Select(d => d.ToModel(dateTimeService)).ToList();if (!excludeProperties && product != null) model.SelectedDiscountIds = product.AppliedDiscounts.ToArray();@@ -529,7 +529,7 @@ public class ProductViewModelService(model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });//warehousesmodel.AvailableWarehouses.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " });- foreach (var wh in await warehouseService.GetAllWarehouses())+ foreach (var wh in await warehouseService.GetAllWarehouses(storeId))model.AvailableWarehouses.Add(new SelectListItem { Text = wh.Name, Value = wh.Id });//product typesdiff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Index.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Index.cshtmlnew file mode 100644index 000000000..c7e50fb35--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Index.cshtml@@ -0,0 +1,141 @@+@{+ ViewBag.Title = Loc["Admin.Configuration.Payment.Methods"];+ Layout = Constants.LayoutStore;+}++<div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption level-caption">+ <i class="fa fa-money"></i>+ @Loc["Admin.Configuration.Payment.Methods"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="x_content">+ <div id="paymentmethods-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>+<script>+ $(document).ready(function () {+ $("#paymentmethods-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("Methods", "Payment", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ update: {+ url: "@Html.Raw(Url.Action("MethodUpdate", "Payment", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "SystemName",+ fields: {+ FriendlyName: { editable: false, type: "string" },+ SystemName: { editable: false, type: "string" },+ SupportCapture: { editable: false, type: "boolean" },+ SupportRefund: { editable: false, type: "boolean" },+ SupportPartiallyRefund: { editable: false, type: "boolean" },+ SupportVoid: { editable: false, type: "boolean" },+ DisplayOrder: { editable: false, type: "number" },+ IsActive: { editable: true, type: "boolean" }+ }+ }+ },+ requestEnd: function (e) {+ if (e.type == "update") {+ this.read();+ }+ },+ error: function (e) {+ display_kendoui_grid_error(e);+ this.cancelChanges();+ },+ serverPaging: true,+ serverFiltering: true,+ serverSorting: true+ },+ pageable: {+ refresh: true,+ numeric: false,+ previousNext: false,+ info: false+ },+ editable: {+ confirmation: false,+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "FriendlyName",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.FriendlyName"]"+ }, {+ field: "SystemName",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.SystemName"]"+ }, {+ field: "SupportCapture",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.SupportCapture"]",+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(SupportCapture) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ field: "SupportRefund",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.SupportRefund"]",+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(SupportRefund) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ field: "SupportPartiallyRefund",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.SupportPartiallyRefund"]",+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(SupportPartiallyRefund) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ field: "SupportVoid",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.SupportVoid"]",+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(SupportVoid) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ field: "DisplayOrder",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.DisplayOrder"]",+ format: "{0:0}"+ }, {+ field: "IsActive",+ title: "@Loc["Admin.Configuration.Payment.Methods.Fields.IsActive"]",+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(IsActive) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ command: {+ name: "edit",+ text: {+ edit: "@Loc["Admin.Common.Edit"]",+ update: "@Loc["Admin.Common.Update"]",+ cancel: "@Loc["Admin.Common.Cancel"]"+ }+ },+ title: "@Loc["Admin.Common.Edit"]",+ width: 150+ }]+ });+ });+</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/MethodRestrictions.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/MethodRestrictions.cshtmlnew file mode 100644index 000000000..926437da5--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/MethodRestrictions.cshtml@@ -0,0 +1,46 @@+@model PaymentMethodRestrictionModel++@{+ ViewBag.Title = Loc["Admin.Configuration.Payment.MethodRestrictions"];+ Layout = Constants.LayoutStore;+}+<form asp-area="@Constants.AreaStore" asp-controller="Payment" asp-action="MethodRestrictions" method="post">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-money"></i>+ @Loc["Admin.Configuration.Payment.MethodRestrictions"]+ </div>+ <div class="actions">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ <div class="x_content form">+ <admin-tabstrip name="paymentrestriction-edit">+ <items>+ <tabstrip-item text="@Loc["Admin.Configuration.Payment.MethodRestrictions.Country"]" tab-index="0">+ <content>+ <div>+ <partial name="Partials/MethodRestrictions.TabCountry" model="Model"/>+ </div>+ </content>+ </tabstrip-item>+ <tabstrip-item text="@Loc["Admin.Configuration.Payment.MethodRestrictions.Shipping"]" tab-index="1">+ <content>+ <div>+ <partial name="Partials/MethodRestrictions.TabShipping" model="Model"/>+ </div>+ </content>+ </tabstrip-item>+ </items>+ </admin-tabstrip>+ </div>+ </div>+ </div>+ </div>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabCountry.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabCountry.cshtmlnew file mode 100644index 000000000..87c91f0bd--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabCountry.cshtml@@ -0,0 +1,81 @@+@model PaymentMethodRestrictionModel+<div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-md-12 col-sm-12">+ <div class="note note-info">+ @Loc["Admin.Configuration.Payment.MethodRestrictions.DescriptionCountry"]+ </div>+ @if (Model.AvailablePaymentMethods.Count == 0)+ {+ <text>No payment methods installed</text>+ }+ else if (Model.AvailableCountries.Count == 0)+ {+ <text>No countries available</text>+ }+ else+ {+ <script>+ $(document).ready(function () {+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <text>+ $('#selectall-@(systemNameWithoutDot)').click(function () {+ $('.restrict_@(systemNameWithoutDot)').prop('checked', $(this).is(':checked')).change();+ });++ </text>+ }+ });+ </script>+ <table class="table table-bordered table-striped table-hover table-hover">+ <tbody>+ <tr>+ <th scope="col">+ <strong>@Loc["Admin.Configuration.Payment.MethodRestrictions.Country"]</strong>+ </th>+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <th scope="col">+ <strong>@pm.FriendlyName</strong>+ <label class='mt-checkbox mt-checkbox-outline control control-checkbox'>+ <input type="checkbox" id="selectall-@(systemNameWithoutDot)"/>+ <div class="control__indicator"></div>+ </label>+ </th>+ }+ </tr>+ @{+ var altRow = true;+ }+ @foreach (var c in Model.AvailableCountries)+ {+ altRow = !altRow;+ <tr class="@(altRow ? "altrowstyle" : "rowstyle")">+ <td>+ <span>@c.Name</span>+ </td>+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var resticted = Model.Resticted.ContainsKey(pm.SystemName) && Model.Resticted[pm.SystemName][c.Id];++ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <td style="text-align:center">+ <label class='mt-checkbox mt-checkbox-outline control control-checkbox'>+ <input class="restrict_@(systemNameWithoutDot)" type="checkbox" value="@(c.Id)" name="restrict_@(systemNameWithoutDot)" @(resticted ? " checked=checked" : null)/>+ <div class="control__indicator"></div>+ </label>+ </td>+ }+ </tr>+ }+ </tbody>+ </table>+ }+ </div>+ </div>+ </div>+</div>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabShipping.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabShipping.cshtmlnew file mode 100644index 000000000..d4f704274--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Partials/MethodRestrictions.TabShipping.cshtml@@ -0,0 +1,80 @@+@model PaymentMethodRestrictionModel+<div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-md-12 col-sm-12">+ <div class="note note-info">+ @Loc["Admin.Configuration.Payment.MethodRestrictions.DescriptionShipping"]+ </div>+ @if (Model.AvailablePaymentMethods.Count == 0)+ {+ <text>No payment methods installed</text>+ }+ else if (Model.AvailableShippingMethods.Count == 0)+ {+ <text>No shipping method available</text>+ }+ else+ {+ <script>+ $(document).ready(function () {+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <text>+ $('#selectshipall-@(systemNameWithoutDot)').click(function () {+ $('.restrictship_@(systemNameWithoutDot)').prop('checked', $(this).is(':checked')).change();+ });++ </text>+ }+ });+ </script>+ <table class="table table-bordered table-striped table-hover table-hover">+ <tbody>+ <tr>+ <th scope="col">+ <strong>@Loc["Admin.Configuration.Payment.MethodRestrictions.Shipping"]</strong>+ </th>+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <th scope="col">+ <strong>@pm.FriendlyName</strong>+ <label class='mt-checkbox mt-checkbox-outline control control-checkbox'>+ <input type="checkbox" id="selectshipall-@(systemNameWithoutDot)"/>+ <div class="control__indicator"></div>+ </label>+ </th>+ }+ </tr>+ @{+ var altRow = true;+ }+ @foreach (var c in Model.AvailableShippingMethods)+ {+ altRow = !altRow;+ <tr class="@(altRow ? "altrowstyle" : "rowstyle")">+ <td>+ <span>@c.Name</span>+ </td>+ @foreach (var pm in Model.AvailablePaymentMethods)+ {+ var resticted = Model.RestictedShipping.ContainsKey(pm.SystemName) && Model.RestictedShipping[pm.SystemName][c.Name];+ var systemNameWithoutDot = pm.SystemName.Replace(".", "");+ <td style="text-align:center">+ <label class='mt-checkbox mt-checkbox-outline control control-checkbox'>+ <input class="restrictship_@(systemNameWithoutDot)" type="checkbox" value="@(c.Name)" name="restrictship_@(systemNameWithoutDot)" @(resticted ? " checked=checked" : null)/>+ <div class="control__indicator"></div>+ </label>+ </td>+ }+ </tr>+ }+ </tbody>+ </table>+ }+ </div>+ </div>+ </div>+</div>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Settings.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Settings.cshtmlnew file mode 100644index 000000000..c71c8a8c4--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Payment/Settings.cshtml@@ -0,0 +1,95 @@+@model PaymentSettingsModel+@{+ ViewBag.Title = Loc["Admin.Configuration.Payment.Settings"];+ Layout = Constants.LayoutStore;+}+<form asp-area="@Constants.AreaStore" asp-controller="Payment" asp-action="Settings" method="post">++ <div asp-validation-summary="All"></div>++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-fw fa-sliders"></i>+ @Loc["Admin.Configuration.Payment.Settings"]+ </div>+ <div class="actions">+ <div class="btn-group btn-group-devided">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="AllowRePostingPayments" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="AllowRePostingPayments"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="AllowRePostingPayments"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="SkipPaymentIfOnlyOne" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="SkipPaymentIfOnlyOne"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="SkipPaymentIfOnlyOne"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ShowPaymentIfCartIsZero" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="ShowPaymentIfCartIsZero"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="ShowPaymentIfCartIsZero"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ShowPaymentDescriptions" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="ShowPaymentDescriptions"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="ShowPaymentDescriptions"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="SkipPaymentInfo" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="SkipPaymentInfo"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="SkipPaymentInfo"></span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtmlindex c34fda895..38a41e485 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtml+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtml@@ -35,6 +35,7 @@@using Grand.Web.AdminShared.Models.Pages@using Grand.Web.AdminShared.Models.Settings@using Grand.Web.AdminShared.Models.Shipping+@using Grand.Web.AdminShared.Models.Payments@using Grand.Web.AdminShared.Models.Discounts@using Grand.Web.AdminShared.Models.Tax@using Grand.Web.Store.Models.Messagesdiff --git a/src/Web/Grand.Web.Store/Controllers/PaymentController.cs b/src/Web/Grand.Web.Store/Controllers/PaymentController.csnew file mode 100644index 000000000..770596359--- /dev/null+++ b/src/Web/Grand.Web.Store/Controllers/PaymentController.cs@@ -0,0 +1,199 @@+using Grand.Business.Core.Extensions;+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Payments;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Extensions.Mapping;+using Grand.Web.AdminShared.Extensions.Mapping.Settings;+using Grand.Web.AdminShared.Models.Payments;+using Grand.Web.AdminShared.Models.Shipping;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;++namespace Grand.Web.Store.Controllers;++[PermissionAuthorize(PermissionSystemName.PaymentMethods)]+public class PaymentController(+ IPaymentService paymentService,+ ISettingService settingService,+ ICountryService countryService,+ IShippingMethodService shippingMethodService,+ ITranslationService translationService,+ IContextAccessor contextAccessor) : BaseStoreController+{+ private string CurrentStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ #region Payment methods++ public IActionResult Index()+ {+ return View();+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> Methods()+ {+ var paymentSettings = await settingService.LoadSetting<PaymentSettings>(CurrentStoreId);++ var paymentMethodsModel = new List<PaymentMethodModel>();+ var paymentMethods = await paymentService.LoadAllPaymentMethods(storeId: CurrentStoreId);+ foreach (var paymentMethod in paymentMethods)+ {+ var tmp = await paymentMethod.ToModel();+ tmp.IsActive = paymentMethod.IsPaymentMethodActive(paymentSettings);+ paymentMethodsModel.Add(tmp);+ }++ var gridModel = new DataSourceResult {+ Data = paymentMethodsModel,+ Total = paymentMethodsModel.Count+ };++ return Json(gridModel);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> MethodUpdate(PaymentMethodModel model)+ {+ var paymentSettings = await settingService.LoadSetting<PaymentSettings>(CurrentStoreId);++ var pm = paymentService.LoadPaymentMethodBySystemName(model.SystemName);+ if (pm == null)+ return new JsonResult("");++ if (pm.IsPaymentMethodActive(paymentSettings))+ {+ if (!model.IsActive)+ {+ paymentSettings.ActivePaymentProviderSystemNames.Remove(pm.SystemName);+ await settingService.SaveSetting(paymentSettings, CurrentStoreId);+ }+ }+ else+ {+ if (model.IsActive)+ {+ paymentSettings.ActivePaymentProviderSystemNames.Add(pm.SystemName);+ await settingService.SaveSetting(paymentSettings, CurrentStoreId);+ }+ }++ return new JsonResult("");+ }++ #endregion++ #region Payment settings++ public async Task<IActionResult> Settings()+ {+ var paymentSettings = await settingService.LoadSetting<PaymentSettings>(CurrentStoreId);+ var model = paymentSettings.ToModel();+ return View(model);+ }++ [HttpPost]+ public async Task<IActionResult> Settings(PaymentSettingsModel model)+ {+ var paymentSettings = await settingService.LoadSetting<PaymentSettings>(CurrentStoreId);+ paymentSettings = model.ToEntity(paymentSettings);+ await settingService.SaveSetting(paymentSettings, CurrentStoreId);++ Success(translationService.GetResource("Admin.Configuration.Updated"));+ return RedirectToAction("Settings");+ }++ #endregion++ #region Restrictions++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ public async Task<IActionResult> MethodRestrictions()+ {+ var model = new PaymentMethodRestrictionModel();+ var paymentMethods = await paymentService.LoadAllPaymentMethods(storeId: CurrentStoreId);+ var countries = await countryService.GetAllCountries(showHidden: true);+ var shippings = await shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);++ foreach (var pm in paymentMethods) model.AvailablePaymentMethods.Add(await pm.ToModel());+ foreach (var c in countries) model.AvailableCountries.Add(c.ToModel());+ foreach (var s in shippings)+ model.AvailableShippingMethods.Add(new ShippingMethodModel {+ Id = s.Id,+ Name = s.Name+ });++ foreach (var pm in paymentMethods)+ {+ var restictedCountries = await paymentService.GetRestrictedCountryIds(pm, CurrentStoreId);+ foreach (var c in countries)+ {+ var resticted = restictedCountries.Contains(c.Id);+ if (!model.Resticted.ContainsKey(pm.SystemName))+ model.Resticted[pm.SystemName] = new Dictionary<string, bool>();+ model.Resticted[pm.SystemName][c.Id] = resticted;+ }++ var restictedShipping = await paymentService.GetRestrictedShippingIds(pm, CurrentStoreId);+ foreach (var s in shippings)+ {+ var resticted = restictedShipping.Contains(s.Name);+ if (!model.RestictedShipping.ContainsKey(pm.SystemName))+ model.RestictedShipping[pm.SystemName] = new Dictionary<string, bool>();+ model.RestictedShipping[pm.SystemName][s.Name] = resticted;+ }+ }++ return View(model);+ }++ [HttpPost]+ [ActionName("MethodRestrictions")]+ [RequestFormLimits(ValueCountLimit = 2048)]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> MethodRestrictionsSave(IDictionary<string, string[]> model)+ {+ var paymentMethods = await paymentService.LoadAllPaymentMethods(storeId: CurrentStoreId);+ var countries = await countryService.GetAllCountries(showHidden: true);+ var shippings = await shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);++ foreach (var pm in paymentMethods)+ {+ if (model.TryGetValue($"restrict_{pm.SystemName.Replace(".", "")}", out var countryIds))+ {+ var countryIdsToRestrict = countryIds.ToList();+ var newCountryIds =+ (from c in countries where countryIdsToRestrict.Contains(c.Id) select c.Id).ToList();+ await paymentService.SaveRestrictedCountryIds(pm, newCountryIds, CurrentStoreId);+ }+ else+ {+ await paymentService.SaveRestrictedCountryIds(pm, new List<string>(), CurrentStoreId);+ }++ if (model.TryGetValue($"restrictship_{pm.SystemName.Replace(".", "")}", out var shipIds))+ {+ var shipIdsToRestrict = shipIds.ToList();+ var newShipIds = (from s in shippings where shipIdsToRestrict.Contains(s.Name) select s.Name).ToList();+ await paymentService.SaveRestrictedShippingIds(pm, newShipIds, CurrentStoreId);+ }+ else+ {+ await paymentService.SaveRestrictedShippingIds(pm, new List<string>(), CurrentStoreId);+ }+ }++ Success(translationService.GetResource("Admin.Configuration.Payment.MethodRestrictions.Updated"));+ await SaveSelectedTabIndex();+ return RedirectToAction("MethodRestrictions");+ }++ #endregion+}diff --git a/src/Web/Grand.Web.Store/Controllers/ShippingController.cs b/src/Web/Grand.Web.Store/Controllers/ShippingController.csindex 17995c354..7a88bbf45 100644--- a/src/Web/Grand.Web.Store/Controllers/ShippingController.cs+++ b/src/Web/Grand.Web.Store/Controllers/ShippingController.cs@@ -591,8 +591,7 @@ public class ShippingController(var model = new ShippingMethodRestrictionModel();var countries = await countryService.GetAllCountries(showHidden: true);- var shippingMethods = (await shippingMethodService.GetAllShippingMethods(CurrentStoreId))- .Where(sm => sm.StoreId == CurrentStoreId).ToList();+ var shippingMethods = await shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);var customerGroups = await groupService.GetAllCustomerGroups();foreach (var country in countries)@@ -636,8 +635,7 @@ public class ShippingController(public async Task<IActionResult> RestrictionSave(IDictionary<string, string[]> model){var countries = await countryService.GetAllCountries(showHidden: true);- var shippingMethods = (await shippingMethodService.GetAllShippingMethods(CurrentStoreId))- .Where(sm => sm.StoreId == CurrentStoreId).ToList();+ var shippingMethods = await shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);var customerGroups = await groupService.GetAllCustomerGroups();foreach (var shippingMethod in shippingMethods){