Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Convert if statement into 'switch'

supportf1cf5b51ddbb
diff --git a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs
index 5f41c6852..6b17aee64 100644
--- a/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs
+++ b/src/API/Grand.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs
@@ -80,12 +80,16 @@ namespace Grand.Api.Commands.Handlers.Catalog
//activity log
_ = _customerActivityService.InsertActivity("EditProduct", product.Id, _workContext.CurrentCustomer, "", _translationService.GetResource("ActivityLog.EditProduct"), product.Name);
- //raise event
- if (!prevPublished && product.Published)
- await _mediator.Publish(new ProductPublishEvent(product), cancellationToken);
-
- if (prevPublished && !product.Published)
- await _mediator.Publish(new ProductUnPublishEvent(product), cancellationToken);
+ switch (prevPublished)
+ {
+ //raise event
+ case false when product.Published:
+ await _mediator.Publish(new ProductPublishEvent(product), cancellationToken);
+ break;
+ case true when !product.Published:
+ await _mediator.Publish(new ProductUnPublishEvent(product), cancellationToken);
+ break;
+ }
return product.ToModel();
}
diff --git a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs b/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs
index 807d9f78f..25cccd2f0 100644
--- a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs
+++ b/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs
@@ -8,15 +8,15 @@ namespace Grand.Api.Extensions
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
- if (context.ApiDescription.GroupName == "v1" && context.ApiDescription.HttpMethod == "GET" &&
- context.ApiDescription.ParameterDescriptions.Count == 0)
+ switch (context.ApiDescription.GroupName)
{
- ApplyV1(operation);
- }
-
- if (context.ApiDescription.GroupName == "v2" && context.ApiDescription.HttpMethod == "POST")
- {
- ApplyV2(operation, context);
+ case "v1" when context.ApiDescription.HttpMethod == "GET" &&
+ context.ApiDescription.ParameterDescriptions.Count == 0:
+ ApplyV1(operation);
+ break;
+ case "v2" when context.ApiDescription.HttpMethod == "POST":
+ ApplyV2(operation, context);
+ break;
}
}
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
index 8e4db6cbd..d614b9b26 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs
@@ -167,10 +167,10 @@ namespace Grand.Business.Catalog.Services.Products
}
private async Task ReverseBookedInventory(Product product, InventoryJournal inventoryJournal)
{
- //standard manage stock
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
+ switch (product.ManageInventoryMethodId)
{
- if (product.UseMultipleWarehouses)
+ //standard manage stock
+ case ManageInventoryMethod.ManageStock when product.UseMultipleWarehouses:
{
var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == inventoryJournal.WarehouseId);
if (pwi == null)
@@ -183,61 +183,61 @@ namespace Grand.Business.Catalog.Services.Products
await _productRepository.UpdateToSet(product.Id, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi);
await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
-
+ break;
}
- else
- {
+ case ManageInventoryMethod.ManageStock:
product.StockQuantity += inventoryJournal.OutQty;
product.ReservedQuantity += inventoryJournal.OutQty;
await UpdateStockProduct(product);
- }
- }
+ break;
+ //manage stock by attributes
+ case ManageInventoryMethod.ManageStockByAttributes:
+ {
+ var combination = product.FindProductAttributeCombination(inventoryJournal.Attributes);
+ if (combination == null)
+ return;
- //manage stock by attributes
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
- {
- var combination = product.FindProductAttributeCombination(inventoryJournal.Attributes);
- if (combination == null)
- return;
+ if (!product.UseMultipleWarehouses)
+ {
+ combination.StockQuantity += inventoryJournal.OutQty;
+ combination.ReservedQuantity += inventoryJournal.OutQty;
+ if (combination.ReservedQuantity < 0)
+ combination.ReservedQuantity = 0;
- if (!product.UseMultipleWarehouses)
- {
- combination.StockQuantity += inventoryJournal.OutQty;
- combination.ReservedQuantity += inventoryJournal.OutQty;
- if (combination.ReservedQuantity < 0)
- combination.ReservedQuantity = 0;
+ product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ await UpdateStockProduct(product);
- await UpdateStockProduct(product);
+ }
+ else
+ {
+ var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == inventoryJournal.WarehouseId);
+ if (pwi == null)
+ return;
- }
- else
- {
- var pwi = combination.WarehouseInventory.FirstOrDefault(x => x.WarehouseId == inventoryJournal.WarehouseId);
- if (pwi == null)
- return;
+ pwi.StockQuantity += inventoryJournal.OutQty;
+ pwi.ReservedQuantity += inventoryJournal.OutQty;
- pwi.StockQuantity += inventoryJournal.OutQty;
- pwi.ReservedQuantity += inventoryJournal.OutQty;
+ if (pwi.ReservedQuantity < 0)
+ pwi.ReservedQuantity = 0;
- if (pwi.ReservedQuantity < 0)
- pwi.ReservedQuantity = 0;
+ combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
+ combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
+ product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
+ product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
- combination.StockQuantity = combination.WarehouseInventory.Sum(x => x.StockQuantity);
- combination.ReservedQuantity = combination.WarehouseInventory.Sum(x => x.ReservedQuantity);
- product.StockQuantity = product.ProductAttributeCombinations.Sum(x => x.StockQuantity);
- product.ReservedQuantity = product.ProductAttributeCombinations.Sum(x => x.ReservedQuantity);
+ await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
+ await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
+ await UpdateStockProduct(product);
- await _productRepository.UpdateToSet(product.Id, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination);
- await _productRepository.UpdateField(product.Id, x => x.UpdatedOnUtc, DateTime.UtcNow);
- await UpdateStockProduct(product);
+ }
+ break;
}
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs
index 040578a21..0b0e88d32 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs
@@ -35,32 +35,38 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
await _orderService.UpdateOrder(request.Order);
}
- if (request.Order.OrderStatusId == (int)OrderStatusSystem.Pending)
+ switch (request.Order.OrderStatusId)
{
- if (request.Order.PaymentStatusId is PaymentStatus.Authorized or PaymentStatus.Paid or PaymentStatus.PartiallyPaid)
+ case (int)OrderStatusSystem.Pending:
{
- await _mediator.Send(new SetOrderStatusCommand
+ if (request.Order.PaymentStatusId is PaymentStatus.Authorized or PaymentStatus.Paid or PaymentStatus.PartiallyPaid)
{
- Order = request.Order,
- Os = OrderStatusSystem.Processing,
- NotifyCustomer = false,
- NotifyStoreOwner = false
- }, cancellationToken);
- }
+ await _mediator.Send(new SetOrderStatusCommand
+ {
+ Order = request.Order,
+ Os = OrderStatusSystem.Processing,
+ NotifyCustomer = false,
+ NotifyStoreOwner = false
+ }, cancellationToken);
+ }
- if (request.Order.ShippingStatusId is ShippingStatus.PartiallyShipped or ShippingStatus.Shipped or ShippingStatus.Delivered)
- {
- await _mediator.Send(new SetOrderStatusCommand
+ if (request.Order.ShippingStatusId is ShippingStatus.PartiallyShipped or ShippingStatus.Shipped or ShippingStatus.Delivered)
{
- Order = request.Order,
- Os = OrderStatusSystem.Processing,
- NotifyCustomer = false,
- NotifyStoreOwner = false
- }, cancellationToken);
+ await _mediator.Send(new SetOrderStatusCommand
+ {
+ Order = request.Order,
+ Os = OrderStatusSystem.Processing,
+ NotifyCustomer = false,
+ NotifyStoreOwner = false
+ }, cancellationToken);
+ }
+
+ break;
}
+ case (int)OrderStatusSystem.Cancelled or (int)OrderStatusSystem.Complete:
+ return true;
}
- if (request.Order.OrderStatusId is (int)OrderStatusSystem.Cancelled or (int)OrderStatusSystem.Complete) return true;
if (request.Order.PaymentStatusId != PaymentStatus.Paid) return true;
bool completed;
if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired)
diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
index b63c92413..4e5580b7b 100644
--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
@@ -70,43 +70,50 @@ namespace Grand.Business.Checkout.Services.CheckoutAttributes
var formattedAttribute = "";
if (!attribute.ShouldHaveValues())
{
- //no values
- if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
+ switch (attribute.AttributeControlTypeId)
{
- //multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- //we never encode multiline text box input
- }
- else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)
- {
- //file upload
- if (Guid.TryParse(valueStr, out var downloadGuid))
+ //no values
+ case AttributeControlType.MultilineTextbox:
{
- var attributeText = string.Empty;
+ //multiline text box
var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
- if (allowHyperlinks)
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ //we never encode multiline text box input
+ break;
+ }
+ case AttributeControlType.FileUpload:
+ {
+ //file upload
+ if (Guid.TryParse(valueStr, out var downloadGuid))
{
- //hyperlinks are allowed
- var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
- attributeText =
- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";
+ var attributeText = string.Empty;
+ var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
+ if (allowHyperlinks)
+ {
+ //hyperlinks are allowed
+ var downloadLink =
+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ attributeText =
+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";
+ }
+ formattedAttribute = $"{attributeName}: {attributeText}";
}
- formattedAttribute = $"{attributeName}: {attributeText}";
+
+ break;
+ }
+ default:
+ {
+ //other attributes (text box, datepicker)
+ formattedAttribute =
+ $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
}
- }
- else
- {
- //other attributes (text box, datepicker)
- formattedAttribute =
- $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
}
}
else
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
index d081bea93..ea75b331d 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
@@ -602,9 +602,14 @@ namespace Grand.Business.Checkout.Services.Orders
}
}
- if (!shippingTotal.HasValue) return (null, taxRate, appliedDiscounts);
- if (shippingTotal.Value < 0)
- shippingTotal = 0;
+ switch (shippingTotal)
+ {
+ case null:
+ return (null, taxRate, appliedDiscounts);
+ case < 0:
+ shippingTotal = 0;
+ break;
+ }
//round
if (_shoppingCartSettings.RoundPrices)
diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs
index 727edf889..60718fc57 100644
--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs
+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs
@@ -45,15 +45,14 @@ namespace Grand.Business.Checkout.Validators
break;
}
- if (value.ShoppingCartType == ShoppingCartType.ShoppingCart && !await permissionService.Authorize(StandardPermission.EnableShoppingCart, value.Customer))
- {
- context.AddFailure("Shopping cart is disabled");
- return;
- }
- if (value.ShoppingCartType == ShoppingCartType.Wishlist && !await permissionService.Authorize(StandardPermission.EnableWishlist, value.Customer))
+ switch (value.ShoppingCartType)
{
- context.AddFailure("Wishlist is disabled");
- return;
+ case ShoppingCartType.ShoppingCart when !await permissionService.Authorize(StandardPermission.EnableShoppingCart, value.Customer):
+ context.AddFailure("Shopping cart is disabled");
+ return;
+ case ShoppingCartType.Wishlist when !await permissionService.Authorize(StandardPermission.EnableWishlist, value.Customer):
+ context.AddFailure("Wishlist is disabled");
+ return;
}
if (value.Quantity <= 0)
diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs
index 0061169a7..b3913b3ee 100644
--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs
+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs
@@ -39,16 +39,16 @@ namespace Grand.Business.Checkout.Validators
context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));
}
- //disabled "add to cart" button
- if (value.ShoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart && value.Product.DisableBuyButton)
+ switch (value.ShoppingCartItem.ShoppingCartTypeId)
{
- context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled"));
- }
-
- //disabled "add to wishlist" button
- if (value.ShoppingCartItem.ShoppingCartTypeId == ShoppingCartType.Wishlist && value.Product.DisableWishlistButton)
- {
- context.AddFailure(translationService.GetResource("ShoppingCart.WishlistDisabled"));
+ //disabled "add to cart" button
+ case ShoppingCartType.ShoppingCart when value.Product.DisableBuyButton:
+ context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled"));
+ break;
+ //disabled "add to wishlist" button
+ case ShoppingCartType.Wishlist when value.Product.DisableWishlistButton:
+ context.AddFailure(translationService.GetResource("ShoppingCart.WishlistDisabled"));
+ break;
}
//call for price
diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
index 0cdad4bda..8db6b9a50 100644
--- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
+++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
@@ -151,29 +151,32 @@ namespace Grand.Business.Common.Services.Addresses
var formattedAttribute = "";
if (!attribute.ShouldHaveValues())
{
- //no values
- if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
+ switch (attribute.AttributeControlType)
{
- //multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- //we never encode multiline text box input
- }
- else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
- {
- //file upload
- //not supported for address attributes
- }
- else
- {
- //other attributes (text box, datepicker)
- formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ //no values
+ case AttributeControlType.MultilineTextbox:
+ {
+ //multiline text box
+ var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ break;
+ }
+ case AttributeControlType.FileUpload:
+ //file upload
+ //not supported for address attributes
+ break;
+ default:
+ {
+ //other attributes (text box, datepicker)
+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
+ }
}
}
else
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
index 51e3ec1b9..cd73271b9 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
@@ -151,29 +151,32 @@ namespace Grand.Business.Customers.Services
var formattedAttribute = "";
if (!attribute.ShouldHaveValues())
{
- //no values
- if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
+ switch (attribute.AttributeControlTypeId)
{
- //multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- //we never encode multiline text box input
- }
- else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)
- {
- //file upload
- //not supported for customer attributes
- }
- else
- {
- //other attributes (text box, datepicker)
- formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ //no values
+ case AttributeControlType.MultilineTextbox:
+ {
+ //multiline text box
+ var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ break;
+ }
+ case AttributeControlType.FileUpload:
+ //file upload
+ //not supported for customer attributes
+ break;
+ default:
+ {
+ //other attributes (text box, datepicker)
+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
+ }
}
}
else
diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
index 832b0b90d..919be9828 100644
--- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
@@ -191,17 +191,27 @@ namespace Grand.Business.Marketing.Services.Campaigns
if (campaign.CustomerLastPurchaseDateTo.HasValue)
query = query.Where(x => x.LastPurchaseDateUtc <= campaign.CustomerLastPurchaseDateTo.Value);
- //customer has shopping carts
- if (campaign.CustomerHasShoppingCart == CampaignCondition.True)
- query = query.Where(x => x.HasShoppingCartItems);
- if (campaign.CustomerHasShoppingCart == CampaignCondition.False)
- query = query.Where(x => !x.HasShoppingCartItems);
-
- //customer has order
- if (campaign.CustomerHasOrders == CampaignCondition.True)
- query = query.Where(x => x.IsHasOrders);
- if (campaign.CustomerHasOrders == CampaignCondition.False)
- query = query.Where(x => !x.IsHasOrders);
+ switch (campaign.CustomerHasShoppingCart)
+ {
+ //customer has shopping carts
+ case CampaignCondition.True:
+ query = query.Where(x => x.HasShoppingCartItems);
+ break;
+ case CampaignCondition.False:
+ query = query.Where(x => !x.HasShoppingCartItems);
+ break;
+ }
+
+ switch (campaign.CustomerHasOrders)
+ {
+ //customer has order
+ case CampaignCondition.True:
+ query = query.Where(x => x.IsHasOrders);
+ break;
+ case CampaignCondition.False:
+ query = query.Where(x => !x.IsHasOrders);
+ break;
+ }
//tags
if (campaign.CustomerTags.Count > 0)
diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
index 95859e7b8..c9a7551af 100644
--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
@@ -194,42 +194,49 @@ namespace Grand.Business.Marketing.Services.Contacts
var formattedAttribute = "";
if (!attribute.ShouldHaveValues())
{
- //no values
- if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
+ switch (attribute.AttributeControlType)
{
- //multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- //we never encode multiline text box input
- }
- else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
- {
- //file upload
- if (Guid.TryParse(valueStr, out var downloadGuid))
+ //no values
+ case AttributeControlType.MultilineTextbox:
{
- var attributeText = string.Empty;
+ //multiline text box
var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
- if (allowHyperlinks)
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ //we never encode multiline text box input
+ break;
+ }
+ case AttributeControlType.FileUpload:
+ {
+ //file upload
+ if (Guid.TryParse(valueStr, out var downloadGuid))
{
- var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
- attributeText =
- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";
+ var attributeText = string.Empty;
+ var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
+ if (allowHyperlinks)
+ {
+ var downloadLink =
+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ attributeText =
+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";
+ }
+
+ formattedAttribute = $"{attributeName}: {attributeText}";
}
- formattedAttribute = $"{attributeName}: {attributeText}";
+ break;
+ }
+ default:
+ {
+ //other attributes (text box, datepicker)
+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
}
- }
- else
- {
- //other attributes (text box, datepicker)
- formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
}
}
else
diff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs
index a6916ec8a..9dc99fe3c 100644
--- a/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs
+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs
@@ -681,20 +681,21 @@ namespace Grand.Domain.Data.LiteDb
MemberExpression expr = null;
- if (Field.Body is MemberExpression expression)
+ switch (Field.Body)
{
- expr = expression;
- }
- else if (Field.Body is UnaryExpression)
- {
- expr = (MemberExpression)((UnaryExpression)Field.Body).Operand;
- }
- else
- {
- const string Format = "Expression '{0}' not supported.";
- var message = string.Format(Format, Field);
+ case MemberExpression expression:
+ expr = expression;
+ break;
+ case UnaryExpression expression:
+ expr = (MemberExpression)expression.Operand;
+ break;
+ default:
+ {
+ const string format = "Expression '{0}' not supported.";
+ var message = string.Format(format, Field);
- throw new ArgumentException(message, "Field");
+ throw new ArgumentException(message, "Field");
+ }
}
return expr.Member.Name;
diff --git a/src/Web/Grand.Web.Admin/Controllers/LayoutController.cs b/src/Web/Grand.Web.Admin/Controllers/LayoutController.cs
index a36a0e19f..92734eb54 100644
--- a/src/Web/Grand.Web.Admin/Controllers/LayoutController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/LayoutController.cs
@@ -87,19 +87,19 @@ namespace Grand.Web.Admin.Controllers
[HttpPost]
public async Task<IActionResult> CategoryLayoutAdd(CategoryLayoutModel model)
{
- if (!ModelState.IsValid)
- {
- return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
- }
- if (ModelState.IsValid)
+ switch (ModelState.IsValid)
{
- var layout = new CategoryLayout();
- layout = model.ToEntity(layout);
- await _categoryLayoutService.InsertCategoryLayout(layout);
-
- return new JsonResult("");
+ case false:
+ return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case true:
+ {
+ var layout = new CategoryLayout();
+ layout = model.ToEntity(layout);
+ await _categoryLayoutService.InsertCategoryLayout(layout);
+
+ return new JsonResult("");
+ }
}
- return ErrorForKendoGridJson(ModelState);
}
[HttpPost]
@@ -160,18 +160,18 @@ namespace Grand.Web.Admin.Controllers
[HttpPost]
public async Task<IActionResult> BrandLayoutAdd(BrandLayoutModel model)
{
- if (!ModelState.IsValid)
+ switch (ModelState.IsValid)
{
- return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case false:
+ return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case true:
+ {
+ var layout = new BrandLayout();
+ layout = model.ToEntity(layout);
+ await _brandLayoutService.InsertBrandLayout(layout);
+ return new JsonResult("");
+ }
}
- if (ModelState.IsValid)
- {
- var layout = new BrandLayout();
- layout = model.ToEntity(layout);
- await _brandLayoutService.InsertBrandLayout(layout);
- return new JsonResult("");
- }
- return ErrorForKendoGridJson(ModelState);
}
[HttpPost]
@@ -230,18 +230,18 @@ namespace Grand.Web.Admin.Controllers
[HttpPost]
public async Task<IActionResult> CollectionLayoutAdd(CollectionLayoutModel model)
{
- if (!ModelState.IsValid)
- {
- return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
- }
- if (ModelState.IsValid)
+ switch (ModelState.IsValid)
{
- var layout = new CollectionLayout();
- layout = model.ToEntity(layout);
- await _collectionLayoutService.InsertCollectionLayout(layout);
- return new JsonResult("");
+ case false:
+ return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case true:
+ {
+ var layout = new CollectionLayout();
+ layout = model.ToEntity(layout);
+ await _collectionLayoutService.InsertCollectionLayout(layout);
+ return new JsonResult("");
+ }
}
- return ErrorForKendoGridJson(ModelState);
}
[HttpPost]
@@ -300,18 +300,18 @@ namespace Grand.Web.Admin.Controllers
[HttpPost]
public async Task<IActionResult> ProductLayoutAdd(ProductLayoutModel model)
{
- if (!ModelState.IsValid)
+ switch (ModelState.IsValid)
{
- return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case false:
+ return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case true:
+ {
+ var layout = new ProductLayout();
+ layout = model.ToEntity(layout);
+ await _productLayoutService.InsertProductLayout(layout);
+ return new JsonResult("");
+ }
}
- if (ModelState.IsValid)
- {
- var layout = new ProductLayout();
- layout = model.ToEntity(layout);
- await _productLayoutService.InsertProductLayout(layout);
- return new JsonResult("");
- }
- return ErrorForKendoGridJson(ModelState);
}
[HttpPost]
@@ -320,12 +320,9 @@ namespace Grand.Web.Admin.Controllers
var layout = await _productLayoutService.GetProductLayoutById(id);
if (layout == null)
throw new ArgumentException("No template found with the specified id");
- if (ModelState.IsValid)
- {
- await _productLayoutService.DeleteProductLayout(layout);
- return new JsonResult("");
- }
- return ErrorForKendoGridJson(ModelState);
+ if (!ModelState.IsValid) return ErrorForKendoGridJson(ModelState);
+ await _productLayoutService.DeleteProductLayout(layout);
+ return new JsonResult("");
}
#endregion
@@ -359,30 +356,27 @@ namespace Grand.Web.Admin.Controllers
var layout = await _pageLayoutService.GetPageLayoutById(model.Id);
if (layout == null)
throw new ArgumentException("No template found with the specified id");
- if (ModelState.IsValid)
- {
- layout = model.ToEntity(layout);
- await _pageLayoutService.UpdatePageLayout(layout);
- return new JsonResult("");
- }
- return ErrorForKendoGridJson(ModelState);
+ if (!ModelState.IsValid) return ErrorForKendoGridJson(ModelState);
+ layout = model.ToEntity(layout);
+ await _pageLayoutService.UpdatePageLayout(layout);
+ return new JsonResult("");
}
[HttpPost]
public async Task<IActionResult> PageLayoutAdd(PageLayoutModel model)
{
- if (!ModelState.IsValid)
+ switch (ModelState.IsValid)
{
- return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
- }
- if (ModelState.IsValid)
- {
- var layout = new PageLayout();
- layout = model.ToEntity(layout);
- await _pageLayoutService.InsertPageLayout(layout);
- return new JsonResult("");
+ case false:
+ return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+ case true:
+ {
+ var layout = new PageLayout();
+ layout = model.ToEntity(layout);
+ await _pageLayoutService.InsertPageLayout(layout);
+ return new JsonResult("");
+ }
}
- return ErrorForKendoGridJson(ModelState);
}
[HttpPost]
@@ -391,12 +385,9 @@ namespace Grand.Web.Admin.Controllers
var layout = await _pageLayoutService.GetPageLayoutById(id);
if (layout == null)
throw new ArgumentException("No layout found with the specified id");
- if (ModelState.IsValid)
- {
- await _pageLayoutService.DeletePageLayout(layout);
- return new JsonResult("");
- }
- return ErrorForKendoGridJson(ModelState);
+ if (!ModelState.IsValid) return ErrorForKendoGridJson(ModelState);
+ await _pageLayoutService.DeletePageLayout(layout);
+ return new JsonResult("");
}
#endregion
diff --git a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
index b28b0066b..c7a07c277 100644
--- a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
@@ -103,10 +103,15 @@ namespace Grand.Web.Admin.Controllers
public async Task<IActionResult> SubscriptionList(DataSourceRequest command, NewsLetterSubscriptionListModel model, string[] searchCategoryIds)
{
bool? isActive = null;
- if (model.ActiveId == 1)
- isActive = true;
- else if (model.ActiveId == 2)
- isActive = false;
+ switch (model.ActiveId)
+ {
+ case 1:
+ isActive = true;
+ break;
+ case 2:
+ isActive = false;
+ break;
+ }
if (await _groupService.IsStaff(_workContext.CurrentCustomer))
{
@@ -167,10 +172,15 @@ namespace Grand.Web.Admin.Controllers
public async Task<IActionResult> ExportCsv(NewsLetterSubscriptionListModel model, string[] searchCategoryIds)
{
bool? isActive = null;
- if (model.ActiveId == 1)
- isActive = true;
- else if (model.ActiveId == 2)
- isActive = false;
+ switch (model.ActiveId)
+ {
+ case 1:
+ isActive = true;
+ break;
+ case 2:
+ isActive = false;
+ break;
+ }
if (await _groupService.IsStaff(_workContext.CurrentCustomer))
{
diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
index f3aafef01..8eb7b23c7 100644
--- a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
@@ -158,14 +158,15 @@ namespace Grand.Web.Admin.Controllers
order = await _orderService.GetOrderByNumber(orderNumber);
}
var orders = await _orderService.GetOrdersByCode(model.GoDirectlyToNumber);
- if (orders.Count > 1)
+ switch (orders.Count)
{
- return RedirectToAction("List", new { Code = model.GoDirectlyToNumber });
- }
- if (orders.Count == 1)
- {
- order = orders.FirstOrDefault();
+ case > 1:
+ return RedirectToAction("List", new { Code = model.GoDirectlyToNumber });
+ case 1:
+ order = orders.FirstOrDefault();
+ break;
}
+
if (order == null || await CheckSalesManager(order))
return RedirectToAction("List");
@@ -1096,12 +1097,21 @@ namespace Grand.Web.Admin.Controllers
}
var address = new Address();
- if (billingAddress && order.BillingAddress != null)
- if (order.BillingAddress.Id == addressId)
- address = order.BillingAddress;
- if (!billingAddress && order.ShippingAddress != null)
- if (order.ShippingAddress.Id == addressId)
- address = order.ShippingAddress;
+ switch (billingAddress)
+ {
+ case true when order.BillingAddress != null:
+ {
+ if (order.BillingAddress.Id == addressId)
+ address = order.BillingAddress;
+ break;
+ }
+ case false when order.ShippingAddress != null:
+ {
+ if (order.ShippingAddress.Id == addressId)
+ address = order.ShippingAddress;
+ break;
+ }
+ }
if (address == null)
throw new ArgumentException("No address found with the specified id", "addressId");
diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
index e2bf53907..9f2fc04b7 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
@@ -139,10 +139,15 @@ namespace Grand.Web.Admin.Controllers
{
var pluginInfos = PluginManager.ReferencedPlugins.ToList();
var loadMode = (LoadPluginsStatus)model.SearchLoadModeId;
- if (loadMode == LoadPluginsStatus.InstalledOnly)
- pluginInfos = pluginInfos.Where(x => x.Installed).ToList();
- if (loadMode == LoadPluginsStatus.NotInstalledOnly)
- pluginInfos = pluginInfos.Where(x => !x.Installed).ToList();
+ switch (loadMode)
+ {
+ case LoadPluginsStatus.InstalledOnly:
+ pluginInfos = pluginInfos.Where(x => x.Installed).ToList();
+ break;
+ case LoadPluginsStatus.NotInstalledOnly:
+ pluginInfos = pluginInfos.Where(x => !x.Installed).ToList();
+ break;
+ }
var items = new List<PluginModel>();
foreach (var item in pluginInfos.OrderBy(x => x.Group))
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
index 482683fed..0c5881401 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
@@ -2632,17 +2632,17 @@ namespace Grand.Web.Admin.Controllers
await _productService.UpdateProductField(product, x => x.IncBothDate, model.IncBothDate);
var minutesToAdd = 0;
- if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Minute)
- {
- minutesToAdd = model.Interval;
- }
- else if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Hour)
- {
- minutesToAdd = model.Interval * 60;
- }
- else if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Day)
- {
- minutesToAdd = model.Interval * 60 * 24;
+ switch ((IntervalUnit)model.IntervalUnit)
+ {
+ case IntervalUnit.Minute:
+ minutesToAdd = model.Interval;
+ break;
+ case IntervalUnit.Hour:
+ minutesToAdd = model.Interval * 60;
+ break;
+ case IntervalUnit.Day:
+ minutesToAdd = model.Interval * 60 * 24;
+ break;
}
var _hourFrom = model.StartTime.Hour;
diff --git a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs
index b3b1b68bf..9e2d6d5e0 100644
--- a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs
@@ -253,10 +253,15 @@ namespace Grand.Web.Admin.Controllers
var catalogSettings = _settingService.LoadSetting<CatalogSettings>(storeScope);
catalogSettings.ProductSortingEnumDisplayOrder[model.Id] = model.DisplayOrder;
- if (model.IsActive && catalogSettings.ProductSortingEnumDisabled.Contains(model.Id))
- catalogSettings.ProductSortingEnumDisabled.Remove(model.Id);
- if (!model.IsActive && !catalogSettings.ProductSortingEnumDisabled.Contains(model.Id))
- catalogSettings.ProductSortingEnumDisabled.Add(model.Id);
+ switch (model.IsActive)
+ {
+ case true when catalogSettings.ProductSortingEnumDisabled.Contains(model.Id):
+ catalogSettings.ProductSortingEnumDisabled.Remove(model.Id);
+ break;
+ case false when !catalogSettings.ProductSortingEnumDisabled.Contains(model.Id):
+ catalogSettings.ProductSortingEnumDisabled.Add(model.Id);
+ break;
+ }
await _settingService.SaveSetting(catalogSettings, storeScope);
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
index 8f6a491be..d8e8e402f 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
@@ -755,22 +755,27 @@ namespace Grand.Web.Admin.Services
customer.Email = model.Email;
}
- //username
- if (_customerSettings.UsernamesEnabled && _customerSettings.AllowUsersToChangeUsernames)
+ switch (_customerSettings.UsernamesEnabled)
{
- if (!string.IsNullOrWhiteSpace(model.Username))
+ //username
+ case true when _customerSettings.AllowUsersToChangeUsernames:
{
- await _customerManagerService.SetUsername(customer, model.Username);
- }
- else
- {
- customer.Username = model.Username;
+ if (!string.IsNullOrWhiteSpace(model.Username))
+ {
+ await _customerManagerService.SetUsername(customer, model.Username);
+ }
+ else
+ {
+ customer.Username = model.Username;
+ }
+
+ break;
}
+ case false:
+ customer.Username = model.Email;
+ break;
}
- if (!_customerSettings.UsernamesEnabled)
- customer.Username = model.Email;
-
if (!string.IsNullOrEmpty(model.Owner))
{
var customerOwner = await _customerService.GetCustomerByEmail(model.Owner);
diff --git a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
index 59c06cf11..92283b23e 100644
--- a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
@@ -188,45 +188,52 @@ namespace Grand.Web.Admin.Services
discount = model.ToEntity(discount, _dateTimeService);
await _discountService.UpdateDiscount(discount);
- //clean up old references (if changed) and update "HasDiscountsApplied" properties
- if (prevDiscountType == DiscountType.AssignedToCategories
- && discount.DiscountTypeId != DiscountType.AssignedToCategories)
+ switch (prevDiscountType)
{
- //applied to categories
- //_categoryService.
- var categories = await _categoryService.GetAllCategoriesByDiscount(discount.Id);
-
- //update "HasDiscountsApplied" property
- foreach (var category in categories)
+ //clean up old references (if changed) and update "HasDiscountsApplied" properties
+ case DiscountType.AssignedToCategories
+ when discount.DiscountTypeId != DiscountType.AssignedToCategories:
{
- var item = category.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
- category.AppliedDiscounts.Remove(item);
- }
- }
+ //applied to categories
+ //_categoryService.
+ var categories = await _categoryService.GetAllCategoriesByDiscount(discount.Id);
- if (prevDiscountType == DiscountType.AssignedToCollections
- && discount.DiscountTypeId != DiscountType.AssignedToCollections)
- {
- //applied to collections
- var collections = await _collectionService.GetAllCollectionsByDiscount(discount.Id);
- foreach (var collection in collections)
+ //update "HasDiscountsApplied" property
+ foreach (var category in categories)
+ {
+ var item = category.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
+ category.AppliedDiscounts.Remove(item);
+ }
+
+ break;
+ }
+ case DiscountType.AssignedToCollections
+ when discount.DiscountTypeId != DiscountType.AssignedToCollections:
{
- var item = collection.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
- collection.AppliedDiscounts.Remove(item);
+ //applied to collections
+ var collections = await _collectionService.GetAllCollectionsByDiscount(discount.Id);
+ foreach (var collection in collections)
+ {
+ var item = collection.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
+ collection.AppliedDiscounts.Remove(item);
+ }
+
+ break;
}
- }
+ case DiscountType.AssignedToSkus
+ when discount.DiscountTypeId != DiscountType.AssignedToSkus:
+ {
+ //applied to products
+ var products = await _productService.GetProductsByDiscount(discount.Id);
- if (prevDiscountType == DiscountType.AssignedToSkus
- && discount.DiscountTypeId != DiscountType.AssignedToSkus)
- {
- //applied to products
- var products = await _productService.GetProductsByDiscount(discount.Id);
+ foreach (var p in products)
+ {
+ var item = p.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
+ p.AppliedDiscounts.Remove(item);
+ await _productService.DeleteDiscount(item, p.Id);
+ }
- foreach (var p in products)
- {
- var item = p.AppliedDiscounts.FirstOrDefault(x => x == discount.Id);
- p.AppliedDiscounts.Remove(item);
- await _productService.DeleteDiscount(item, p.Id);
+ break;
}
}
diff --git a/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs b/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
index c4b664730..70a0020b4 100644
--- a/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
@@ -105,10 +105,15 @@ namespace Grand.Web.Admin.Services
PrepareGiftVoucherModel(GiftVoucherListModel model, int pageIndex, int pageSize)
{
bool? isGiftVoucherActivated = null;
- if (model.ActivatedId == 1)
- isGiftVoucherActivated = true;
- else if (model.ActivatedId == 2)
- isGiftVoucherActivated = false;
+ switch (model.ActivatedId)
+ {
+ case 1:
+ isGiftVoucherActivated = true;
+ break;
+ case 2:
+ isGiftVoucherActivated = false;
+ break;
+ }
var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(
isGiftVoucherActivated: isGiftVoucherActivated,
giftVoucherCouponCode: model.CouponCode,
diff --git a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
index 9ab0c0e51..2431b45a1 100644
--- a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
@@ -788,10 +788,15 @@ namespace Grand.Web.Admin.Services
//1 - published only
//2 - unpublished only
bool? overridePublished = null;
- if (model.SearchPublishedId == 1)
- overridePublished = true;
- else if (model.SearchPublishedId == 2)
- overridePublished = false;
+ switch (model.SearchPublishedId)
+ {
+ case 1:
+ overridePublished = true;
+ break;
+ case 2:
+ overridePublished = false;
+ break;
+ }
bool? showOnHomePage = null;
if (model.SearchPublishedId == 3)
@@ -861,10 +866,15 @@ namespace Grand.Web.Admin.Services
//1 - published only
//2 - unpublished only
bool? overridePublished = null;
- if (model.SearchPublishedId == 1)
- overridePublished = true;
- else if (model.SearchPublishedId == 2)
- overridePublished = false;
+ switch (model.SearchPublishedId)
+ {
+ case 1:
+ overridePublished = true;
+ break;
+ case 2:
+ overridePublished = false;
+ break;
+ }
var products = (await _productService.SearchProducts(
categoryIds: categoryIds,
diff --git a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
index 34a3e8226..fb0c22d55 100644
--- a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
@@ -408,9 +408,9 @@ namespace Grand.Web.Admin.Services
QuantityToAdd = maxQtyToAdd
};
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
+ switch (product.ManageInventoryMethodId)
{
- if (product.UseMultipleWarehouses)
+ case ManageInventoryMethod.ManageStock when product.UseMultipleWarehouses:
{
//multiple warehouses supported
shipmentItemModel.AllowToChooseWarehouse = true;
@@ -430,8 +430,10 @@ namespace Grand.Web.Admin.Services
});
}
}
+
+ break;
}
- else
+ case ManageInventoryMethod.ManageStock:
{
//multiple warehouses are not supported
var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);
@@ -444,12 +446,10 @@ namespace Grand.Web.Admin.Services
StockQuantity = product.StockQuantity
});
}
- }
- }
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
- {
- if (product.UseMultipleWarehouses)
+ break;
+ }
+ case ManageInventoryMethod.ManageStockByAttributes when product.UseMultipleWarehouses:
{
//multiple warehouses supported
shipmentItemModel.AllowToChooseWarehouse = true;
@@ -473,8 +473,10 @@ namespace Grand.Web.Admin.Services
}
}
}
+
+ break;
}
- else
+ case ManageInventoryMethod.ManageStockByAttributes:
{
//multiple warehouses are not supported
var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);
@@ -487,6 +489,8 @@ namespace Grand.Web.Admin.Services
StockQuantity = product.StockQuantity
});
}
+
+ break;
}
}
@@ -538,24 +542,28 @@ namespace Grand.Web.Admin.Services
foreach (var item in shipment.ShipmentItems)
{
var product = await _productService.GetProductById(item.ProductId);
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)
- {
- var stock = _stockQuantityService.GetTotalStockQuantity(product, useReservedQuantity: false,
- warehouseId: item.WarehouseId);
- if (stock - item.Quantity < 0)
- return (false, $"Out of stock for product {product.Name}");
- }
-
- if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)
+ switch (product.ManageInventoryMethodId)
{
- var combination = product.FindProductAttributeCombination(item.Attributes);
- if (combination == null)
- return (false, $"Can't find combination for product {product.Name}");
-
- var stock = _stockQuantityService.GetTotalStockQuantityForCombination(product, combination,
- useReservedQuantity: false, warehouseId: item.WarehouseId);
- if (stock - item.Quantity < 0)
- return (false, $"Out of stock for product {product.Name}");
+ case ManageInventoryMethod.ManageStock:
+ {
+ var stock = _stockQuantityService.GetTotalStockQuantity(product, useReservedQuantity: false,
+ warehouseId: item.WarehouseId);
+ if (stock - item.Quantity < 0)
+ return (false, $"Out of stock for product {product.Name}");
+ break;
+ }
+ case ManageInventoryMethod.ManageStockByAttributes:
+ {
+ var combination = product.FindProductAttributeCombination(item.Attributes);
+ if (combination == null)
+ return (false, $"Can't find combination for product {product.Name}");
+
+ var stock = _stockQuantityService.GetTotalStockQuantityForCombination(product, combination,
+ useReservedQuantity: false, warehouseId: item.WarehouseId);
+ if (stock - item.Quantity < 0)
+ return (false, $"Out of stock for product {product.Name}");
+ break;
+ }
}
}
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
index b7c78768a..3c307c9db 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
@@ -53,17 +53,19 @@ namespace Grand.Web.Admin.Validators.Catalog
{
var product = await productService.GetProductById(x.ProductId);
var productAttributeMapping = product.ProductAttributeMappings.FirstOrDefault(y => y.Id == x.ProductAttributeMappingId);
- if (productAttributeMapping?.AttributeControlTypeId == AttributeControlType.ColorSquares)
+ switch (productAttributeMapping?.AttributeControlTypeId)
{
- //ensure valid color is chosen/entered
- if (string.IsNullOrEmpty(x.ColorSquaresRgb))
- context.AddFailure("Color is required");
- }
-
- //ensure a picture is uploaded
- if (productAttributeMapping?.AttributeControlTypeId == AttributeControlType.ImageSquares && string.IsNullOrEmpty(x.ImageSquaresPictureId))
- {
- context.AddFailure("Image is required");
+ case AttributeControlType.ColorSquares:
+ {
+ //ensure valid color is chosen/entered
+ if (string.IsNullOrEmpty(x.ColorSquaresRgb))
+ context.AddFailure("Color is required");
+ break;
+ }
+ //ensure a picture is uploaded
+ case AttributeControlType.ImageSquares when string.IsNullOrEmpty(x.ImageSquaresPictureId):
+ context.AddFailure("Image is required");
+ break;
}
});
}
diff --git a/src/Web/Grand.Web.Admin/Validators/Common/CommonValid.cs b/src/Web/Grand.Web.Admin/Validators/Common/CommonValid.cs
index bd0b9c8c5..697309484 100644
--- a/src/Web/Grand.Web.Admin/Validators/Common/CommonValid.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Common/CommonValid.cs
@@ -4,13 +4,16 @@
{
public static bool IsCommissionValid(double? commission)
{
- if (!commission.HasValue)
- return true;
-
- if (commission < 0 || commission > 100)
- return false;
-
- return true;
+ switch (commission)
+ {
+ case null:
+ return true;
+ case < 0:
+ case > 100:
+ return false;
+ default:
+ return true;
+ }
}
}
diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
index c155ba6ca..9671e253a 100644
--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
@@ -115,11 +115,13 @@ namespace Grand.Web.Admin.Validators.Customers
var isStaffGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Staff) != null;
var isSalesGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.SalesManager) != null;
- if (isInGuestsGroup && isInRegisteredGroup)
- return "The customer cannot be in both 'Guests' and 'Registered' customer groups";
-
- if (!isInGuestsGroup && !isInRegisteredGroup)
- return "Add the customer to 'Guests' or 'Registered' customer group";
+ switch (isInGuestsGroup)
+ {
+ case true when isInRegisteredGroup:
+ return "The customer cannot be in both 'Guests' and 'Registered' customer groups";
+ case false when !isInRegisteredGroup:
+ return "Add the customer to 'Guests' or 'Registered' customer group";
+ }
if (await groupService.IsSalesManager(workContext.CurrentCustomer) &&
(isInGuestsGroup || customerGroups.Count != 1))
@@ -128,20 +130,23 @@ namespace Grand.Web.Admin.Validators.Customers
if (!await groupService.IsAdmin(workContext.CurrentCustomer) && isAdminGroup)
return "Only administrators can assign role 'Administrators'";
- if (isAdminGroup && !string.IsNullOrEmpty(customerModel.VendorId))
- return "A customer who is associated with a vendor can't be assigned the 'Administrator' role";
-
- if (isAdminGroup && !string.IsNullOrEmpty(customerModel.StaffStoreId))
- return "A customer who is associated with a staff can't be assigned the 'Administrator' role";
-
- if (isVendorGroup && string.IsNullOrEmpty(customerModel.VendorId))
- return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
-
- if (isVendorGroup && string.IsNullOrEmpty(customerModel.VendorId))
- return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
+ switch (isAdminGroup)
+ {
+ case true when !string.IsNullOrEmpty(customerModel.VendorId):
+ return "A customer who is associated with a vendor can't be assigned the 'Administrator' role";
+ case true when !string.IsNullOrEmpty(customerModel.StaffStoreId):
+ return "A customer who is associated with a staff can't be assigned the 'Administrator' role";
+ }
- if (isVendorGroup && isStaffGroup)
- return translationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff");
+ switch (isVendorGroup)
+ {
+ case true when string.IsNullOrEmpty(customerModel.VendorId):
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
+ case true when string.IsNullOrEmpty(customerModel.VendorId):
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
+ case true when isStaffGroup:
+ return translationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff");
+ }
if (isStaffGroup && string.IsNullOrEmpty(customerModel.StaffStoreId))
return translationService.GetResource("Admin.Customers.Customers.CannotBeInStaffGroupWithoutStaffAssociated");
diff --git a/src/Web/Grand.Web/Controllers/ActionCartController.cs b/src/Web/Grand.Web/Controllers/ActionCartController.cs
index 52bdb1894..fd6921027 100644
--- a/src/Web/Grand.Web/Controllers/ActionCartController.cs
+++ b/src/Web/Grand.Web/Controllers/ActionCartController.cs
@@ -80,24 +80,23 @@ namespace Grand.Web.Controllers
});
}
- //products with "minimum order quantity" more than a specified qty
- if (cartType == ShoppingCartType.ShoppingCart && product.OrderMinimumQuantity > quantity)
+ switch (cartType)
{
- //we cannot add to the cart such products from category pages
- return Json(new
- {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
- });
+ //products with "minimum order quantity" more than a specified qty
+ case ShoppingCartType.ShoppingCart when product.OrderMinimumQuantity > quantity:
+ //we cannot add to the cart such products from category pages
+ return Json(new
+ {
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ });
+ case ShoppingCartType.ShoppingCart when product.EnteredPrice:
+ //cannot be added to the cart (requires a customer to enter price)
+ return Json(new
+ {
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ });
}
- if (cartType == ShoppingCartType.ShoppingCart && product.EnteredPrice)
- {
- //cannot be added to the cart (requires a customer to enter price)
- return Json(new
- {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
- });
- }
var allowedQuantities = product.ParseAllowedQuantities();
if (cartType == ShoppingCartType.ShoppingCart && allowedQuantities.Length > 0)
{
@@ -128,35 +127,31 @@ namespace Grand.Web.Controllers
private IActionResult ReturnFailMessage(Product product, ShoppingCartType shoppingCartTypeId)
{
- //you can't add group products
- if (product.ProductTypeId == ProductType.GroupedProduct)
+ switch (product.ProductTypeId)
{
- return Json(new
- {
- success = false,
- message = "Grouped products couldn't be added to the cart"
- });
- }
-
- //you can't add reservation product to wishlist
- if (product.ProductTypeId == ProductType.Reservation && shoppingCartTypeId == ShoppingCartType.Wishlist)
- {
- return Json(new
- {
- success = false,
- message = "Reservation products couldn't be added to the wishlist"
- });
+ //you can't add group products
+ case ProductType.GroupedProduct:
+ return Json(new
+ {
+ success = false,
+ message = "Grouped products couldn't be added to the cart"
+ });
+ //you can't add reservation product to wishlist
+ case ProductType.Reservation when shoppingCartTypeId == ShoppingCartType.Wishlist:
+ return Json(new
+ {
+ success = false,
+ message = "Reservation products couldn't be added to the wishlist"
+ });
+ //you can't add auction product to wishlist
+ case ProductType.Auction when shoppingCartTypeId == ShoppingCartType.Wishlist:
+ return Json(new
+ {
+ success = false,
+ message = "Auction products couldn't be added to the wishlist"
+ });
}
- //you can't add auction product to wishlist
- if (product.ProductTypeId == ProductType.Auction && shoppingCartTypeId == ShoppingCartType.Wishlist)
- {
- return Json(new
- {
- success = false,
- message = "Auction products couldn't be added to the wishlist"
- });
- }
//check available date
if (product.AvailableEndDateTimeUtc.HasValue && product.AvailableEndDateTimeUtc.Value < DateTime.UtcNow)
{
@@ -589,35 +584,31 @@ namespace Grand.Web.Controllers
});
}
- //you can't add group products
- if (product.ProductTypeId == ProductType.GroupedProduct)
+ switch (product.ProductTypeId)
{
- return Json(new
- {
- success = false,
- message = "Grouped products couldn't be added to the cart"
- });
- }
-
- //you can't add reservation product to wishlist
- if (product.ProductTypeId == ProductType.Reservation && cart.ShoppingCartTypeId == ShoppingCartType.Wishlist)
- {
- return Json(new
- {
- success = false,
- message = "Reservation products couldn't be added to the wishlist"
- });
+ //you can't add group products
+ case ProductType.GroupedProduct:
+ return Json(new
+ {
+ success = false,
+ message = "Grouped products couldn't be added to the cart"
+ });
+ //you can't add reservation product to wishlist
+ case ProductType.Reservation when cart.ShoppingCartTypeId == ShoppingCartType.Wishlist:
+ return Json(new
+ {
+ success = false,
+ message = "Reservation products couldn't be added to the wishlist"
+ });
+ //you can't add auction product to wishlist
+ case ProductType.Auction:
+ return Json(new
+ {
+ success = false,
+ message = "Auction products couldn't be added to the wishlist"
+ });
}
- //you can't add auction product to wishlist
- if (product.ProductTypeId == ProductType.Auction)
- {
- return Json(new
- {
- success = false,
- message = "Auction products couldn't be added to the wishlist"
- });
- }
//check available date
if (product.AvailableEndDateTimeUtc.HasValue && product.AvailableEndDateTimeUtc.Value < DateTime.UtcNow)
{
@@ -662,39 +653,43 @@ namespace Grand.Web.Controllers
//product reservation
if (product.ProductTypeId == ProductType.Reservation)
{
- if (product.IntervalUnitId is IntervalUnit.Hour or IntervalUnit.Minute)
+ switch (product.IntervalUnitId)
{
- if (string.IsNullOrEmpty(model.Reservation))
- {
+ case IntervalUnit.Hour or IntervalUnit.Minute when string.IsNullOrEmpty(model.Reservation):
return Json(new
{
success = false,
message = _translationService.GetResource("Product.Addtocart.Reservation.Required")
});
- }
- var productReservationService = HttpContext.RequestServices.GetRequiredService<IProductReservationService>();
- var reservation = await productReservationService.GetProductReservation(model.Reservation);
- if (reservation == null)
+ case IntervalUnit.Hour or IntervalUnit.Minute:
{
- return Json(new
+ var productReservationService = HttpContext.RequestServices.GetRequiredService<IProductReservationService>();
+ var reservation = await productReservationService.GetProductReservation(model.Reservation);
+ if (reservation == null)
{
- success = false,
- message = "No reservation found"
- });
- }
+ return Json(new
+ {
+ success = false,
+ message = "No reservation found"
+ });
+ }
- rentalStartDate = reservation.Date;
- }
- else if (product.IntervalUnitId == IntervalUnit.Day)
- {
- const string datePickerFormat = "MM/dd/yyyy";
- if (!string.IsNullOrEmpty(model.ReservationDatepickerFrom))
- {
- rentalStartDate = DateTime.ParseExact(model.ReservationDatepickerFrom, datePickerFormat, CultureInfo.InvariantCulture);
+ rentalStartDate = reservation.Date;
+ break;
}
- if (!string.IsNullOrEmpty(model.ReservationDatepickerTo))
+ case IntervalUnit.Day:
{
- rentalEndDate = DateTime.ParseExact(model.ReservationDatepickerTo, datePickerFormat, CultureInfo.InvariantCulture);
+ const string datePickerFormat = "MM/dd/yyyy";
+ if (!string.IsNullOrEmpty(model.ReservationDatepickerFrom))
+ {
+ rentalStartDate = DateTime.ParseExact(model.ReservationDatepickerFrom, datePickerFormat, CultureInfo.InvariantCulture);
+ }
+ if (!string.IsNullOrEmpty(model.ReservationDatepickerTo))
+ {
+ rentalEndDate = DateTime.ParseExact(model.ReservationDatepickerTo, datePickerFormat, CultureInfo.InvariantCulture);
+ }
+
+ break;
}
}
}
diff --git a/src/Web/Grand.Web/Controllers/InstallController.cs b/src/Web/Grand.Web/Controllers/InstallController.cs
index 3451ec252..aa0c9aa95 100644
--- a/src/Web/Grand.Web/Controllers/InstallController.cs
+++ b/src/Web/Grand.Web/Controllers/InstallController.cs
@@ -163,13 +163,14 @@ namespace Grand.Web.Controllers
protected async Task CheckConnectionString(IInstallationLocalizedService locService, string connectionString, InstallModel model)
{
- if (!_dbConfig.UseLiteDb && model.DataProvider == DbProvider.LiteDB)
+ switch (_dbConfig.UseLiteDb)
{
- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbEnable"));
- }
- if (_dbConfig.UseLiteDb && model.DataProvider != DbProvider.LiteDB)
- {
- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbDisable"));
+ case false when model.DataProvider == DbProvider.LiteDB:
+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbEnable"));
+ break;
+ case true when model.DataProvider != DbProvider.LiteDB:
+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbDisable"));
+ break;
}
if (ModelState.IsValid && !string.IsNullOrEmpty(connectionString))
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
index a5b87102a..150459c1c 100644
--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
@@ -940,12 +940,17 @@ namespace Grand.Web.Features.Handlers.Products
await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);
var productprice =
await _taxService.GetProductPrice(product, attributeValuePriceAdjustment);
- if (productprice.productprice > 0)
- valueModel.PriceAdjustment =
- "+" + _priceFormatter.FormatPrice(productprice.productprice, false);
- else if (productprice.productprice < 0)
- valueModel.PriceAdjustment =
- "-" + _priceFormatter.FormatPrice(-productprice.productprice, false);
+ switch (productprice.productprice)
+ {
+ case > 0:
+ valueModel.PriceAdjustment =
+ "+" + _priceFormatter.FormatPrice(productprice.productprice, false);
+ break;
+ case < 0:
+ valueModel.PriceAdjustment =
+ "-" + _priceFormatter.FormatPrice(-productprice.productprice, false);
+ break;
+ }
valueModel.PriceAdjustmentValue = productprice.productprice;
}
diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs
index 73a8fde45..931013e0b 100644
--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs
@@ -144,23 +144,27 @@ namespace Grand.Web.Features.Handlers.ShoppingCart
}
- if (request.CartType == ShoppingCartType.ShoppingCart)
+ switch (request.CartType)
{
- var subTotalIncludingTax = request.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal;
- var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax);
- model.SubTotal = _priceFormatter.FormatPrice(shoppingCartSubTotal.subTotalWithoutDiscount, request.Currency, request.Language, subTotalIncludingTax);
- model.DecimalSubTotal = shoppingCartSubTotal.subTotalWithoutDiscount;
- if (shoppingCartSubTotal.discountAmount > 0)
+ case ShoppingCartType.ShoppingCart:
{
- model.SubTotalDiscount = _priceFormatter.FormatPrice(-shoppingCartSubTotal.discountAmount, request.Currency, request.Language, subTotalIncludingTax);
+ var subTotalIncludingTax = request.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal;
+ var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax);
+ model.SubTotal = _priceFormatter.FormatPrice(shoppingCartSubTotal.subTotalWithoutDiscount, request.Currency, request.Language, subTotalIncludingTax);
+ model.DecimalSubTotal = shoppingCartSubTotal.subTotalWithoutDiscount;
+ if (shoppingCartSubTotal.discountAmount > 0)
+ {
+ model.SubTotalDiscount = _priceFormatter.FormatPrice(-shoppingCartSubTotal.discountAmount, request.Currency, request.Language, subTotalIncludingTax);
+ }
+
+ break;
}
- }
- else if (request.CartType == ShoppingCartType.Auctions)
- {
- model.IsAuction = true;
- model.HighestBidValue = request.Product.HighestBid;
- model.HighestBid = _priceFormatter.FormatPrice(request.Product.HighestBid);
- model.EndTime = request.Product.AvailableEndDateTimeUtc;
+ case ShoppingCartType.Auctions:
+ model.IsAuction = true;
+ model.HighestBidValue = request.Product.HighestBid;
+ model.HighestBid = _priceFormatter.FormatPrice(request.Product.HighestBid);
+ model.EndTime = request.Product.AvailableEndDateTimeUtc;
+ break;
}
return model;
diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
index 58c699f90..033f1a141 100644
--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
@@ -228,10 +228,15 @@ namespace Grand.Web.Features.Handlers.ShoppingCart
if (!await _permissionService.Authorize(StandardPermission.DisplayPrices)) continue;
var priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue)).checkoutPrice;
var priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, request.Currency);
- if (priceAdjustmentBase > 0)
- attributeValueModel.PriceAdjustment = "+" + _priceFormatter.FormatPrice(priceAdjustment);
- else if (priceAdjustmentBase < 0)
- attributeValueModel.PriceAdjustment = "-" + _priceFormatter.FormatPrice(-priceAdjustment);
+ switch (priceAdjustmentBase)
+ {
+ case > 0:
+ attributeValueModel.PriceAdjustment = "+" + _priceFormatter.FormatPrice(priceAdjustment);
+ break;
+ case < 0:
+ attributeValueModel.PriceAdjustment = "-" + _priceFormatter.FormatPrice(-priceAdjustment);
+ break;
+ }
}
}
//set already selected attributes
diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
index 2477418a4..6b8cab4d9 100644
--- a/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
+++ b/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
@@ -20,13 +20,21 @@ namespace Grand.Web.Validators.ShoppingCart
RuleFor(x => x.Quantity).GreaterThan(0).WithMessage("Wrong quantity");
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
- if(x.ShoppingCartType == ShoppingCartType.ShoppingCart)
- if (!await permissionService.Authorize(StandardPermission.EnableShoppingCart))
- context.AddFailure("No permission");
-
- if(x.ShoppingCartType == ShoppingCartType.Wishlist)
- if (!await permissionService.Authorize(StandardPermission.EnableWishlist))
- context.AddFailure("No permission");
+ switch (x.ShoppingCartType)
+ {
+ case ShoppingCartType.ShoppingCart:
+ {
+ if (!await permissionService.Authorize(StandardPermission.EnableShoppingCart))
+ context.AddFailure("No permission");
+ break;
+ }
+ case ShoppingCartType.Wishlist:
+ {
+ if (!await permissionService.Authorize(StandardPermission.EnableWishlist))
+ context.AddFailure("No permission");
+ break;
+ }
+ }
var cart = (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, PrepareCartTypes()))
.FirstOrDefault(z => z.Id == x.ShoppingCartId);