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 TaxController to Grand.Web.Store and StoreId support for tax settings, tax categories, tax providers (#712)
Krzysztof Pajak7087636eefc3
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.csindex b87ccb310..7360dbd0d 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs@@ -235,7 +235,7 @@ public class ProductAttributeFormatter : IProductAttributeFormattervar attributeValuePriceAdjustment =await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);var (priceAdjustmentBase, _) = await _taxService.GetProductPrice(product,- attributeValuePriceAdjustment, _contextAccessor.WorkContext.CurrentCustomer);+ attributeValuePriceAdjustment, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore);switch (priceAdjustmentBase){case > 0:diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.csindex b5437aa56..83fb9d5bd 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs@@ -45,16 +45,17 @@ public class TaxCategoryService : ITaxCategoryService/// <summary>/// Gets all tax categories/// </summary>+ /// <param name="storeId">Store identifier; pass empty to return all</param>/// <returns>Tax categories</returns>- public virtual async Task<IList<TaxCategory>> GetAllTaxCategories()+ public virtual async Task<IList<TaxCategory>> GetAllTaxCategories(string storeId = ""){- var key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY);+ var key = string.Format(CacheKey.TAXCATEGORIES_ALL_KEY, storeId);return await _cacheBase.GetAsync(key, async () =>{- var query = from tc in _taxCategoryRepository.Table- orderby tc.DisplayOrder- select tc;- return await Task.FromResult(query.ToList());+ var query = _taxCategoryRepository.Table.AsQueryable();+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(tc => tc.StoreId == storeId || string.IsNullOrEmpty(tc.StoreId));+ return await Task.FromResult(query.OrderBy(tc => tc.DisplayOrder).ToList());});}diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.csindex ba54c0663..e1110c889 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs@@ -6,6 +6,7 @@ using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Directory;using Grand.Domain.Orders;+using Grand.Domain.Stores;using Grand.Domain.Tax;using Grand.Infrastructure;using Grand.Infrastructure.Extensions;@@ -99,15 +100,15 @@ public class TaxService : ITaxService/// <param name="customer">Customer</param>/// <param name="price">Price</param>/// <returns>Package for tax calculation</returns>- protected virtual async Task<TaxRequest> CreateCalculateTaxRequest(Product product,- string taxCategoryId, Customer customer, double price)+ protected virtual async Task<TaxRequest> CreateCalculateTaxRequest(Product product, string taxCategoryId, Customer customer, Store store, double price){ArgumentNullException.ThrowIfNull(customer);var calculateTaxRequest = new TaxRequest {Customer = customer,Product = product,- Price = price+ Price = price,+ Store = store};if (!string.IsNullOrEmpty(taxCategoryId))@@ -186,8 +187,7 @@ public class TaxService : ITaxService/// <param name="taxCategoryId">Tax category identifier</param>/// <param name="customer">Customer</param>/// <param name="price">Price (taxable value)</param>- protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId,- Customer customer, double price)+ protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId, Customer customer, Store store, double price){double taxRate = 0;var isTaxable = true;@@ -198,7 +198,7 @@ public class TaxService : ITaxServicereturn (taxRate, true);//tax request- var calculateTaxRequest = await CreateCalculateTaxRequest(product, taxCategoryId, customer, price);+ var calculateTaxRequest = await CreateCalculateTaxRequest(product, taxCategoryId, customer, store, price);//tax exemptif (await IsTaxExempt(product, calculateTaxRequest.Customer)) isTaxable = false;@@ -278,8 +278,7 @@ public class TaxService : ITaxService/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price){- var customer = _contextAccessor.WorkContext.CurrentCustomer;- return await GetProductPrice(product, price, customer);+ return await GetProductPrice(product, price, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore);}/// <summary>@@ -288,12 +287,12 @@ public class TaxService : ITaxService/// <param name="product">Product</param>/// <param name="price">Price</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,- Customer customer)+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, Customer customer, Store store){var includingTax = _contextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;- return await GetProductPrice(product, price, includingTax, customer);+ return await GetProductPrice(product, price, includingTax, customer, store);}/// <summary>@@ -303,13 +302,13 @@ public class TaxService : ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,- bool includingTax, Customer customer)+ public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, bool includingTax, Customer customer, Store store){var priceIncludesTax = _taxSettings.PricesIncludeTax;return await GetProductPrice(product, string.Empty, price, includingTax,- customer, priceIncludesTax);+ customer, store, priceIncludesTax);}/// <summary>@@ -320,17 +319,18 @@ public class TaxService : ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>/// <returns>Price</returns>public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product,string taxCategoryId,double price, bool includingTax, Customer customer,- bool priceIncludesTax)+ Store store, bool priceIncludesTax){//no need to calculate tax rate if passed "price" is 0if (price == 0) return (0, 0);- var taxrates = await GetTaxRate(product, taxCategoryId, customer, price);+ var taxrates = await GetTaxRate(product, taxCategoryId, customer, store, price);if (priceIncludesTax){@@ -373,6 +373,7 @@ public class TaxService : ITaxServicepublic virtual async Task<TaxProductPrice> GetTaxProductPrice(Product product,Customer customer,+ Store store,double unitPrice,double unitPriceWithoutDisc,int quantity,@@ -381,7 +382,7 @@ public class TaxService : ITaxServicebool priceIncludesTax){- var taxrates = await GetTaxRate(product, product.TaxCategoryId, customer, 0);+ var taxrates = await GetTaxRate(product, product.TaxCategoryId, customer, store, 0);var productPrice = new TaxProductPrice {TaxRate = taxrates.taxRate,@@ -466,10 +467,10 @@ public class TaxService : ITaxService/// <param name="price">Price</param>/// <param name="customer">Customer</param>/// <returns>Price</returns>- public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer)+ public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer, Store store){var includingTax = _contextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;- return await GetShippingPrice(price, includingTax, customer);+ return await GetShippingPrice(price, includingTax, customer, store);}/// <summary>@@ -478,16 +479,16 @@ public class TaxService : ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax,- Customer customer)+ Customer customer, Store store){if (!_taxSettings.ShippingIsTaxable) return (price, 0);var taxCategoryId = _taxSettings.ShippingTaxCategoryId;var priceIncludesTax = _taxSettings.ShippingPriceIncludesTax;- var prices = await GetProductPrice(null, taxCategoryId, price, includingTax, customer,- priceIncludesTax);+ var prices = await GetProductPrice(null, taxCategoryId, price, includingTax, customer, store, priceIncludesTax);return (prices.productprice, prices.taxRate);}@@ -496,12 +497,12 @@ public class TaxService : ITaxService/// </summary>/// <param name="price">Price</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price,- Customer customer)+ public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, Customer customer, Store store){var includingTax = _contextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;- return await GetPaymentMethodAdditionalFee(price, includingTax, customer);+ return await GetPaymentMethodAdditionalFee(price, includingTax, customer, store);}/// <summary>@@ -510,15 +511,14 @@ public class TaxService : ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price,- bool includingTax, Customer customer)+ public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, bool includingTax, Customer customer, Store store){if (!_taxSettings.PaymentMethodAdditionalFeeIsTaxable) return (price, 0);var taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxCategoryId;var priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax;- var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,- priceIncludesTax);+ var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer, store, priceIncludesTax);return (prices.productprice, prices.taxRate);}@@ -528,11 +528,11 @@ public class TaxService : ITaxService/// <param name="ca">Checkout attribute</param>/// <param name="cav">Checkout attribute value</param>/// <returns>Price</returns>- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav)+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav){var customer = _contextAccessor.WorkContext.CurrentCustomer;- return await GetCheckoutAttributePrice(ca, cav, customer);+ var store = _contextAccessor.StoreContext.CurrentStore;+ return await GetCheckoutAttributePrice(ca, cav, customer, store);}/// <summary>@@ -541,12 +541,12 @@ public class TaxService : ITaxService/// <param name="ca">Checkout attribute</param>/// <param name="cav">Checkout attribute value</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav, Customer customer)+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, Customer customer, Store store){var includingTax = _contextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;- return await GetCheckoutAttributePrice(ca, cav, includingTax, customer);+ return await GetCheckoutAttributePrice(ca, cav, includingTax, customer, store);}/// <summary>@@ -556,9 +556,9 @@ public class TaxService : ITaxService/// <param name="cav">Checkout attribute value</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav, bool includingTax, Customer customer)+ public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, bool includingTax, Customer customer, Store store){ArgumentNullException.ThrowIfNull(ca);ArgumentNullException.ThrowIfNull(cav);@@ -569,7 +569,7 @@ public class TaxService : ITaxServicevar priceIncludesTax = _taxSettings.PricesIncludeTax;var taxClassId = ca.TaxCategoryId;var prices = await GetProductPrice(null, taxClassId, price, includingTax, customer,- priceIncludesTax);+ store, priceIncludesTax);return (prices.productprice, prices.taxRate);}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.csindex 6b330e57c..dad11a8ab 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs@@ -376,8 +376,8 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Placeprotected virtual async Task<PlaceOrderContainer> PreparePlaceOrderDetails(){var details = new PlaceOrderContainer {- //customer- Customer = _contextAccessor.WorkContext.CurrentCustomer+ Customer = _contextAccessor.WorkContext.CurrentCustomer,+ Store = _contextAccessor.StoreContext.CurrentStore,};if (details.Customer == null)throw new ArgumentException("Customer is not set");@@ -432,7 +432,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Placedetails.Customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,_contextAccessor.StoreContext.CurrentStore.Id);details.CheckoutAttributeDescription =- await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Customer);+ await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Customer, details.Store);//load and validate customer shopping cartdetails.Cart = details.Customer.ShoppingCartItems@@ -572,10 +572,10 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Placevar paymentAdditionalFee =await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);details.PaymentAdditionalFeeInclTax =- (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer))+ (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer, details.Store)).paymentPrice;details.PaymentAdditionalFeeExclTax =- (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer))+ (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer, details.Store)).paymentPrice;//tax total@@ -618,7 +618,8 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Placevar (scSubTotal, discountAmount, scDiscounts) = await _pricingService.GetSubTotal(sc, product);- var prices = await _taxService.GetTaxProductPrice(product, details.Customer, scUnitPrice,+ var prices = await _taxService.GetTaxProductPrice(product, details.Customer,+ details.Store, scUnitPrice,scUnitPriceWithoutDisc, sc.Quantity, scSubTotal, discountAmount, _taxSettings.PricesIncludeTax);var scUnitPriceWithoutDiscInclTax = prices.UnitPriceWithoutDiscInclTax;var scUnitPriceWithoutDiscExclTax = prices.UnitPriceWithoutDiscExclTax;diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.csindex 1a274f410..28387414c 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs@@ -7,6 +7,7 @@ using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Orders;+using Grand.Domain.Stores;using Grand.Infrastructure;using Grand.SharedKernel.Extensions;using System.Net;@@ -42,6 +43,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter/// </summary>/// <param name="customAttributes">Attributes</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="separator">Separator</param>/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>@@ -49,6 +51,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter/// <returns>Attributes</returns>public virtual async Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,Customer customer,+ Store store,string separator = "<br />",bool htmlEncode = true,bool renderPrices = true,@@ -128,7 +131,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatterif (renderPrices){var priceAdjustmentBase =- (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer))+ (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer, store)).checkoutPrice;var priceAdjustment =await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase,diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.csindex 64a9acda9..f489bc16e 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -312,6 +312,7 @@ public class OrderCalculationService : IOrderCalculationService//get the customervar customer = _contextAccessor.WorkContext.CurrentCustomer;+ var store = _contextAccessor.StoreContext.CurrentStore;//sub totalsdouble subTotalExclTaxWithoutDiscount = 0;@@ -325,10 +326,10 @@ public class OrderCalculationService : IOrderCalculationServicevar subtotal = await _pricingService.GetSubTotal(shoppingCartItem, product);var sciSubTotal = subtotal.subTotal;- var pricesExcl = await _taxService.GetProductPrice(product, sciSubTotal, false, customer);+ var pricesExcl = await _taxService.GetProductPrice(product, sciSubTotal, false, customer, store);var sciExclTax = pricesExcl.productprice;- var (sciInclTax, taxRate) = await _taxService.GetProductPrice(product, sciSubTotal, true, customer);+ var (sciInclTax, taxRate) = await _taxService.GetProductPrice(product, sciSubTotal, true, customer, store);subTotalExclTaxWithoutDiscount += sciExclTax;subTotalInclTaxWithoutDiscount += sciInclTax;@@ -345,25 +346,15 @@ public class OrderCalculationService : IOrderCalculationService//checkout attributesif (customer != null){- var checkoutAttributes =- customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,- _contextAccessor.StoreContext.CurrentStore.Id);+ var checkoutAttributes = customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, store.Id);var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes);foreach (var attributeValue in attributeValues){- var checkoutAttributePriceExclTax =- await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false,- customer);- var caExclTax =- await _currencyService.ConvertFromPrimaryStoreCurrency(- checkoutAttributePriceExclTax.checkoutPrice, _contextAccessor.WorkContext.WorkingCurrency);-- var (checkoutPrice, taxRate) =- await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true,- customer);- var caInclTax =- await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice,- _contextAccessor.WorkContext.WorkingCurrency);+ var checkoutAttributePriceExclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer, store);++ var caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, _contextAccessor.WorkContext.WorkingCurrency);+ var (checkoutPrice, taxRate) = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer, store);+ var caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice, _contextAccessor.WorkContext.WorkingCurrency);subTotalExclTaxWithoutDiscount += caExclTax;subTotalInclTaxWithoutDiscount += caInclTax;@@ -385,8 +376,7 @@ public class OrderCalculationService : IOrderCalculationServicesubTotalWithoutDiscount = 0;if (_shoppingCartSettings.RoundPrices)- subTotalWithoutDiscount =- RoundingHelper.RoundPrice(subTotalWithoutDiscount, _contextAccessor.WorkContext.WorkingCurrency);+ subTotalWithoutDiscount = RoundingHelper.RoundPrice(subTotalWithoutDiscount, _contextAccessor.WorkContext.WorkingCurrency);//We calculate discount amount on order subtotal excl tax (discount first)//calculate discount amount ('Applied to order subtotal' discount)@@ -573,6 +563,7 @@ public class OrderCalculationService : IOrderCalculationServicedouble taxRate = 0;var customer = _contextAccessor.WorkContext.CurrentCustomer;+ var store = _contextAccessor.StoreContext.CurrentStore;var currency = await _currencyService.GetPrimaryExchangeRateCurrency();var isFreeShipping = await IsFreeShipping(cart);@@ -646,7 +637,7 @@ public class OrderCalculationService : IOrderCalculationServiceif (_shoppingCartSettings.RoundPrices)shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value, currency);- var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer);+ var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer, store);double? shippingTotalTaxed = shippingPrice.shippingPrice;taxRate = shippingPrice.taxRate;@@ -674,6 +665,8 @@ public class OrderCalculationService : IOrderCalculationServicevar taxRates = new SortedDictionary<double, double>();var customer = _contextAccessor.WorkContext.CurrentCustomer;+ var store = _contextAccessor.StoreContext.CurrentStore;+var paymentMethodSystemName = "";if (customer != null)paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(@@ -732,12 +725,11 @@ public class OrderCalculationService : IOrderCalculationServiceawait _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);var additionalFeeExclTax =- await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer, store);var paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;var (paymentMethodAdditionalFeeInclTax, taxRate) =- await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);-+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer, store);paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;//ensure that tax is equal or greater than zeroif (paymentMethodAdditionalFeeTax < 0)@@ -806,7 +798,7 @@ public class OrderCalculationService : IOrderCalculationServiceawait _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);paymentMethodAdditionalFeeWithoutTax =(await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false,- _contextAccessor.WorkContext.CurrentCustomer))+ _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)).paymentPrice;}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.csindex a8b1c5adf..d7659084e 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs@@ -10,8 +10,9 @@ public interface ITaxCategoryService/// <summary>/// Gets all tax categories/// </summary>+ /// <param name="storeId">Store identifier; pass empty to return all</param>/// <returns>Tax categories</returns>- Task<IList<TaxCategory>> GetAllTaxCategories();+ Task<IList<TaxCategory>> GetAllTaxCategories(string storeId = "");/// <summary>/// Gets a tax categorydiff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.csindex d1e33db6c..9aa86712c 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs@@ -3,6 +3,7 @@ using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Orders;+using Grand.Domain.Stores;namespace Grand.Business.Core.Interfaces.Catalog.Tax;@@ -47,8 +48,9 @@ public interface ITaxService/// <param name="product">Product</param>/// <param name="price">Price</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, Customer customer);+ Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, Customer customer, Store store);/// <summary>/// Gets price@@ -57,9 +59,9 @@ public interface ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, bool includingTax,- Customer customer);+ Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price, bool includingTax, Customer customer, Store store);/// <summary>/// Gets price@@ -70,9 +72,10 @@ public interface ITaxService/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>/// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>Task<(double productprice, double taxRate)> GetProductPrice(Product product, string taxCategoryId, double price,- bool includingTax, Customer customer, bool priceIncludesTax);+ bool includingTax, Customer customer, Store store, bool priceIncludesTax);/// <summary>@@ -80,6 +83,7 @@ public interface ITaxService/// </summary>/// <param name="product">Product</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="unitPrice">Unit Price</param>/// <param name="unitPriceWithoutDisc">Unit price without discount</param>/// <param name="quantity">Quantity</param>@@ -90,6 +94,7 @@ public interface ITaxServiceTask<TaxProductPrice> GetTaxProductPrice(Product product,Customer customer,+ Store store,double unitPrice,double unitPriceWithoutDisc,int quantity,@@ -103,8 +108,9 @@ public interface ITaxService/// </summary>/// <param name="price">Price</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer);+ Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer, Store store);/// <summary>/// Gets shipping price@@ -112,16 +118,18 @@ public interface ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax, Customer customer);+ Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, bool includingTax, Customer customer, Store store);/// <summary>/// Gets payment method additional handling fee/// </summary>/// <param name="price">Price</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, Customer customer);+ Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, Customer customer, Store store);/// <summary>/// Gets payment method additional handling fee@@ -129,9 +137,9 @@ public interface ITaxService/// <param name="price">Price</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, bool includingTax,- Customer customer);+ Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price, bool includingTax, Customer customer, Store store);/// <summary>/// Gets checkout attribute value price@@ -139,8 +147,7 @@ public interface ITaxService/// <param name="ca">Checkout attribute</param>/// <param name="cav">Checkout attribute value</param>/// <returns>Price</returns>- Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav);+ Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav);/// <summary>/// Gets checkout attribute value price@@ -148,9 +155,9 @@ public interface ITaxService/// <param name="ca">Checkout attribute</param>/// <param name="cav">Checkout attribute value</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav, Customer customer);+ Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, Customer customer, Store store);/// <summary>/// Gets checkout attribute value price@@ -159,9 +166,9 @@ public interface ITaxService/// <param name="cav">Checkout attribute value</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <returns>Price</returns>- Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,- CheckoutAttributeValue cav, bool includingTax, Customer customer);+ Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, bool includingTax, Customer customer, Store store);/// <summary>/// Gets a value indicating whether a product is tax exempt@@ -178,4 +185,4 @@ public interface ITaxService/// <param name="customer">Customer</param>/// <returns>Result</returns>Task<bool> IsVatExempt(Address address, Customer customer);-}\ No newline at end of file+}diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.csindex d25bb9ec1..ef50d2e43 100644--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs@@ -1,5 +1,6 @@using Grand.Domain.Common;using Grand.Domain.Customers;+using Grand.Domain.Stores;namespace Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;@@ -17,9 +18,11 @@ public interface ICheckoutAttributeFormatter/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>/// <param name="renderPrices">A value indicating whether to render prices</param>/// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>+ /// <param name="store">Store</param>/// <returns>Attributes</returns>Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,Customer customer,+ Store store,string separator = "<br />",bool htmlEncode = true,bool renderPrices = true,diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.csindex 0a065ffb7..98a14c26e 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs@@ -1,6 +1,7 @@using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;+using Grand.Domain.Stores;namespace Grand.Business.Core.Utilities.Catalog;@@ -24,6 +25,11 @@ public class TaxRequest/// </summary>public Address Address { get; set; }+ /// <summary>+ /// Gets or sets the store in which the tax is being calculated+ /// </summary>+ public Store Store { get; set; }+/// <summary>/// Gets or sets a tax category identifier/// </summary>diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.csindex 660ae28fd..5c6849cbf 100644--- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs+++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs@@ -6,6 +6,7 @@ using Grand.Domain.Directory;using Grand.Domain.Localization;using Grand.Domain.Orders;using Grand.Domain.Shipping;+using Grand.Domain.Stores;using Grand.Domain.Tax;namespace Grand.Business.Core.Utilities.Checkout;@@ -13,6 +14,7 @@ namespace Grand.Business.Core.Utilities.Checkout;public class PlaceOrderContainer{public Customer Customer { get; set; }+ public Store Store { get; set; }public Language Language { get; set; }public Currency Currency { get; set; }public string AffiliateId { get; set; }diff --git a/src/Core/Grand.Domain/Tax/TaxCategory.cs b/src/Core/Grand.Domain/Tax/TaxCategory.csindex 322cd41fc..f6236219c 100644--- a/src/Core/Grand.Domain/Tax/TaxCategory.cs+++ b/src/Core/Grand.Domain/Tax/TaxCategory.cs@@ -14,4 +14,9 @@ public class TaxCategory : BaseEntity/// Gets or sets the display order/// </summary>public int DisplayOrder { get; set; }++ /// <summary>+ /// Gets or sets the store identifier (empty = available to all stores)+ /// </summary>+ public string StoreId { get; set; }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.csindex 7cdd207cd..660c6befc 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs@@ -162,7 +162,10 @@ public static partial class CacheKey/// <summary>/// Key for caching/// </summary>- public static string TAXCATEGORIES_ALL_KEY => "Grand.taxcategory.all";+ /// <remarks>+ /// {0} : store ID (empty = all stores)+ /// </remarks>+ public static string TAXCATEGORIES_ALL_KEY => "Grand.taxcategory.all-{0}";/// <summary>/// Key for cachingdiff --git a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.csindex fa899e62e..6c93cf107 100644--- a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs+++ b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs@@ -68,7 +68,7 @@ public class TaxCountryStateZipController : BaseAdminPluginController[AutoValidateAntiforgeryToken]public async Task<IActionResult> RatesList(DataSourceRequest command){- var records = await _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);+ var records = await _taxRateService.GetAllTaxRates(pageIndex: command.Page - 1, pageSize: command.PageSize);var taxRatesModel = new List<TaxRateModel>();foreach (var x in records){diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Store/Controllers/TaxCountryStateZipController.cs b/src/Plugins/Tax.CountryStateZip/Areas/Store/Controllers/TaxCountryStateZipController.csnew file mode 100644index 000000000..dac234747--- /dev/null+++ b/src/Plugins/Tax.CountryStateZip/Areas/Store/Controllers/TaxCountryStateZipController.cs@@ -0,0 +1,172 @@+using Grand.Business.Core.Interfaces.Catalog.Tax;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Rendering;+using Tax.CountryStateZip.Domain;+using Tax.CountryStateZip.Models;+using Tax.CountryStateZip.Services;++namespace Tax.CountryStateZip.Areas.Store.Controllers;++/// <summary>+/// Store-manager configuration of the country/state/zip tax provider.+/// A store owner can add, edit and delete tax rates, but only the ones that+/// belong to his own store (<see cref="CurrentStoreId" />). Records owned by+/// other stores or global (store = *) records are never returned nor mutated.+/// </summary>+[Area("Store")]+[AuthorizeStore]+[AuthorizeMenu]+[AutoValidateAntiforgeryToken]+[PermissionAuthorize(PermissionSystemName.TaxSettings)]+public class TaxCountryStateZipController : BaseController+{+ private readonly IContextAccessor _contextAccessor;+ private readonly ICountryService _countryService;+ private readonly ITaxCategoryService _taxCategoryService;+ private readonly ITaxRateService _taxRateService;++ public TaxCountryStateZipController(ITaxCategoryService taxCategoryService,+ ICountryService countryService,+ ITaxRateService taxRateService,+ IContextAccessor contextAccessor)+ {+ _taxCategoryService = taxCategoryService;+ _countryService = countryService;+ _taxRateService = taxRateService;+ _contextAccessor = contextAccessor;+ }++ /// <summary>+ /// The store the current staff/store-manager is bound to.+ /// </summary>+ private string CurrentStoreId => _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ public async Task<IActionResult> Configure()+ {+ var taxCategories = await _taxCategoryService.GetAllTaxCategories(CurrentStoreId);+ if (taxCategories.Count == 0)+ return Content("No tax categories can be loaded");++ var model = new TaxRateListModel {+ //the store owner can only add records for his own store, so no store selector is offered+ AddStoreId = CurrentStoreId+ };++ //tax categories+ foreach (var tc in taxCategories)+ model.AvailableTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id });++ //countries+ var countries = await _countryService.GetAllCountries(showHidden: true);+ foreach (var c in countries)+ model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id });++ //states+ model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" });+ var defaultCountry = countries.FirstOrDefault();+ if (defaultCountry != null)+ {+ var states = await _countryService.GetStateProvincesByCountryId(defaultCountry.Id);+ foreach (var s in states)+ model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id });+ }++ return View(model);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> RatesList(DataSourceRequest command)+ {+ //only the current store records - filtered and paged in the service layer+ var records = await _taxRateService.GetAllTaxRates(CurrentStoreId, command.Page - 1, command.PageSize);++ var taxRatesModel = new List<TaxRateModel>();+ foreach (var x in records)+ {+ var m = new TaxRateModel {+ Id = x.Id,+ StoreId = x.StoreId,+ TaxCategoryId = x.TaxCategoryId,+ CountryId = x.CountryId,+ StateProvinceId = x.StateProvinceId,+ Zip = x.Zip,+ Percentage = x.Percentage+ };+ //tax category+ var tc = await _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);+ m.TaxCategoryName = tc != null ? tc.Name : "";+ //country+ var c = await _countryService.GetCountryById(x.CountryId);+ m.CountryName = c != null ? c.Name : "Unavailable";+ //state+ var s = c?.StateProvinces.FirstOrDefault(z => z.Id == x.StateProvinceId);+ m.StateProvinceName = s != null ? s.Name : "*";+ //zip+ m.Zip = !string.IsNullOrEmpty(x.Zip) ? x.Zip : "*";+ taxRatesModel.Add(m);+ }++ var gridModel = new DataSourceResult {+ Data = taxRatesModel,+ Total = records.TotalCount+ };++ return Json(gridModel);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> RateUpdate(TaxRateModel model)+ {+ var taxRate = await _taxRateService.GetTaxRateById(model.Id);+ //guard: a store owner can only edit his own store records+ if (taxRate == null || taxRate.StoreId != CurrentStoreId)+ return new JsonResult("");++ taxRate.Zip = model.Zip == "*" ? null : model.Zip;+ taxRate.Percentage = model.Percentage;+ await _taxRateService.UpdateTaxRate(taxRate);++ return new JsonResult("");+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ public async Task<IActionResult> RateDelete(string id)+ {+ var taxRate = await _taxRateService.GetTaxRateById(id);+ //guard: a store owner can only delete his own store records+ if (taxRate == null || taxRate.StoreId != CurrentStoreId)+ return new JsonResult("");++ await _taxRateService.DeleteTaxRate(taxRate);++ return new JsonResult("");+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> AddTaxRate(TaxRateListModel model)+ {+ var taxRate = new TaxRate {+ //force the current store - the owner cannot create records for another store+ StoreId = CurrentStoreId,+ TaxCategoryId = model.AddTaxCategoryId,+ CountryId = model.AddCountryId,+ StateProvinceId = model.AddStateProvinceId,+ Zip = model.AddZip,+ Percentage = model.AddPercentage+ };+ await _taxRateService.InsertTaxRate(taxRate);++ return Json(new { Result = true });+ }+}diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/TaxCountryStateZip/Configure.cshtml b/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/TaxCountryStateZip/Configure.cshtmlnew file mode 100644index 000000000..b4aca0061--- /dev/null+++ b/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/TaxCountryStateZip/Configure.cshtml@@ -0,0 +1,248 @@+@using Microsoft.AspNetCore.Routing+@model Tax.CountryStateZip.Models.TaxRateListModel+@{+ Layout = "~/Areas/Store/Views/Shared/_StoreLayout.cshtml";+ ViewBag.Title = Loc["Admin.Configuration.Tax.Providers"];+}+<input id="active-menu-item" type="hidden" value="/Store/Tax/Providers"/>++<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["Tax.CountryStateZip.FriendlyName"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="x_content">+ <div id="tax-countrystatezip-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+ $(document).ready(function () {+ $("#tax-countrystatezip-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("RatesList", "TaxCountryStateZip", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ update: {+ url: "@Html.Raw(Url.Action("RateUpdate", "TaxCountryStateZip", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ destroy: {+ url: "@Html.Raw(Url.Action("RateDelete", "TaxCountryStateZip", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id",+ fields: {+ CountryName: { editable: false, type: "string" },+ StateProvinceName: { editable: false, type: "string" },+ Zip: { editable: true, type: "string" },+ TaxCategoryName: { editable: false, type: "string" },+ Percentage: { editable: true, type: "number" },+ Id: { editable: false, type: "string" }+ }+ }+ },+ requestEnd: function (e) {+ if (e.type == "update") {+ this.read();+ }+ },+ error: function (e) {+ display_kendoui_grid_error(e);+ // Cancel the changes+ this.cancelChanges();+ },+ pageSize: 15,+ serverPaging: true,+ serverFiltering: true,+ serverSorting: true+ },+ pageable: {+ refresh: true,+ pageSizes: [15, 30, 50]+ },+ editable: {+ confirmation: false,+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "CountryName",+ title: "@Loc["Plugins.Tax.CountryStateZip.Fields.Country"]",+ width: 200+ }, {+ field: "StateProvinceName",+ title: "@Loc["Plugins.Tax.CountryStateZip.Fields.StateProvince"]",+ width: 200+ }, {+ field: "Zip",+ title: "@Loc["Plugins.Tax.CountryStateZip.Fields.Zip"]",+ width: 200+ }, {+ field: "TaxCategoryName",+ title: "@Loc["Plugins.Tax.CountryStateZip.Fields.TaxCategory"]",+ width: 200+ }, {+ field: "Percentage",+ title: "@Loc["Plugins.Tax.CountryStateZip.Fields.Percentage"]",+ width: 100,+ editor: function (container, options) {+ $('<input name="' + options.field + '"/>')+ .appendTo(container)+ .kendoNumericTextBox({+ format: "{0:n4}",+ doubles: 4+ });+ }+ }, {+ command: [{+ name: "edit",+ text: "@Loc["Admin.Common.Edit"]"+ }, {+ name: "destroy",+ text: "@Loc["Admin.Common.Delete"]"+ }],+ width: 200+ }]+ });+ });+</script>++<script>+ $(document).ready(function () {+ $("#@Html.IdFor(model => model.AddCountryId)").change(function () {+ var selectedItem = $(this).val();+ var ddlStates = $("#@Html.IdFor(model => model.AddStateProvinceId)");+ $.ajax({+ cache: false,+ type: "GET",+ url: "@(Url.Action("GetStatesByCountryId", "Home", new RouteValueDictionary { { "area", "Store" } }))",+ data: { "countryId": selectedItem, "addAsterisk": "true" },+ success: function (data) {+ ddlStates.html('');+ $.each(data, function (id, option) {+ ddlStates.append($('<option></option>').val(option.id).html(option.name));+ });+ },+ error: function (xhr, ajaxOptions, thrownError) {+ alert('Failed to retrieve states.');+ }+ });+ });+ });+</script>++<form asp-controller="TaxCountryStateZip" asp-action="Configure" asp-route-area="Store" method="post">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="note note-info">+ @Loc["Plugins.Tax.CountryStateZip.AddRecord.Hint"]+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AddCountryId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="AddCountryId" asp-items="Model.AvailableCountries"/>+ <span asp-validation-for="AddCountryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AddStateProvinceId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="AddStateProvinceId" asp-items="Model.AvailableStates"/>+ <span asp-validation-for="AddStateProvinceId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AddZip" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="AddZip"/>+ <span asp-validation-for="AddZip"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AddTaxCategoryId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="AddTaxCategoryId" asp-items="Model.AvailableTaxCategories"/>+ <span asp-validation-for="AddTaxCategoryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AddPercentage" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="AddPercentage"/>+ <span asp-validation-for="AddPercentage"></span>+ </div>+ </div>+ </div>+ <div class="form-actions">+ <div class="row">+ <div class="offset-md-3 offset-sm-3 col-md-9 col-sm-9">+ <input type="button" id="addtaxrate" class="btn green" value="@Loc["Plugins.Tax.CountryStateZip.AddRecord"]"/>+ </div>+ </div>+ </div>+ </div>+ <script>+ $(function () {+ $('#addtaxrate').click(function () {++ var postData = $(this.form).serialize();+ addAntiForgeryToken(postData);++ $.ajax({+ cache: false,+ type: 'POST',+ url: "@Html.Raw(Url.Action("AddTaxRate", "TaxCountryStateZip", new { area = "Store" }))",+ data: postData,+ dataType: 'json',+ success: function (data) {+ var grid = $("#tax-countrystatezip-grid").data('kendoGrid');+ grid.dataSource.read();+ },+ error: function (xhr, ajaxOptions, thrownError) {+ alert('Failed to add record.');+ }+ });+ return false;+ });+ });+ </script>+</form>diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/_ViewImports.cshtml b/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/_ViewImports.cshtmlnew file mode 100644index 000000000..0d1778c76--- /dev/null+++ b/src/Plugins/Tax.CountryStateZip/Areas/Store/Views/_ViewImports.cshtml@@ -0,0 +1,8 @@+@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers+@addTagHelper *, Grand.Web.Common++@using Microsoft.AspNetCore.Mvc.ViewFeatures+@using Grand.Infrastructure.Extensions+@using Grand.Web.Common.Localization++@inject LocService Locdiff --git a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.csindex 5520072d0..f584cb98e 100644--- a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs+++ b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs@@ -1,7 +1,6 @@-using Grand.Business.Core.Interfaces.Catalog.Tax;+using Grand.Business.Core.Interfaces.Catalog.Tax;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Utilities.Catalog;-using Grand.Infrastructure;using Grand.Infrastructure.Caching;using Tax.CountryStateZip.Infrastructure.Cache;using Tax.CountryStateZip.Services;@@ -15,18 +14,15 @@ public class CountryStateZipTaxProvider : ITaxProviderprivate readonly CountryStateZipTaxSettings _countryStateZipTaxSettings;private readonly ITaxRateService _taxRateService;private readonly ITranslationService _translationService;- private readonly IContextAccessor _contextAccessor;public CountryStateZipTaxProvider(ITranslationService translationService,ICacheBase cacheBase,- IContextAccessor contextAccessor,ITaxRateService taxRateService,CountryStateZipTaxSettings countryStateZipTaxSettings){_translationService = translationService;_cacheBase = cacheBase;- _contextAccessor = contextAccessor;_taxRateService = taxRateService;_countryStateZipTaxSettings = countryStateZipTaxSettings;}@@ -51,65 +47,62 @@ public class CountryStateZipTaxProvider : ITaxProvider/// <returns>Tax</returns>public async Task<TaxResult> GetTaxRate(TaxRequest calculateTaxRequest){- var result = new TaxResult();-if (calculateTaxRequest.Address == null){- result.Errors.Add("Address is not set");- return result;+ var errorResult = new TaxResult();+ errorResult.Errors.Add("Address is not set");+ return errorResult;}- const string cacheKey = ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY;- var allTaxRates = await _cacheBase.GetAsync(cacheKey, async () =>- {- var taxes = await _taxRateService.GetAllTaxRates();- return taxes.Select(x => new TaxRateForCaching {- Id = x.Id,- StoreId = x.StoreId,- TaxCategoryId = x.TaxCategoryId,- CountryId = x.CountryId,- StateProvinceId = x.StateProvinceId,- Zip = x.Zip,- Percentage = x.Percentage- });- });-- var storeId = _contextAccessor.StoreContext.CurrentStore.Id;- var taxCategoryId = calculateTaxRequest.TaxCategoryId;- var countryId = calculateTaxRequest.Address.CountryId;- var stateProvinceId = calculateTaxRequest.Address.StateProvinceId;- var zip = calculateTaxRequest.Address.ZipPostalCode?.Trim() ?? string.Empty;-- var existingRates = allTaxRates- .Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId).ToList();-- //filter by store- var matchedByStore = existingRates.Where(taxRate => storeId == taxRate.StoreId).ToList();-- //not found? use the default ones (ID == 0)- if (!matchedByStore.Any())- matchedByStore.AddRange(existingRates.Where(taxRate => string.IsNullOrEmpty(taxRate.StoreId)));-- //filter by state/province- var matchedByStateProvince =- matchedByStore.Where(taxRate => stateProvinceId == taxRate.StateProvinceId).ToList();-- //not found? use the default ones (ID == 0)- if (!matchedByStateProvince.Any())- matchedByStateProvince.AddRange(matchedByStore.Where(taxRate =>- string.IsNullOrEmpty(taxRate.StateProvinceId)));-- //filter by zip- if(!string.IsNullOrEmpty(zip))- {- var matchedByZip = matchedByStateProvince.Where(taxRate => zip.Equals(taxRate.Zip, StringComparison.OrdinalIgnoreCase)).ToList();- if (matchedByZip.Any())- {- result.TaxRate = matchedByZip[0].Percentage;- return result;- }- }+ var allTaxRates = await GetAllTaxRatesFromCache();++ var address = calculateTaxRequest.Address;+ var storeId = calculateTaxRequest.Store?.Id ?? string.Empty;+ var zip = address.ZipPostalCode?.Trim() ?? string.Empty;++ var byCountryAndCategory = allTaxRates+ .Where(r => r.CountryId == address.CountryId && r.TaxCategoryId == calculateTaxRequest.TaxCategoryId)+ .ToList();++ var byStore = MatchOrFallback(byCountryAndCategory,+ r => r.StoreId == storeId,+ r => string.IsNullOrEmpty(r.StoreId));++ var byStateProvince = MatchOrFallback(byStore,+ r => r.StateProvinceId == address.StateProvinceId,+ r => string.IsNullOrEmpty(r.StateProvinceId));- return result;+ var matched = byStateProvince+ .OrderByDescending(r => !string.IsNullOrWhiteSpace(r.Zip))+ .FirstOrDefault(r =>+ string.IsNullOrWhiteSpace(r.Zip) ||+ (!string.IsNullOrEmpty(zip) && zip.Equals(r.Zip, StringComparison.OrdinalIgnoreCase)));++ return new TaxResult { TaxRate = matched?.Percentage ?? 0 };+ }++ private async Task<List<TaxRateForCaching>> GetAllTaxRatesFromCache()+ {+ return await _cacheBase.GetAsync(+ ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY,+ async () => (await _taxRateService.GetAllTaxRates())+ .Select(x => new TaxRateForCaching {+ Id = x.Id,+ StoreId = x.StoreId,+ TaxCategoryId = x.TaxCategoryId,+ CountryId = x.CountryId,+ StateProvinceId = x.StateProvinceId,+ Zip = x.Zip,+ Percentage = x.Percentage+ }).ToList());+ }++ private static List<TaxRateForCaching> MatchOrFallback(+ List<TaxRateForCaching> source,+ Func<TaxRateForCaching, bool> exact,+ Func<TaxRateForCaching, bool> fallback)+ {+ List<TaxRateForCaching> matched = [..source.Where(exact)];+ return matched.Count > 0 ? matched : [..source.Where(fallback)];}-}\ No newline at end of file+}diff --git a/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.csindex bd462a29e..565ef62bc 100644--- a/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs+++ b/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs@@ -17,8 +17,11 @@ public interface ITaxRateService/// <summary>/// Gets all tax rates/// </summary>+ /// <param name="storeId">Store identifier; pass an empty string to return rates of all stores</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>/// <returns>Tax rates</returns>- Task<IPagedList<TaxRate>> GetAllTaxRates(int pageIndex = 0, int pageSize = int.MaxValue);+ Task<IPagedList<TaxRate>> GetAllTaxRates(string storeId = "", int pageIndex = 0, int pageSize = int.MaxValue);/// <summary>/// Gets a tax ratediff --git a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.csindex ddff99786..cb0cd9c3b 100644--- a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs+++ b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs@@ -33,7 +33,7 @@ public class TaxRateService : ITaxRateService#region Constants- private const string TAXRATE_ALL_KEY = "Grand.taxrate.all-{0}-{1}";+ private const string TAXRATE_ALL_KEY = "Grand.taxrate.all-{0}-{1}-{2}";private const string TAXRATE_PATTERN_KEY = "Grand.taxrate.";#endregion@@ -68,15 +68,22 @@ public class TaxRateService : ITaxRateService/// Gets all tax rates/// </summary>/// <returns>Tax rates</returns>- public virtual async Task<IPagedList<TaxRate>> GetAllTaxRates(int pageIndex = 0, int pageSize = int.MaxValue)+ public virtual async Task<IPagedList<TaxRate>> GetAllTaxRates(string storeId = "", int pageIndex = 0,+ int pageSize = int.MaxValue){- var key = string.Format(TAXRATE_ALL_KEY, pageIndex, pageSize);+ var key = string.Format(TAXRATE_ALL_KEY, storeId, pageIndex, pageSize);return await _cacheBase.GetAsync(key, async () =>{- var query = from tr in _taxRateRepository.Table- orderby tr.StoreId, tr.CountryId, tr.StateProvinceId, tr.Zip, tr.TaxCategoryId- select tr;- return await Task.FromResult(new PagedList<TaxRate>(query, pageIndex, pageSize));+ var query = _taxRateRepository.Table.AsQueryable();+ //filter by store when requested; an empty storeId returns rates of all stores+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(tr => tr.StoreId == storeId);++ var ordered = query+ .OrderBy(tr => tr.StoreId).ThenBy(tr => tr.CountryId).ThenBy(tr => tr.StateProvinceId)+ .ThenBy(tr => tr.Zip).ThenBy(tr => tr.TaxCategoryId);++ return await Task.FromResult(new PagedList<TaxRate>(ordered, pageIndex, pageSize));});}diff --git a/src/Plugins/Tax.FixedRate/Areas/Store/Controllers/TaxFixedRateController.cs b/src/Plugins/Tax.FixedRate/Areas/Store/Controllers/TaxFixedRateController.csnew file mode 100644index 000000000..ebc39dc4a--- /dev/null+++ b/src/Plugins/Tax.FixedRate/Areas/Store/Controllers/TaxFixedRateController.cs@@ -0,0 +1,103 @@+using Grand.Business.Core.Interfaces.Catalog.Tax;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Tax.FixedRate.Models;++namespace Tax.FixedRate.Areas.Store.Controllers;++/// <summary>+/// Store-manager configuration of the fixed tax rate provider.+/// Shared (global) rates are managed by the administrator and are read-only here -+/// only a store specific rate can be edited, and editing is always scoped to+/// <see cref="CurrentStoreId" /> (it never modifies the shared/other stores value).+/// </summary>+[Area("Store")]+[AuthorizeStore]+[AuthorizeMenu]+[AutoValidateAntiforgeryToken]+[PermissionAuthorize(PermissionSystemName.TaxSettings)]+public class TaxFixedRateController : BaseController+{+ private readonly IContextAccessor _contextAccessor;+ private readonly ISettingService _settingService;+ private readonly ITaxCategoryService _taxCategoryService;++ public TaxFixedRateController(ITaxCategoryService taxCategoryService,+ ISettingService settingService,+ IContextAccessor contextAccessor)+ {+ _taxCategoryService = taxCategoryService;+ _settingService = settingService;+ _contextAccessor = contextAccessor;+ }++ /// <summary>+ /// The store the current staff/store-manager is bound to.+ /// </summary>+ private string CurrentStoreId => _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ public IActionResult Configure()+ {+ return View();+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> Configure(DataSourceRequest command)+ {+ var taxRateModels = new List<FixedTaxRateModel>();+ foreach (var taxCategory in await _taxCategoryService.GetAllTaxCategories(CurrentStoreId))+ {+ taxRateModels.Add(new FixedTaxRateModel {+ TaxCategoryId = taxCategory.Id,+ TaxCategoryName = taxCategory.Name,+ Rate = await GetTaxRate(taxCategory.Id, CurrentStoreId),+ StoreId = taxCategory.StoreId+ });+ }++ var gridModel = new DataSourceResult {+ Data = taxRateModels,+ Total = taxRateModels.Count+ };+ return Json(gridModel);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> TaxRateUpdate(FixedTaxRateModel model)+ {+ if (!await HasStoreRate(model.TaxCategoryId))+ return new JsonResult("");++ await _settingService.SetSetting($"Tax.TaxProvider.FixedRate.TaxCategoryId{model.TaxCategoryId}",+ new FixedTaxRate { Rate = model.Rate }, CurrentStoreId);++ return new JsonResult("");+ }++ /// <summary>+ /// Whether a store specific override exists for the tax category (store = current store).+ /// </summary>+ [NonAction]+ private async Task<bool> HasStoreRate(string taxCategoryId)+ {+ var taxCategory = await _taxCategoryService.GetTaxCategoryById(taxCategoryId);+ return taxCategory != null && taxCategory.StoreId == CurrentStoreId;+ }++ [NonAction]+ private async Task<double> GetTaxRate(string taxCategoryId, string storeId)+ {+ //store override when present, otherwise the shared/global value (built-in fallback)+ var rate = (await _settingService.GetSettingByKey<FixedTaxRate>(+ $"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}", storeId: storeId))?.Rate;+ return rate ?? 0;+ }+}diff --git a/src/Plugins/Tax.FixedRate/Areas/Store/Views/TaxFixedRate/Configure.cshtml b/src/Plugins/Tax.FixedRate/Areas/Store/Views/TaxFixedRate/Configure.cshtmlnew file mode 100644index 000000000..2d13cee2d--- /dev/null+++ b/src/Plugins/Tax.FixedRate/Areas/Store/Views/TaxFixedRate/Configure.cshtml@@ -0,0 +1,128 @@+@{+ Layout = "~/Areas/Store/Views/Shared/_StoreLayout.cshtml";+ ViewBag.Title = Loc["Admin.Configuration.Tax.Providers"];+}+<input id="active-menu-item" type="hidden" value="/Store/Tax/Providers"/>++<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["Tax.FixedRate.FriendlyName"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="x_content">+ <div id="tax-categories-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+ $(document).ready(function () {+ $("#tax-categories-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("Configure", "TaxFixedRate", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ update: {+ url: "@Html.Raw(Url.Action("TaxRateUpdate", "TaxFixedRate", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ parameterMap: function (data, operation) {+ if (operation != "read") {+ data.Rate = kendo.toString(data.Rate, "n8");+ return data;+ } else {+ return data;+ }+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "TaxCategoryId",+ fields: {+ TaxCategoryId: { editable: false, type: "string" },+ StoreId: { editable: false, type: "string", defaultValue: "" },+ TaxCategoryName: { editable: false, type: "string" },+ Rate: { editable: true, type: "number" }+ }+ }+ },+ requestEnd: function (e) {+ if (e.type == "update") {+ this.read();+ }+ },+ error: function (e) {+ display_kendoui_grid_error(e);+ // Cancel the changes+ this.cancelChanges();+ },+ serverPaging: true,+ serverFiltering: true,+ serverSorting: true+ },+ pageable: {+ refresh: true,+ numeric: false,+ previousNext: false,+ info: false+ },+ editable: {+ confirmation: false,+ mode: "inline"+ },+ scrollable: false,+ dataBound: function () {+ var grid = this;+ grid.tbody.find("tr[data-uid]").each(function () {+ var dataItem = grid.dataItem(this);+ //shared/global rate (empty StoreId) is read-only - only store specific rates can be edited+ if (dataItem && !dataItem.StoreId) {+ $(this).find(".k-grid-edit").hide();+ }+ });+ },+ columns: [{+ field: "TaxCategoryName",+ title: "@Loc["Plugins.Tax.FixedRate.Fields.TaxCategoryName"]",+ width: 400+ }, {+ field: "Rate",+ title: "@Loc["Plugins.Tax.FixedRate.Fields.Rate"]",+ width: 200,+ format: "{0:n4}",+ editor: function (container, options) {+ $('<input name="' + options.field + '"/>')+ .appendTo(container)+ .kendoNumericTextBox({+ format: "{0:n4}",+ doubles: 4+ });+ }+ }, {+ command: {name: "edit", text: "@Loc["Admin.Common.Edit"]"},+ title: "@Loc["Admin.Common.Edit"]",+ width: 150+ }]+ });+ });+</script>diff --git a/src/Plugins/Tax.FixedRate/Areas/Store/Views/_ViewImports.cshtml b/src/Plugins/Tax.FixedRate/Areas/Store/Views/_ViewImports.cshtmlnew file mode 100644index 000000000..0d1778c76--- /dev/null+++ b/src/Plugins/Tax.FixedRate/Areas/Store/Views/_ViewImports.cshtml@@ -0,0 +1,8 @@+@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers+@addTagHelper *, Grand.Web.Common++@using Microsoft.AspNetCore.Mvc.ViewFeatures+@using Grand.Infrastructure.Extensions+@using Grand.Web.Common.Localization++@inject LocService Locdiff --git a/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs b/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.csindex f12648aa6..a4e49f3c1 100644--- a/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs+++ b/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs@@ -37,7 +37,8 @@ public class FixedRateTaxProvider : ITaxProviderpublic async Task<TaxResult> GetTaxRate(TaxRequest calculateTaxRequest){var result = new TaxResult {- TaxRate = await GetTaxRate(calculateTaxRequest.TaxCategoryId)+ TaxRate = await GetTaxRate(calculateTaxRequest.TaxCategoryId,+ calculateTaxRequest.Store?.Id ?? string.Empty)};return result;}@@ -46,10 +47,14 @@ public class FixedRateTaxProvider : ITaxProvider/// Gets a tax rate/// </summary>/// <param name="taxCategoryId">The tax category identifier</param>+ /// <param name="storeId">The store identifier the tax is being calculated for</param>/// <returns>Tax rate</returns>- private async Task<double> GetTaxRate(string taxCategoryId)+ private async Task<double> GetTaxRate(string taxCategoryId, string storeId){- var rate = (await _settingService.GetSettingByKey<FixedTaxRate>($"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}"))?.Rate;+ //use the store specific rate when defined, otherwise fall back to the global rate+ //(SettingService.GetSettingByKey resolves the store override first and the global value second)+ var rate = (await _settingService.GetSettingByKey<FixedTaxRate>(+ $"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}", storeId: storeId))?.Rate;return rate ?? 0;}}\ No newline at end of filediff --git a/src/Plugins/Tax.FixedRate/Models/FixedTaxRateModel.cs b/src/Plugins/Tax.FixedRate/Models/FixedTaxRateModel.csindex 0df58e2f8..9e6d45413 100644--- a/src/Plugins/Tax.FixedRate/Models/FixedTaxRateModel.cs+++ b/src/Plugins/Tax.FixedRate/Models/FixedTaxRateModel.cs@@ -6,6 +6,12 @@ public class FixedTaxRateModel{public string TaxCategoryId { get; set; }+ /// <summary>+ /// Store the rate belongs to. Empty means the shared (global) rate, which is read-only+ /// in the store panel; the current store id means a store specific, editable rate.+ /// </summary>+ public string StoreId { get; set; }+[GrandResourceDisplayName("Plugins.Tax.FixedRate.Fields.TaxCategoryName")]public string TaxCategoryName { get; set; }diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.csindex 196298f2e..dfb1bc42d 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs@@ -110,7 +110,7 @@ public class TaxServiceTestsvar product = new Product();_groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));- var pp = await _taxService.GetProductPrice(product, "0", 1000, true, customer, true);+ var pp = await _taxService.GetProductPrice(product, "0", 1000, true, customer, null, true);var price = pp.productprice;Assert.AreEqual(1000, price);}@@ -122,13 +122,13 @@ public class TaxServiceTestsvar product = new Product();Assert.AreEqual(Math.Round(909.0909090, 2),- (await _taxService.GetProductPrice(product, "0", 1000, true, customer, true)).productprice);+ (await _taxService.GetProductPrice(product, "0", 1000, true, customer, null, true)).productprice);Assert.AreEqual(1000,- (await _taxService.GetProductPrice(product, "0", 1000, true, customer, false)).productprice);+ (await _taxService.GetProductPrice(product, "0", 1000, true, customer, null, false)).productprice);Assert.AreEqual(Math.Round(909.0909090, 2),- (await _taxService.GetProductPrice(product, "0", 1000, false, customer, true)).productprice);+ (await _taxService.GetProductPrice(product, "0", 1000, false, customer, null, true)).productprice);Assert.AreEqual(1000,- (await _taxService.GetProductPrice(product, "0", 1000, false, customer, false)).productprice);+ (await _taxService.GetProductPrice(product, "0", 1000, false, customer, null, false)).productprice);}[TestMethod]@@ -158,22 +158,22 @@ public class TaxServiceTests.Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));//these 6 methods..var scUnitPriceInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, null, true)).productprice;var scUnitPriceExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, null, true)).productprice;var scSubTotalInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, null, true)).productprice;var scSubTotalExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, null, true)).productprice;var discountAmountInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, null, true)).productprice;var discountAmountExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, null, true)).productprice;//..should return the same value as this one method's properties are having- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,+ var result02 = await _taxService.GetTaxProductPrice(product, customer, null, scUnitPrice, scUnitPriceWithoutDiscount,1, scSubTotal, discountAmount, true);Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");@@ -204,24 +204,24 @@ public class TaxServiceTestsvar discountAmount = 7000.00;var scUnitPriceInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, null, false)).productprice;var scUnitPriceExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, null, false)).productprice;var scSubTotalInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, null, false)).productprice;var scSubTotalExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, null, false)).productprice;var discountAmountInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, null, false)).productprice;var discountAmountExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, null, false)).productprice;- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,+ var result02 = await _taxService.GetTaxProductPrice(product, customer, null, scUnitPrice, scUnitPriceWithoutDiscount,1, scSubTotal, discountAmount, false);Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");@@ -251,22 +251,22 @@ public class TaxServiceTestsvar discountAmount = 7000.00;var scUnitPriceInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, null, true)).productprice;var scUnitPriceExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, null, true)).productprice;var scSubTotalInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, null, true)).productprice;var scSubTotalExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, null, true)).productprice;var discountAmountInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, null, true)).productprice;var discountAmountExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, null, true)).productprice;- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,+ var result02 = await _taxService.GetTaxProductPrice(product, customer, null, scUnitPrice, scUnitPriceWithoutDiscount,1, scSubTotal, discountAmount, true);Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");@@ -296,24 +296,24 @@ public class TaxServiceTestsvar discountAmount = 7000.00;var scUnitPriceInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, null, false)).productprice;var scUnitPriceExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, null, false)).productprice;var scSubTotalInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, null, false)).productprice;var scSubTotalExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, null, false)).productprice;var discountAmountInclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, null, false)).productprice;var discountAmountExclTax =- (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false))+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, null, false)).productprice;- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,+ var result02 = await _taxService.GetTaxProductPrice(product, customer, null, scUnitPrice, scUnitPriceWithoutDiscount,1, scSubTotal, discountAmount, false);Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Categories.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Categories.cshtmlindex 0d3566e5e..cb5f784ca 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Categories.cshtml+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Categories.cshtml@@ -1,4 +1,5 @@-@{+@model TaxCategoryListModel+@{//page titleViewBag.Title = Loc["Admin.Configuration.Tax.Categories"];}@@ -26,100 +27,117 @@</div></div>-<script>- $(document).ready(function () {- $("#tax-categories-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("Categories", "Tax", new { area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- create: {- url: "@Html.Raw(Url.Action("CategoryAdd", "Tax", new { area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- update: {- url:"@Html.Raw(Url.Action("CategoryUpdate", "Tax", new { area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("CategoryDelete", "Tax", new { area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id",- fields: {- Name: { editable: true, type: "string" },- DisplayOrder: { editable: true, type: "number" },- Id: { editable: false, type: "string" }- }- }+ var storesData = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(+ Model.AvailableStores.Select(s => new { text = s.Text, value = s.Value })+ ));++ $(document).ready(function () {+ $("#tax-categories-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("Categories", "Tax", new { area = Constants.AreaAdmin }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken},- requestEnd: function (e) {- if (e.type == "create" || e.type == "update") {- this.read();- }+ create: {+ url: "@Html.Raw(Url.Action("CategoryAdd", "Tax", new { area = Constants.AreaAdmin }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken},- error: function (e) {- display_kendoui_grid_error(e);- // Cancel the changes- this.cancelChanges();+ update: {+ url: "@Html.Raw(Url.Action("CategoryUpdate", "Tax", new { area = Constants.AreaAdmin }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken},- serverPaging: true,- serverFiltering: true,- serverSorting: true+ destroy: {+ url: "@Html.Raw(Url.Action("CategoryDelete", "Tax", new { area = Constants.AreaAdmin }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }},- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id",+ fields: {+ Name: { editable: true, type: "string" },+ DisplayOrder: { editable: true, type: "number" },+ StoreId: { editable: true, type: "string", defaultValue: "" },+ StoreName: { editable: false, type: "string" },+ Id: { editable: false, type: "string" }+ }+ }},- toolbar: [{ name: "create", text: "@Loc["Admin.Common.AddNewRecord"]" }],- editable: {- confirmation: true,- mode: "inline"+ requestEnd: function (e) {+ if (e.type == "create" || e.type == "update") {+ this.read();+ }},- scrollable: false,- columns: [{- field: "Name",- title: "@Loc["Admin.Configuration.Tax.Categories.Fields.Name"]",- width: 300- }, {- field: "DisplayOrder",- title: "@Loc["Admin.Configuration.Tax.Categories.Fields.DisplayOrder"]",- //integer format- format: "{0:0}",- width: 100+ 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+ },+ toolbar: [{ name: "create", text: "@Loc["Admin.Common.AddNewRecord"]" }],+ editable: {+ confirmation: true,+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "Name",+ title: "@Loc["Admin.Configuration.Tax.Categories.Fields.Name"]",+ width: 250+ }, {+ field: "DisplayOrder",+ title: "@Loc["Admin.Configuration.Tax.Categories.Fields.DisplayOrder"]",+ format: "{0:0}",+ width: 100+ }, {+ field: "StoreId",+ title: "@Loc["Admin.Common.Store"]",+ width: 200,+ template: "#=StoreName#",+ editor: function (container, options) {+ $('<input name="' + options.field + '"/>')+ .appendTo(container)+ .kendoDropDownList({+ dataTextField: "text",+ dataValueField: "value",+ dataSource: storesData+ });+ }+ }, {+ command: [{+ name: "edit",+ text: {+ edit: "@Loc["Admin.Common.Edit"]",+ update: "@Loc["Admin.Common.Update"]",+ cancel: "@Loc["Admin.Common.Cancel"]"+ }}, {- command: [{- name: "edit",- text: {- edit: "@Loc["Admin.Common.Edit"]",- update: "@Loc["Admin.Common.Update"]",- cancel: "@Loc["Admin.Common.Cancel"]"- }- }, {- name: "destroy",- text: "@Loc["Admin.Common.Delete"]"- }],- width: 200- }]- });+ name: "destroy",+ text: "@Loc["Admin.Common.Delete"]"+ }],+ width: 200+ }]});- </script>\ No newline at end of file+ });+</script>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Providers.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Providers.cshtmlindex 3ffa15bdf..ee996a0c0 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Providers.cshtml+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Tax/Providers.cshtml@@ -14,6 +14,13 @@</div><vc:admin-widget widget-zone="tax_provider_list_buttons" additional-data="null"/></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"><div class="form-horizontal"><div class="form-body">diff --git a/src/Web/Grand.Web.Admin/Controllers/TaxController.cs b/src/Web/Grand.Web.Admin/Controllers/TaxController.csindex 4ba877b09..41be5f5ff 100644--- a/src/Web/Grand.Web.Admin/Controllers/TaxController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/TaxController.cs@@ -2,6 +2,7 @@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.Permissions;using Grand.Domain.Directory;using Grand.Domain.Tax;@@ -31,7 +32,8 @@ public class TaxController : BaseAdminControllerIServiceProvider serviceProvider,ICacheBase cacheBase,ITranslationService translationService,- ICountryService countryService,+ ICountryService countryService,+ IStoreService storeService,IEnumTranslationService enumTranslationService){_taxService = taxService;@@ -41,6 +43,7 @@ public class TaxController : BaseAdminController_cacheBase = cacheBase;_translationService = translationService;_countryService = countryService;+ _storeService = storeService;_enumTranslationService = enumTranslationService;}@@ -55,6 +58,7 @@ public class TaxController : BaseAdminControllerprivate readonly ICacheBase _cacheBase;private readonly ITranslationService _translationService;private readonly ICountryService _countryService;+ private readonly IStoreService _storeService;private readonly IEnumTranslationService _enumTranslationService;#endregion@@ -75,8 +79,7 @@ public class TaxController : BaseAdminControllerpublic async Task<IActionResult> Providers(DataSourceRequest command){var storeScope = await GetActiveStore();- await _settingService.LoadSetting<TaxSettings>(storeScope);- var taxProviderSettings = await _settingService.LoadSetting<TaxProviderSettings>();+ var taxProviderSettings = await _settingService.LoadSetting<TaxProviderSettings>(storeScope);var taxProviders = _taxService.LoadAllTaxProviders().ToList();@@ -106,14 +109,15 @@ public class TaxController : BaseAdminControllerpublic async Task<IActionResult> MarkAsPrimaryProvider(string systemName){- var taxProviderettings = await _settingService.LoadSetting<TaxProviderSettings>();+ var storeScope = await GetActiveStore();+ var taxProviderettings = await _settingService.LoadSetting<TaxProviderSettings>(storeScope);if (string.IsNullOrEmpty(systemName)) return RedirectToAction("Providers");var taxProvider = _taxService.LoadTaxProviderBySystemName(systemName);if (taxProvider != null){taxProviderettings.ActiveTaxProviderSystemName = systemName;- await _settingService.SaveSetting(taxProviderettings);+ await _settingService.SaveSetting(taxProviderettings, storeScope);}//now clear cache@@ -202,22 +206,33 @@ public class TaxController : BaseAdminController#region Tax Categories- public IActionResult Categories()+ public async Task<IActionResult> Categories(){- return View();+ var model = new TaxCategoryListModel();+ model.AvailableStores.Add(new SelectListItem+ { Text = _translationService.GetResource("Admin.Common.All"), Value = "" });+ foreach (var s in await _storeService.GetAllStores())+ model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });+ return View(model);}[HttpPost]public async Task<IActionResult> Categories(DataSourceRequest command){+ var storeMap = (await _storeService.GetAllStores()).ToDictionary(s => s.Id, s => s.Shortcut);var categoriesModel = (await _taxCategoryService.GetAllTaxCategories())- .Select(x => x.ToModel())+ .Select(x => {+ var m = x.ToModel();+ m.StoreName = !string.IsNullOrEmpty(x.StoreId) && storeMap.TryGetValue(x.StoreId, out var name)+ ? name+ : _translationService.GetResource("Admin.Common.All");+ return m;+ }).ToList();var gridModel = new DataSourceResult {Data = categoriesModel,Total = categoriesModel.Count};-return Json(gridModel);}diff --git a/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryListModel.cs b/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryListModel.csnew file mode 100644index 000000000..47a269c11--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryListModel.cs@@ -0,0 +1,8 @@+using Microsoft.AspNetCore.Mvc.Rendering;++namespace Grand.Web.AdminShared.Models.Tax;++public class TaxCategoryListModel+{+ public IList<SelectListItem> AvailableStores { get; set; } = new List<SelectListItem>();+}diff --git a/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryModel.cs b/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryModel.csindex 86c135413..0ff3c9cc0 100644--- a/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryModel.cs+++ b/src/Web/Grand.Web.AdminShared/Models/Tax/TaxCategoryModel.cs@@ -11,4 +11,8 @@ public class TaxCategoryModel : BaseEntityModel[GrandResourceDisplayName("Admin.Configuration.Tax.Categories.Fields.DisplayOrder")]public int DisplayOrder { get; set; }++ public string StoreId { get; set; }++ public string StoreName { get; set; }}\ No newline at end of filediff --git a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.csindex 8fe41185b..fc87bfb8a 100644--- a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs@@ -826,10 +826,10 @@ public class OrderViewModelService : IOrderViewModelServicevar presetQty = 1;var presetPrice = (await _pricingService.GetFinalPrice(product, customer, store, currency, 0, true, presetQty)).finalPrice;- var productPrice = await _taxService.GetProductPrice(product, presetPrice, true, customer);+ var productPrice = await _taxService.GetProductPrice(product, presetPrice, true, customer, store);var presetPriceInclTax = productPrice.productprice;var presetPriceExclTax =- (await _taxService.GetProductPrice(product, presetPrice, false, customer)).productprice;+ (await _taxService.GetProductPrice(product, presetPrice, false, customer, store)).productprice;var model = new OrderModel.AddOrderProductModel.ProductDetailsModel {ProductId = product.Id,diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Categories.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Categories.cshtmlnew file mode 100644index 000000000..6878698a3--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Categories.cshtml@@ -0,0 +1,134 @@+@model Grand.Web.Store.Models.TaxCategoryListModel+@{+ ViewBag.Title = Loc["Admin.Configuration.Tax.Categories"];+ 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.Tax.Categories"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="x_content">+ <div id="tax-categories-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+ var currentStoreId = '@Model.StoreId';++ $(document).ready(function () {+ var grid = $("#tax-categories-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("Categories", "Tax", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ create: {+ url: "@Html.Raw(Url.Action("CategoryAdd", "Tax", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ update: {+ url: "@Html.Raw(Url.Action("CategoryUpdate", "Tax", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ destroy: {+ url: "@Html.Raw(Url.Action("CategoryDelete", "Tax", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id",+ fields: {+ Name: { editable: true, type: "string" },+ DisplayOrder: { editable: true, type: "number" },+ Id: { editable: false, type: "string" },+ StoreId: { editable: false, type: "string", defaultValue: "" }+ }+ }+ },+ requestEnd: function (e) {+ if (e.type == "create" || 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+ },+ toolbar: [{ name: "create", text: "@Loc["Admin.Common.AddNewRecord"]" }],+ editable: {+ confirmation: true,+ mode: "inline"+ },+ scrollable: false,+ dataBound: function () {+ var g = this;+ g.tbody.find("tr[data-uid]").each(function () {+ var dataItem = g.dataItem(this);+ if (dataItem && dataItem.StoreId !== "" && dataItem.StoreId !== currentStoreId) {+ $(this).find(".k-grid-edit, .k-grid-delete").hide();+ }+ });+ },+ columns: [{+ field: "Name",+ title: "@Loc["Admin.Configuration.Tax.Categories.Fields.Name"]",+ width: 300+ }, {+ field: "DisplayOrder",+ title: "@Loc["Admin.Configuration.Tax.Categories.Fields.DisplayOrder"]",+ format: "{0:0}",+ width: 100+ }, {+ command: [{+ name: "edit",+ text: {+ edit: "@Loc["Admin.Common.Edit"]",+ update: "@Loc["Admin.Common.Update"]",+ cancel: "@Loc["Admin.Common.Cancel"]"+ }+ }, {+ name: "destroy",+ text: "@Loc["Admin.Common.Delete"]"+ }],+ width: 200+ }]+ }).data("kendoGrid");+ });+</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Providers.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Providers.cshtmlnew file mode 100644index 000000000..f2d12b51a--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Providers.cshtml@@ -0,0 +1,81 @@+@{+ ViewBag.Title = Loc["Admin.Configuration.Tax.Providers"];+ 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.Tax.Providers"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="x_content">+ <div id="tax-providers-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>+<script>+ $(document).ready(function () {+ $("#tax-providers-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("Providers", "Tax", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors"+ },+ 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.Tax.Providers.Fields.FriendlyName"]",+ width: 250,+ template: '<a class="k-link" href="#=ConfigurationUrl#">#=FriendlyName#</a>',+ }, {+ field: "SystemName",+ title: "@Loc["Admin.Configuration.Tax.Providers.Fields.SystemName"]",+ width: 250,+ template: '<a class="k-link" href="#=ConfigurationUrl#">#=SystemName#</a>',+ }, {+ field: "SystemName",+ title: "@Loc["Admin.Configuration.Tax.Providers.Fields.IsPrimaryTaxProvider"]",+ width: 200,+ template: '<a href="@Url.Action("MarkAsPrimaryProvider", "Tax", new { area = Constants.AreaStore })/?systemName=#=SystemName#" class="k-button"> # if(IsPrimaryTaxProvider) {# <i class="fa fa-check" aria-hidden="true" style="color:green;margin-right:5px;"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red;margin-right:5px;"></i> #} # @Loc["Admin.Configuration.Tax.Providers.Fields.MarkAsPrimaryProvider"]</a>'+ }]+ });+ });+</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Settings.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Settings.cshtmlnew file mode 100644index 000000000..198b074ac--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Tax/Settings.cshtml@@ -0,0 +1,347 @@+@model TaxSettingsModel+@{+ ViewBag.Title = Loc["Admin.Configuration.Tax.Settings"];+ Layout = Constants.LayoutStore;+}+<form asp-area="@Constants.AreaStore" asp-controller="Tax" asp-action="Settings" method="post">++ <div asp-validation-summary="All"></div>+ <script>+ $(document).ready(function () {+ $("#@Html.IdFor(model => model.AllowCustomersToSelectTaxDisplayType)").click(toggleTaxDisplayType);+ $("#@Html.IdFor(model => model.ShippingIsTaxable)").click(toggleShipping);+ $("#@Html.IdFor(model => model.PaymentMethodAdditionalFeeIsTaxable)").click(togglePayment);+ $("#@Html.IdFor(model => model.EuVatEnabled)").click(toggleEUVAT);++ toggleTaxDisplayType();+ toggleShipping();+ togglePayment();+ toggleEUVAT();+ });++ function toggleTaxDisplayType() {+ if ($('#@Html.IdFor(model => model.AllowCustomersToSelectTaxDisplayType)').is(':checked')) {+ $('#pnlTaxDisplayType').hide();+ } else {+ $('#pnlTaxDisplayType').show();+ }+ }++ function toggleShipping() {+ if ($('#@Html.IdFor(model => model.ShippingIsTaxable)').is(':checked')) {+ $('#pnlShippingPriceIncludesTax').show();+ $('#pnlShippingTaxClass').show();+ } else {+ $('#pnlShippingPriceIncludesTax').hide();+ $('#pnlShippingTaxClass').hide();+ }+ }++ function togglePayment() {+ if ($('#@Html.IdFor(model => model.PaymentMethodAdditionalFeeIsTaxable)').is(':checked')) {+ $('#pnlPaymentMethodAdditionalFeeIncludesTax').show();+ $('#pnlPaymentMethodAdditionalFeeTaxCategory').show();+ } else {+ $('#pnlPaymentMethodAdditionalFeeIncludesTax').hide();+ $('#pnlPaymentMethodAdditionalFeeTaxCategory').hide();+ }+ }++ function toggleEUVAT() {+ if ($('#@Html.IdFor(model => model.EuVatEnabled)').is(':checked')) {+ $('#pnlEuVatShopCountry').show();+ $('#pnlEuVatAllowVATExemption').show();+ $('#pnlEuVatAssumeValid').show();+ $('#pnlEuVatUseWebService').show();+ $('#pnlEuVatNote').show();+ } else {+ $('#pnlEuVatShopCountry').hide();+ $('#pnlEuVatAllowVATExemption').hide();+ $('#pnlEuVatAssumeValid').hide();+ $('#pnlEuVatUseWebService').hide();+ $('#pnlEuVatNote').hide();+ }+ }+ </script>+ <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.Tax.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="PricesIncludeTax" 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="PricesIncludeTax"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="PricesIncludeTax"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="AllowCustomersToSelectTaxDisplayType" 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="AllowCustomersToSelectTaxDisplayType"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="AllowCustomersToSelectTaxDisplayType"></span>+ </div>+ </div>+ <div class="form-group" id="pnlTaxDisplayType">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="TaxDisplayType" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="TaxDisplayType" asp-items="Model.TaxDisplayTypeValues"/>+ <span asp-validation-for="TaxDisplayType"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="DisplayTaxRates" 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="DisplayTaxRates"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="DisplayTaxRates"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="HideZeroTax" 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="HideZeroTax"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="HideZeroTax"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="HideTaxInOrderSummary" 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="HideTaxInOrderSummary"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="HideTaxInOrderSummary"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ForceTaxExclusionFromOrderSubtotal" 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="ForceTaxExclusionFromOrderSubtotal"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="ForceTaxExclusionFromOrderSubtotal"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="TaxBasedOn" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="TaxBasedOn" asp-items="Model.TaxBasedOnValues"/>+ <span asp-validation-for="TaxBasedOn"></span>+ </div>+ </div>+ <div class="form-horizontal portlet light bg-inverse form-fit">+ <div class="form-group" style="padding-top:15px;margin-bottom: 0px;">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <strong>@Loc["Admin.Configuration.Tax.DefaultTaxAddress"]</strong>+ </div>+ </div>+ <div class="form-group">+ <div id="pnlDefaultTaxAddress">+ <admin-input asp-for="DefaultTaxAddress" asp-template="Address"/>+ </div>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="DefaultTaxCategoryId" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="DefaultTaxCategoryId" asp-items="Model.TaxCategories"/>+ <span asp-validation-for="DefaultTaxCategoryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ShippingIsTaxable" 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="ShippingIsTaxable"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="ShippingIsTaxable"></span>+ </div>+ </div>+ <div class="form-group" id="pnlShippingPriceIncludesTax">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ShippingPriceIncludesTax" 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="ShippingPriceIncludesTax"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="ShippingPriceIncludesTax"></span>+ </div>+ </div>+ <div class="form-group" id="pnlShippingTaxClass">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="ShippingTaxCategoryId" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="ShippingTaxCategoryId" asp-items="Model.TaxCategories"/>+ <span asp-validation-for="ShippingTaxCategoryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="PaymentMethodAdditionalFeeIsTaxable" 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="PaymentMethodAdditionalFeeIsTaxable"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="PaymentMethodAdditionalFeeIsTaxable"></span>+ </div>+ </div>+ <div class="form-group" id="pnlPaymentMethodAdditionalFeeIncludesTax">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="PaymentMethodAdditionalFeeIncludesTax" 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="PaymentMethodAdditionalFeeIncludesTax"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="PaymentMethodAdditionalFeeIncludesTax"></span>+ </div>+ </div>+ <div class="form-group" id="pnlPaymentMethodAdditionalFeeTaxCategory">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="PaymentMethodAdditionalFeeTaxCategoryId" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="PaymentMethodAdditionalFeeTaxCategoryId" asp-items="Model.TaxCategories"/>+ <span asp-validation-for="PaymentMethodAdditionalFeeTaxCategoryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="EuVatEnabled" 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="EuVatEnabled"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="EuVatEnabled"></span>+ </div>+ </div>+ <div class="form-group" id="pnlEuVatShopCountry">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="EuVatShopCountryId" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="EuVatShopCountryId" asp-items="Model.EuVatShopCountries"/>+ <span asp-validation-for="EuVatShopCountryId"></span>+ </div>+ </div>+ <div class="form-group" id="pnlEuVatAllowVATExemption">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="EuVatAllowVatExemption" 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="EuVatAllowVatExemption"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="EuVatAllowVatExemption"></span>+ </div>+ </div>+ <div class="form-group" id="pnlEuVatAssumeValid">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="EuVatAssumeValid" 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="EuVatAssumeValid"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="EuVatAssumeValid"></span>+ </div>+ </div>+ <div class="form-group" id="pnlEuVatUseWebService">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="EuVatUseWebService" 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="EuVatUseWebService"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="EuVatUseWebService"></span>+ </div>+ </div>+ <div class="form-group" id="pnlEuVatNote">+ <div class="note note-info">+ If you want to use EU VAT Web Service to validate the EU VAT numbers, please add EuropaCheckVat plugin to your store.+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="CalculateRoundPrice" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-input asp-for="CalculateRoundPrice"/>+ </div>+ </div>+ <div class="form-group">+ <div class="col-8 col-md-4 col-sm-4 text-right">+ <admin-label asp-for="MidpointRounding" class="control-label"/>+ </div>+ <div class="col-4 col-md-8 col-sm-8">+ <admin-select asp-for="MidpointRounding" asp-items="EnumTranslationService.ToSelectList(MidpointRounding.ToEven)"/>+ <span asp-validation-for="MidpointRounding"></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 f9058e898..c34fda895 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtml+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/_ViewImports.cshtml@@ -36,6 +36,7 @@@using Grand.Web.AdminShared.Models.Settings@using Grand.Web.AdminShared.Models.Shipping@using Grand.Web.AdminShared.Models.Discounts+@using Grand.Web.AdminShared.Models.Tax@using Grand.Web.Store.Models.Messages@inject LocService Locdiff --git a/src/Web/Grand.Web.Store/Controllers/TaxController.cs b/src/Web/Grand.Web.Store/Controllers/TaxController.csnew file mode 100644index 000000000..ac4641816--- /dev/null+++ b/src/Web/Grand.Web.Store/Controllers/TaxController.cs@@ -0,0 +1,213 @@+using Grand.Business.Core.Interfaces.Catalog.Tax;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Directory;+using Grand.Domain.Permissions;+using Grand.Domain.Tax;+using Grand.Infrastructure;+using Grand.Infrastructure.Caching;+using Grand.Infrastructure.Plugins;+using Grand.Web.AdminShared.Extensions.Mapping;+using Grand.Web.AdminShared.Extensions.Mapping.Settings;+using Grand.Web.AdminShared.Models.Common;+using Grand.Web.AdminShared.Models.Tax;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Extensions;+using Grand.Web.Common.Localization;+using Grand.Web.Common.Security.Authorization;+using Grand.Web.Store.Models;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Rendering;++namespace Grand.Web.Store.Controllers;++[PermissionAuthorize(PermissionSystemName.TaxSettings)]+public class TaxController(+ ITaxService taxService,+ ITaxCategoryService taxCategoryService,+ ISettingService settingService,+ IServiceProvider serviceProvider,+ ICacheBase cacheBase,+ ITranslationService translationService,+ ICountryService countryService,+ IEnumTranslationService enumTranslationService,+ IContextAccessor contextAccessor) : BaseStoreController+{+ private string CurrentStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ #region Tax Providers++ public IActionResult Providers()+ {+ return View();+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> Providers(DataSourceRequest command)+ {+ var taxProviderSettings = await settingService.LoadSetting<TaxProviderSettings>(CurrentStoreId);+ var taxProvidersModel = new List<TaxProviderModel>();+ foreach (var tax in taxService.LoadAllTaxProviders())+ {+ var tmp = tax.ToModel();+ var url = tax.ConfigurationUrl;+ if (string.IsNullOrEmpty(url))+ url = PluginManager.ReferencedPlugins.FirstOrDefault(x =>+ x.SystemName.Equals(tax.SystemName, StringComparison.OrdinalIgnoreCase))+ ?.Instance<IPlugin>(serviceProvider)?.ConfigurationUrl();+ tmp.ConfigurationUrl = url;+ tmp.IsPrimaryTaxProvider = tmp.SystemName.Equals(taxProviderSettings.ActiveTaxProviderSystemName,+ StringComparison.OrdinalIgnoreCase);+ taxProvidersModel.Add(tmp);+ }++ var gridModel = new DataSourceResult {+ Data = taxProvidersModel,+ Total = taxProvidersModel.Count+ };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> MarkAsPrimaryProvider(string systemName)+ {+ var taxProviderSettings = await settingService.LoadSetting<TaxProviderSettings>(CurrentStoreId);+ if (string.IsNullOrEmpty(systemName)) return RedirectToAction("Providers");+ var taxProvider = taxService.LoadTaxProviderBySystemName(systemName);+ if (taxProvider != null)+ {+ taxProviderSettings.ActiveTaxProviderSystemName = systemName;+ await settingService.SaveSetting(taxProviderSettings, CurrentStoreId);+ }+ await cacheBase.Clear();+ return RedirectToAction("Providers");+ }++ #endregion++ #region Settings++ public async Task<IActionResult> Settings()+ {+ var taxSettings = await settingService.LoadSetting<TaxSettings>(CurrentStoreId);+ var model = taxSettings.ToModel();+ model.ActiveStore = CurrentStoreId;+ model.TaxBasedOnValues = enumTranslationService.ToSelectList(taxSettings.TaxBasedOn);+ model.TaxDisplayTypeValues = enumTranslationService.ToSelectList(taxSettings.TaxDisplayType);++ var taxCategories = await taxCategoryService.GetAllTaxCategories(CurrentStoreId);+ model.TaxCategories.Add(new SelectListItem {+ Text = translationService.GetResource("Admin.Configuration.Tax.Settings.TaxCategories.None"), Value = ""+ });+ foreach (var tc in taxCategories)+ model.TaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id });++ model.EuVatShopCountries.Add(new SelectListItem+ { Text = translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });+ foreach (var c in await countryService.GetAllCountries(showHidden: true))+ model.EuVatShopCountries.Add(new SelectListItem+ { Text = c.Name, Value = c.Id, Selected = c.Id == taxSettings.EuVatShopCountryId });++ var defaultAddress = taxSettings.DefaultTaxAddress;+ model.DefaultTaxAddress = defaultAddress != null+ ? await defaultAddress.ToModel(countryService)+ : new AddressModel();++ model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem+ { Text = translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });+ foreach (var c in await countryService.GetAllCountries(showHidden: true))+ model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem+ { Text = c.Name, Value = c.Id, Selected = defaultAddress != null && c.Id == defaultAddress.CountryId });++ var states = defaultAddress != null && !string.IsNullOrEmpty(defaultAddress.CountryId)+ ? (await countryService.GetCountryById(defaultAddress.CountryId))?.StateProvinces+ : new List<StateProvince>();+ if (states?.Count > 0)+ foreach (var s in states)+ model.DefaultTaxAddress.AvailableStates.Add(new SelectListItem+ { Text = s.Name, Value = s.Id, Selected = s.Id == defaultAddress?.StateProvinceId });++ model.DefaultTaxAddress.CountryEnabled = true;+ model.DefaultTaxAddress.StateProvinceEnabled = true;+ model.DefaultTaxAddress.ZipPostalCodeEnabled = true;+ model.DefaultTaxAddress.ZipPostalCodeRequired = true;++ return View(model);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> Settings(TaxSettingsModel model)+ {+ var taxSettings = await settingService.LoadSetting<TaxSettings>(CurrentStoreId);+ taxSettings = model.ToEntity(taxSettings);+ await settingService.SaveSetting(taxSettings, CurrentStoreId);+ await cacheBase.Clear();+ Success(translationService.GetResource("Admin.Configuration.Updated"));+ return RedirectToAction("Settings");+ }++ #endregion++ #region Tax Categories++ public IActionResult Categories()+ {+ return View(new Models.TaxCategoryListModel { StoreId = CurrentStoreId });+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> Categories(DataSourceRequest command)+ {+ var categoriesModel = (await taxCategoryService.GetAllTaxCategories(CurrentStoreId))+ .Select(x => x.ToModel())+ .ToList();+ var gridModel = new DataSourceResult {+ Data = categoriesModel,+ Total = categoriesModel.Count+ };+ return Json(gridModel);+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> CategoryUpdate(TaxCategoryModel model)+ {+ if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });+ var taxCategory = await taxCategoryService.GetTaxCategoryById(model.Id);+ if (taxCategory == null || taxCategory.StoreId != CurrentStoreId)+ return new JsonResult("");+ taxCategory = model.ToEntity(taxCategory);+ taxCategory.StoreId = CurrentStoreId;+ await taxCategoryService.UpdateTaxCategory(taxCategory);+ return new JsonResult("");+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> CategoryAdd(TaxCategoryModel model)+ {+ if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });+ var taxCategory = new TaxCategory { StoreId = CurrentStoreId };+ taxCategory = model.ToEntity(taxCategory);+ taxCategory.StoreId = CurrentStoreId;+ await taxCategoryService.InsertTaxCategory(taxCategory);+ return new JsonResult("");+ }++ [HttpPost]+ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ public async Task<IActionResult> CategoryDelete(string id)+ {+ var taxCategory = await taxCategoryService.GetTaxCategoryById(id);+ if (taxCategory == null || taxCategory.StoreId != CurrentStoreId)+ return new JsonResult("");+ await taxCategoryService.DeleteTaxCategory(taxCategory);+ return new JsonResult("");+ }++ #endregion+}diff --git a/src/Web/Grand.Web.Store/Models/TaxCategoryListModel.cs b/src/Web/Grand.Web.Store/Models/TaxCategoryListModel.csnew file mode 100644index 000000000..2f9b74f9d--- /dev/null+++ b/src/Web/Grand.Web.Store/Models/TaxCategoryListModel.cs@@ -0,0 +1,6 @@+namespace Grand.Web.Store.Models;++public class TaxCategoryListModel+{+ public string StoreId { get; set; }+}diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.csindex 9296c6cf2..3f28df28c 100644--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs@@ -163,7 +163,7 @@ public class ShoppingCartController : BasePublicControllerdisabledattributeids = disabledAttributeIds.ToArray(),model = orderTotals,checkoutattributeinfo =- await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _contextAccessor.WorkContext.CurrentCustomer)+ await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)});}diff --git a/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs b/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.csindex bb2318da1..b781f736e 100644--- a/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs@@ -89,7 +89,7 @@ public class GetPaymentMethodHandler : IRequestHandler<GetPaymentMethod, Checkou//payment method additional feevar paymentMethodAdditionalFee =await _paymentService.GetAdditionalHandlingFee(request.Cart, pm.SystemName);- var rate = (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, request.Customer))+ var rate = (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, request.Customer, request.Store)).paymentPrice;if (rate > 0)pmModel.Fee = _priceFormatter.FormatPrice(rate, request.Currency);diff --git a/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingAddressHandler.cs b/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingAddressHandler.csindex 91e663c6d..dd7d47f35 100644--- a/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingAddressHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingAddressHandler.cs@@ -101,7 +101,7 @@ public class GetShippingAddressHandler : IRequestHandler<GetShippingAddress, Che};if (pickupPoint.PickupFee > 0){- var amount = (await _taxService.GetShippingPrice(pickupPoint.PickupFee, request.Customer))+ var amount = (await _taxService.GetShippingPrice(pickupPoint.PickupFee, request.Customer, request.Store)).shippingPrice;amount = await _currencyService.ConvertFromPrimaryStoreCurrency(amount, request.Currency);pickupPointModel.PickupFee = _priceFormatter.FormatPrice(amount, request.Currency);diff --git a/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingMethodHandler.cs b/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingMethodHandler.csindex e68c40699..a40562637 100644--- a/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingMethodHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Checkout/GetShippingMethodHandler.cs@@ -64,7 +64,7 @@ public class GetShippingMethodHandler : IRequestHandler<GetShippingMethod, Checkvar shippingTotal = (await _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, request.Cart)).shippingRate;- var rateBase = (await _taxService.GetShippingPrice(shippingTotal, request.Customer)).shippingPrice;+ var rateBase = (await _taxService.GetShippingPrice(shippingTotal, request.Customer, request.Store)).shippingPrice;soModel.Fee = _priceFormatter.FormatPrice(rateBase);model.ShippingMethods.Add(soModel);diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.csindex 4b48eb054..012125c6d 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs@@ -431,7 +431,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag//additional shipping chargeif (model.AdditionalShippingCharge > 0)model.AdditionalShippingChargeStr = _priceFormatter.FormatPrice(- (await _taxService.GetShippingPrice(model.AdditionalShippingCharge, _contextAccessor.WorkContext.CurrentCustomer))+ (await _taxService.GetShippingPrice(model.AdditionalShippingCharge, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)).shippingPrice);//ask question us on the productdiff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.csindex eb84f7ff7..7f55ca118 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs@@ -238,7 +238,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn//calculate pricesvar finalPrice = (await _taxService.GetProductPrice(minPriceProduct,minPossiblePrice.Value, priceIncludesTax,- _contextAccessor.WorkContext.CurrentCustomer))+ _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)).productprice;priceModel.OldPrice = null;@@ -346,9 +346,9 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEnvar minPossiblePrice = infoPrice.finalPrice;var oldPriceBase = (await _taxService.GetProductPrice(product, product.OldPrice,- priceIncludesTax, _contextAccessor.WorkContext.CurrentCustomer)).productprice;+ priceIncludesTax, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)).productprice;var finalPrice = (await _taxService.GetProductPrice(product, minPossiblePrice,- priceIncludesTax, _contextAccessor.WorkContext.CurrentCustomer)).productprice;+ priceIncludesTax, _contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore)).productprice;var oldPrice =await _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase,diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetEstimateShippingResultHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetEstimateShippingResultHandler.csindex 6f30bfbe4..7a355a96c 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetEstimateShippingResultHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetEstimateShippingResultHandler.cs@@ -76,7 +76,7 @@ public class GetEstimateShippingResultHandler : IRequestHandler<GetEstimateShipprequest.Cart);var shippingTotal = total.shippingRate;- var rate = (await _taxService.GetShippingPrice(shippingTotal, request.Customer)).shippingPrice;+ var rate = (await _taxService.GetShippingPrice(shippingTotal, request.Customer, request.Store)).shippingPrice;soModel.Price = _priceFormatter.FormatPrice(rate, request.Currency);model.ShippingOptions.Add(soModel);}@@ -92,7 +92,7 @@ public class GetEstimateShippingResultHandler : IRequestHandler<GetEstimateShipp};var shippingTotal = pickupPoints.Max(x => x.PickupFee);- var rate = (await _taxService.GetShippingPrice(shippingTotal, request.Customer)).shippingPrice;+ var rate = (await _taxService.GetShippingPrice(shippingTotal, request.Customer, request.Store)).shippingPrice;soModel.Price = _priceFormatter.FormatPrice(rate, request.Currency);model.ShippingOptions.Add(soModel);}diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetOrderTotalsHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetOrderTotalsHandler.csindex 518951a1c..323e11916 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetOrderTotalsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetOrderTotalsHandler.cs@@ -120,7 +120,7 @@ public class GetOrderTotalsHandler : IRequestHandler<GetOrderTotals, OrderTotalsvar paymentMethodAdditionalFee =await _paymentService.GetAdditionalHandlingFee(request.Cart, paymentMethodSystemName);var paymentMethodAdditionalFeeWithTaxBase =- (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, request.Customer))+ (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, request.Customer, request.Store)).paymentPrice;if (paymentMethodAdditionalFeeWithTaxBase > 0){diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.csindex c777a968a..b6f908e4f 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs@@ -150,7 +150,7 @@ public class GetShoppingCartHandler : IRequestHandler<GetShoppingCart, ShoppingCrequest.Customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,request.Store.Id);model.CheckoutAttributeInfo =- await _checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, request.Customer);+ await _checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, request.Customer, request.Store);if (!request.Cart.Where(x => x.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions).ToList().Any()){