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.

Plugins - code improvements and use common practice/fix spelling issue/improve syntax style

support11104746d976
diff --git a/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml b/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml
index 5f3cb6078..112dfb5c7 100644
--- a/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml
+++ b/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml
@@ -16,7 +16,7 @@
3. Fill out the form and tap the <b>Create App ID button</b>.<br />
4. The <b>Product Setup</b> page is displayed, letting you select the features for your new app. Click <b>Get Started</b> on <b>Facebook Login</b>.<br />
5. Click the <b>Settings</b> link in the menu at the left, you are presented with the <b>Client OAuth Settings</b> page with some defaults already set.<br />
- 6. Enter "@($"https://yourstore.com/signin-facebook")" into the <b>Valid OAuth Redirect URIs</b> field.<br />
+ 6. Enter "@("https://yourstore.com/signin-facebook")" into the <b>Valid OAuth Redirect URIs</b> field.<br />
7. Click <b>Save Changes</b>.<br />
8. Click the <b>Dashboard</b> link in the left navigation.<br />
9. Copy your App ID and App secret below.<br />
@@ -32,7 +32,7 @@
<admin-label asp-for="ClientId" class="control-label" />
</div>
<div class="col-md-9 col-sm-9">
- <input asp-for=ClientId type="text"
+ <input asp-for="ClientId" type="text"
disabled class="form-control k-input text-box single-line" />
<span asp-validation-for="ClientId"></span>
</div>
@@ -42,7 +42,7 @@
<admin-label asp-for="ClientSecret" class="control-label" />
</div>
<div class="col-md-9 col-sm-9">
- <input asp-for=ClientSecret type="text" disabled class="form-control k-input text-box single-line" />
+ <input asp-for="ClientSecret" type="text" disabled class="form-control k-input text-box single-line" />
<span asp-validation-for="ClientSecret"></span>
</div>
</div>
diff --git a/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs b/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs
index fb7c05084..6abb459f6 100644
--- a/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs
+++ b/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs
@@ -44,7 +44,7 @@ namespace Authentication.Facebook.Controllers
//configure login callback action
var authenticationProperties = new AuthenticationProperties {
- RedirectUri = Url.Action("FacebookLoginCallback", "FacebookAuthentication", new { returnUrl = returnUrl })
+ RedirectUri = Url.Action("FacebookLoginCallback", "FacebookAuthentication", new { returnUrl })
};
return Challenge(authenticationProperties, FacebookDefaults.AuthenticationScheme);
diff --git a/src/Plugins/Authentication.Facebook/EndpointProvider.cs b/src/Plugins/Authentication.Facebook/EndpointProvider.cs
index a250866da..71da303a7 100644
--- a/src/Plugins/Authentication.Facebook/EndpointProvider.cs
+++ b/src/Plugins/Authentication.Facebook/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Authentication.Facebook
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
diff --git a/src/Plugins/Authentication.Facebook/FacebookAuthConfig.cs b/src/Plugins/Authentication.Facebook/FacebookAuthConfig.cs
deleted file mode 100644
index c41b4f08d..000000000
--- a/src/Plugins/Authentication.Facebook/FacebookAuthConfig.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace Authentication.Facebook
-{
- class FacebookAuthConfig
- {
- /// <summary>
- /// Gets or sets OAuth2 client identifier
- /// </summary>
- public string ClientKeyIdentifier { get; set; }
-
- /// <summary>
- /// Gets or sets OAuth2 client secret
- /// </summary>
- public string ClientSecret { get; set; }
- }
-}
diff --git a/src/Plugins/Authentication.Facebook/FacebookAuthenticationProvider.cs b/src/Plugins/Authentication.Facebook/FacebookAuthenticationProvider.cs
index 26e25007b..fc79a5666 100644
--- a/src/Plugins/Authentication.Facebook/FacebookAuthenticationProvider.cs
+++ b/src/Plugins/Authentication.Facebook/FacebookAuthenticationProvider.cs
@@ -25,7 +25,6 @@ namespace Authentication.Facebook
/// <summary>
/// Gets a view component for displaying plugin in public store
/// </summary>
- /// <param name="viewComponentName">View component name</param>
public async Task<string> GetPublicViewComponentName()
{
return await Task.FromResult("FacebookAuthentication");
diff --git a/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs b/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs
index e5f2f1845..8ac2d6693 100644
--- a/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs
+++ b/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs
@@ -3,7 +3,7 @@ using Grand.Domain.Configuration;
namespace Authentication.Facebook
{
/// <summary>
- /// Represents settings of the Facebook authentication mehod
+ /// Represents settings of the Facebook authentication method
/// </summary>
public class FacebookExternalAuthSettings : ISettings
{
diff --git a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
index f1cdc92d7..0ef3b5fdd 100644
--- a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
@@ -11,7 +11,7 @@ namespace Authentication.Facebook.Infrastructure.Cache
/// <summary>
/// Facebook authentication event consumer (used for saving customer fields on registration)
/// </summary>
- public partial class FacebookAuthenticationEventConsumer : INotificationHandler<RegisteredByExternalMethod>
+ public class FacebookAuthenticationEventConsumer : INotificationHandler<RegisteredByExternalMethod>
{
#region Fields
diff --git a/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs b/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs
index 22d1b83ad..adf48623b 100644
--- a/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs
+++ b/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs
@@ -17,6 +17,7 @@ namespace Authentication.Facebook.Infrastructure
/// Configure
/// </summary>
/// <param name="builder">Authentication builder</param>
+ /// <param name="configuration">Configuration</param>
public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration)
{
builder.AddFacebook(FacebookDefaults.AuthenticationScheme, options =>
diff --git a/src/Plugins/Authentication.Facebook/Manifest.cs b/src/Plugins/Authentication.Facebook/Manifest.cs
index d9b5f8f9b..f2fa48230 100644
--- a/src/Plugins/Authentication.Facebook/Manifest.cs
+++ b/src/Plugins/Authentication.Facebook/Manifest.cs
@@ -8,5 +8,5 @@ using Grand.Infrastructure.Plugins;
SystemName = FacebookAuthenticationDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs b/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs
index 272b72e97..d953fefb3 100644
--- a/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs
+++ b/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs
@@ -43,7 +43,7 @@ namespace Authentication.Google.Controllers
//configure login callback action
var authenticationProperties = new AuthenticationProperties {
- RedirectUri = Url.Action("GoogleLoginCallback", "GoogleAuthentication", new { returnUrl = returnUrl })
+ RedirectUri = Url.Action("GoogleLoginCallback", "GoogleAuthentication", new { returnUrl })
};
return Challenge(authenticationProperties, GoogleDefaults.AuthenticationScheme);
diff --git a/src/Plugins/Authentication.Google/EndpointProvider.cs b/src/Plugins/Authentication.Google/EndpointProvider.cs
index ab0e9c6b7..d328b8ee1 100644
--- a/src/Plugins/Authentication.Google/EndpointProvider.cs
+++ b/src/Plugins/Authentication.Google/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Authentication.Google
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
@@ -13,12 +13,6 @@ namespace Authentication.Google
new { controller = "GoogleAuthentication", action = "GoogleSignInFailed" }
);
}
- public int Priority
- {
- get
- {
- return 10;
- }
- }
+ public int Priority => 10;
}
}
diff --git a/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs b/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs
index be7fdd2f3..dbdd208fc 100644
--- a/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs
+++ b/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs
@@ -53,9 +53,9 @@ namespace Authentication.Google
await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientKeyIdentifier", "Client ID");
await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret", "Client Secret");
await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Title", "<h4>Configuring Google OAuth2</h4>");
- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed", "Failed authentication");
- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed.Errormessage", "Error message: ");
- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Externalauth.Google.DisplayOrder", "Display order");
+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Failed", "Failed authentication");
+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Failed.Errormessage", "Error message: ");
+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.DisplayOrder", "Display order");
await base.Install();
}
@@ -75,8 +75,8 @@ namespace Authentication.Google
await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret");
await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Title");
await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.DisplayOrder");
- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed");
- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed.Errormessage");
+ await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Failed");
+ await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Failed.Errormessage");
await base.Uninstall();
}
diff --git a/src/Plugins/Authentication.Google/GoogleAuthenticationProvider.cs b/src/Plugins/Authentication.Google/GoogleAuthenticationProvider.cs
index 5e4f04569..91c78117c 100644
--- a/src/Plugins/Authentication.Google/GoogleAuthenticationProvider.cs
+++ b/src/Plugins/Authentication.Google/GoogleAuthenticationProvider.cs
@@ -26,7 +26,6 @@ namespace Authentication.Google
/// <summary>
/// Gets a view component for displaying plugin in public store
/// </summary>
- /// <param name="viewComponentName">View component name</param>
public async Task<string> GetPublicViewComponentName()
{
return await Task.FromResult("GoogleAuthentication");
diff --git a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs
index 9c0a0bddc..3901ac7e6 100644
--- a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs
+++ b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs
@@ -17,6 +17,7 @@ namespace Authentication.Google.Infrastructure
/// Configure
/// </summary>
/// <param name="builder">Authentication builder</param>
+ /// <param name="configuration">Configuration</param>
public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration)
{
builder.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
@@ -33,7 +34,7 @@ namespace Authentication.Google.Infrastructure
OnRemoteFailure = ctx =>
{
ctx.HandleResponse();
- var errorMessage = ctx.Failure.Message;
+ var errorMessage = ctx.Failure?.Message;
var state = ctx.Request.Query["state"].FirstOrDefault();
errorMessage = WebUtility.UrlEncode(errorMessage);
ctx.Response.Redirect($"/google-signin-failed?error_message={errorMessage}");
diff --git a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
index 7c28ae091..d88e021ed 100644
--- a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
@@ -11,7 +11,7 @@ namespace Authentication.Google.Infrastructure.Cache
/// <summary>
/// Google authentication event consumer (used for saving customer fields on registration)
/// </summary>
- public partial class GoogleAuthenticationEventConsumer : INotificationHandler<RegisteredByExternalMethod>
+ public class GoogleAuthenticationEventConsumer : INotificationHandler<RegisteredByExternalMethod>
{
#region Fields
diff --git a/src/Plugins/Authentication.Google/Manifest.cs b/src/Plugins/Authentication.Google/Manifest.cs
index 93989bad8..331ec8d2c 100644
--- a/src/Plugins/Authentication.Google/Manifest.cs
+++ b/src/Plugins/Authentication.Google/Manifest.cs
@@ -8,5 +8,5 @@ using Grand.Infrastructure.Plugins;
SystemName = GoogleAuthenticationDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.01"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Authentication.Google/Models/ConfigurationModel.cs b/src/Plugins/Authentication.Google/Models/ConfigurationModel.cs
index 04f3b4d44..7d7c0b7bc 100644
--- a/src/Plugins/Authentication.Google/Models/ConfigurationModel.cs
+++ b/src/Plugins/Authentication.Google/Models/ConfigurationModel.cs
@@ -9,7 +9,7 @@ namespace Authentication.Google.Models
public string ClientKeyIdentifier { get; set; }
[GrandResourceDisplayName("Plugins.ExternalAuth.Google.ClientSecret")]
public string ClientSecret { get; set; }
- [GrandResourceDisplayName("Plugins.Externalauth.Google.DisplayOrder")]
+ [GrandResourceDisplayName("Plugins.ExternalAuth.Google.DisplayOrder")]
public int DisplayOrder { get; set; }
}
}
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
index c28aeb860..c72164035 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
@@ -55,10 +55,11 @@ namespace DiscountRules.CustomerGroups.Controllers
//customer groups
model.AvailableCustomerGroups.Add(new SelectListItem { Text = "Select customer group", Value = "" });
foreach (var cr in await _groupService.GetAllCustomerGroups(showHidden: true))
- model.AvailableCustomerGroups.Add(new SelectListItem { Text = cr.Name, Value = cr.Id.ToString(), Selected = discountRequirement != null && cr.Id == discountRequirement?.Metadata });
+ model.AvailableCustomerGroups.Add(new SelectListItem { Text = cr.Name, Value = cr.Id, Selected = discountRequirement != null && cr.Id == discountRequirement?.Metadata });
//add a prefix
- ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("DiscountRulesCustomerGroups{0}", !String.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "");
+ ViewData.TemplateInfo.HtmlFieldPrefix =
+ $"DiscountRulesCustomerGroups{(!string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "")}";
return View(model);
}
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
index 699407b52..e8d07def7 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
@@ -6,6 +6,7 @@ using Grand.Web.Common.Filters;
using Grand.Domain.Discounts;
using Microsoft.AspNetCore.Mvc;
using DiscountRules.Standard.HadSpentAmount.Models;
+using System.Globalization;
namespace DiscountRules.Standard.HadSpentAmount.Controllers
{
@@ -50,7 +51,8 @@ namespace DiscountRules.Standard.HadSpentAmount.Controllers
};
//add a prefix
- ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("DiscountRulesHadSpentAmount{0}-{1}", discount.Id, !String.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "");
+ ViewData.TemplateInfo.HtmlFieldPrefix =
+ $"DiscountRulesHadSpentAmount{discount.Id}-{(!string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "")}";
return View(model);
}
@@ -73,7 +75,7 @@ namespace DiscountRules.Standard.HadSpentAmount.Controllers
if (discountRequirement != null)
{
//update existing rule
- discountRequirement.Metadata = spentAmount.ToString();
+ discountRequirement.Metadata = spentAmount.ToString(CultureInfo.InvariantCulture);
await _discountService.UpdateDiscount(discount);
}
else
@@ -81,7 +83,7 @@ namespace DiscountRules.Standard.HadSpentAmount.Controllers
//save new rule
discountRequirement = new DiscountRule {
DiscountRequirementRuleSystemName = "DiscountRules.Standard.HadSpentAmount",
- Metadata = spentAmount.ToString()
+ Metadata = spentAmount.ToString(CultureInfo.InvariantCulture)
};
discount.DiscountRules.Add(discountRequirement);
await _discountService.UpdateDiscount(discount);
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
index e1ebd0b77..6f998b30c 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
@@ -74,7 +74,8 @@ namespace DiscountRules.HasAllProducts.Controllers
};
//add a prefix
- ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("DiscountRulesHasAllProducts{0}-{1}", discount.Id, !string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "");
+ ViewData.TemplateInfo.HtmlFieldPrefix =
+ $"DiscountRulesHasAllProducts{discount.Id}-{(!string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "")}";
return View(model);
}
@@ -127,12 +128,12 @@ namespace DiscountRules.HasAllProducts.Controllers
//stores
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.ToString() });
+ model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
//vendors
model.AvailableVendors.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
foreach (var v in await _vendorService.GetAllVendors(showHidden: true))
- model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id.ToString() });
+ model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id });
//product types
model.AvailableProductTypes = ProductType.SimpleProduct.ToSelectList(HttpContext, false).ToList();
@@ -172,13 +173,14 @@ namespace DiscountRules.HasAllProducts.Controllers
pageSize: command.PageSize,
showHidden: true
)).products;
- var gridModel = new DataSourceResult();
- gridModel.Data = products.Select(x => new RequirementModel.ProductModel {
- Id = x.Id,
- Name = x.Name,
- Published = x.Published
- });
- gridModel.Total = products.TotalCount;
+ var gridModel = new DataSourceResult {
+ Data = products.Select(x => new RequirementModel.ProductModel {
+ Id = x.Id,
+ Name = x.Name,
+ Published = x.Published
+ }),
+ Total = products.TotalCount
+ };
return new JsonResult(gridModel);
}
@@ -192,38 +194,36 @@ namespace DiscountRules.HasAllProducts.Controllers
if (!await _permissionService.Authorize(StandardPermission.ManageProducts))
return new JsonResult(new { Text = result });
- if (!String.IsNullOrWhiteSpace(productIds))
+ if (string.IsNullOrWhiteSpace(productIds)) return new JsonResult(new { Text = result });
+ var ids = new List<string>();
+ var rangeArray = productIds
+ .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(x => x.Trim())
+ .ToList();
+
+ //we support three ways of specifying products:
+ //1. The comma-separated list of product identifiers (e.g. 77, 123, 156).
+ //2. The comma-separated list of product identifiers with quantities.
+ // {Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
+ //3. The comma-separated list of product identifiers with quantity range.
+ // {Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
+ foreach (var str1 in rangeArray)
+ {
+ var str2 = str1;
+ //we do not display specified quantities and ranges
+ //parse only product names
+ if (str2.Contains(':'))
+ str2 = str2[..str2.IndexOf(":", StringComparison.Ordinal)];
+
+ ids.Add(str2);
+ }
+
+ var products = await _productService.GetProductsByIds(ids.ToArray(), true);
+ for (var i = 0; i <= products.Count - 1; i++)
{
- var ids = new List<string>();
- var rangeArray = productIds
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(x => x.Trim())
- .ToList();
-
- //we support three ways of specifying products:
- //1. The comma-separated list of product identifiers (e.g. 77, 123, 156).
- //2. The comma-separated list of product identifiers with quantities.
- // {Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
- //3. The comma-separated list of product identifiers with quantity range.
- // {Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
- foreach (string str1 in rangeArray)
- {
- var str2 = str1;
- //we do not display specified quantities and ranges
- //parse only product names
- if (str2.Contains(":"))
- str2 = str2.Substring(0, str2.IndexOf(":"));
-
- ids.Add(str2);
- }
-
- var products = await _productService.GetProductsByIds(ids.ToArray(), true);
- for (int i = 0; i <= products.Count - 1; i++)
- {
- result += products[i].Name;
- if (i != products.Count - 1)
- result += ", ";
- }
+ result += products[i].Name;
+ if (i != products.Count - 1)
+ result += ", ";
}
return new JsonResult(new { Text = result });
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
index 7dd67b4ed..b37a663e4 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
@@ -73,7 +73,8 @@ namespace DiscountRules.HasOneProduct.Controllers
};
//add a prefix
- ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("DiscountRulesHasOneProduct{0}-{1}", discount.Id, !String.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "");
+ ViewData.TemplateInfo.HtmlFieldPrefix =
+ $"DiscountRulesHasOneProduct{discount.Id}-{(!string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "")}";
return View(model);
}
@@ -126,12 +127,12 @@ namespace DiscountRules.HasOneProduct.Controllers
//stores
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.ToString() });
+ model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
//vendors
model.AvailableVendors.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
foreach (var v in await _vendorService.GetAllVendors(showHidden: true))
- model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id.ToString() });
+ model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id });
//product types
model.AvailableProductTypes = ProductType.SimpleProduct.ToSelectList(HttpContext, false).ToList();
@@ -172,13 +173,14 @@ namespace DiscountRules.HasOneProduct.Controllers
pageSize: command.PageSize,
showHidden: true
)).products;
- var gridModel = new DataSourceResult();
- gridModel.Data = products.Select(x => new RequirementModel.ProductModel {
- Id = x.Id,
- Name = x.Name,
- Published = x.Published
- });
- gridModel.Total = products.TotalCount;
+ var gridModel = new DataSourceResult {
+ Data = products.Select(x => new RequirementModel.ProductModel {
+ Id = x.Id,
+ Name = x.Name,
+ Published = x.Published
+ }),
+ Total = products.TotalCount
+ };
return new JsonResult(gridModel);
}
@@ -192,38 +194,36 @@ namespace DiscountRules.HasOneProduct.Controllers
if (!await _permissionService.Authorize(StandardPermission.ManageProducts))
return new JsonResult(new { Text = result });
- if (!String.IsNullOrWhiteSpace(productIds))
+ if (string.IsNullOrWhiteSpace(productIds)) return new JsonResult(new { Text = result });
+ var ids = new List<string>();
+ var rangeArray = productIds
+ .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
+ .Select(x => x.Trim())
+ .ToList();
+
+ //we support three ways of specifying products:
+ //1. The comma-separated list of product identifiers (e.g. 77, 123, 156).
+ //2. The comma-separated list of product identifiers with quantities.
+ // {Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
+ //3. The comma-separated list of product identifiers with quantity range.
+ // {Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
+ foreach (var str1 in rangeArray)
+ {
+ var str2 = str1;
+ //we do not display specified quantities and ranges
+ //parse only product names (before : sign)
+ if (str2.Contains(':'))
+ str2 = str2[..str2.IndexOf(":", StringComparison.Ordinal)];
+
+ ids.Add(str2);
+ }
+
+ var products = await _productService.GetProductsByIds(ids.ToArray(), true);
+ for (var i = 0; i <= products.Count - 1; i++)
{
- var ids = new List<string>();
- var rangeArray = productIds
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(x => x.Trim())
- .ToList();
-
- //we support three ways of specifying products:
- //1. The comma-separated list of product identifiers (e.g. 77, 123, 156).
- //2. The comma-separated list of product identifiers with quantities.
- // {Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
- //3. The comma-separated list of product identifiers with quantity range.
- // {Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
- foreach (string str1 in rangeArray)
- {
- var str2 = str1;
- //we do not display specified quantities and ranges
- //parse only product names (before : sign)
- if (str2.Contains(":"))
- str2 = str2.Substring(0, str2.IndexOf(":"));
-
- ids.Add(str2);
- }
-
- var products = await _productService.GetProductsByIds(ids.ToArray(), true);
- for (int i = 0; i <= products.Count - 1; i++)
- {
- result += products[i].Name;
- if (i != products.Count - 1)
- result += ", ";
- }
+ result += products[i].Name;
+ if (i != products.Count - 1)
+ result += ", ";
}
return new JsonResult(new { Text = result });
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
index fd8860cca..b6a266582 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
@@ -6,6 +6,7 @@ using Grand.Web.Common.Filters;
using Grand.Domain.Discounts;
using Grand.Plugin.DiscountRules.ShoppingCart.Models;
using Microsoft.AspNetCore.Mvc;
+using System.Globalization;
namespace DiscountRules.Standard.Controllers
{
@@ -49,7 +50,8 @@ namespace DiscountRules.Standard.Controllers
};
//add a prefix
- ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("DiscountRulesShoppingCart{0}", !String.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "");
+ ViewData.TemplateInfo.HtmlFieldPrefix =
+ $"DiscountRulesShoppingCart{(!string.IsNullOrEmpty(discountRequirementId) ? discountRequirementId : "")}";
return View(model);
}
@@ -72,7 +74,7 @@ namespace DiscountRules.Standard.Controllers
if (discountRequirement != null)
{
//update existing rule
- discountRequirement.Metadata = spentAmount.ToString();
+ discountRequirement.Metadata = spentAmount.ToString(CultureInfo.InvariantCulture);
await _discountService.UpdateDiscount(discount);
}
else
@@ -81,7 +83,7 @@ namespace DiscountRules.Standard.Controllers
discountRequirement = new DiscountRule
{
DiscountRequirementRuleSystemName = "DiscountRequirement.ShoppingCart",
- Metadata = spentAmount.ToString()
+ Metadata = spentAmount.ToString(CultureInfo.InvariantCulture)
};
discount.DiscountRules.Add(discountRequirement);
await _discountService.UpdateDiscount(discount);
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasAllProducts/ProductAddPopup.cshtml b/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasAllProducts/ProductAddPopup.cshtml
index cbcdab3ce..a071bb0f0 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasAllProducts/ProductAddPopup.cshtml
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasAllProducts/ProductAddPopup.cshtml
@@ -66,7 +66,6 @@
</div>
</div>
</div>
- <div id="products-grid"></div>
</div>
</div>
</div>
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasOneProduct/ProductAddPopup.cshtml b/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasOneProduct/ProductAddPopup.cshtml
index 0c7224dbd..906740f6e 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasOneProduct/ProductAddPopup.cshtml
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Views/HasOneProduct/ProductAddPopup.cshtml
@@ -66,7 +66,6 @@
</div>
</div>
</div>
- <div id="products-grid"></div>
</div>
</div>
</div>
diff --git a/src/Plugins/DiscountRules.Standard/DiscountPlugin.cs b/src/Plugins/DiscountRules.Standard/DiscountPlugin.cs
index f35561ba0..0a64108f2 100644
--- a/src/Plugins/DiscountRules.Standard/DiscountPlugin.cs
+++ b/src/Plugins/DiscountRules.Standard/DiscountPlugin.cs
@@ -4,7 +4,7 @@ using Grand.Infrastructure.Plugins;
namespace DiscountRules.Standard
{
- public partial class DiscountPlugin : BasePlugin, IPlugin
+ public class DiscountPlugin : BasePlugin, IPlugin
{
private readonly ITranslationService _translationService;
private readonly ILanguageService _languageService;
diff --git a/src/Plugins/DiscountRules.Standard/EndpointProvider.cs b/src/Plugins/DiscountRules.Standard/EndpointProvider.cs
index 9466c5058..fc2f558b0 100644
--- a/src/Plugins/DiscountRules.Standard/EndpointProvider.cs
+++ b/src/Plugins/DiscountRules.Standard/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace DiscountRules
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
@@ -56,12 +56,6 @@ namespace DiscountRules
new { controller = "HasOneProduct", action = "LoadProductFriendlyNames" }
);
}
- public int Priority
- {
- get
- {
- return 0;
- }
- }
+ public int Priority => 0;
}
}
diff --git a/src/Plugins/DiscountRules.Standard/Manifest.cs b/src/Plugins/DiscountRules.Standard/Manifest.cs
index 340cc1916..c3b9de4bf 100644
--- a/src/Plugins/DiscountRules.Standard/Manifest.cs
+++ b/src/Plugins/DiscountRules.Standard/Manifest.cs
@@ -7,5 +7,5 @@ using Grand.Infrastructure.Plugins;
SystemName = "DiscountRules.Standard",
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.02"
+ Version = "2.1.1"
)]
diff --git a/src/Plugins/DiscountRules.Standard/Models/RequirementCustomerGroup.cs b/src/Plugins/DiscountRules.Standard/Models/RequirementCustomerGroup.cs
deleted file mode 100644
index b42ec2069..000000000
--- a/src/Plugins/DiscountRules.Standard/Models/RequirementCustomerGroup.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace DiscountRules.Standard.Models
-{
- public class RequirementCustomerGroup
- {
- public string CustomerGroupId { get; set; }
- }
-}
diff --git a/src/Plugins/DiscountRules.Standard/Models/RequirementHadSpentAmount.cs b/src/Plugins/DiscountRules.Standard/Models/RequirementHadSpentAmount.cs
deleted file mode 100644
index f487fce65..000000000
--- a/src/Plugins/DiscountRules.Standard/Models/RequirementHadSpentAmount.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace DiscountRules.Standard.Models
-{
- public class RequirementHadSpentAmount
- {
- public double SpentAmount { get; set; }
- }
-}
diff --git a/src/Plugins/DiscountRules.Standard/Models/RequirementModel.cs b/src/Plugins/DiscountRules.Standard/Models/RequirementModel.cs
index b96193750..a345bf283 100644
--- a/src/Plugins/DiscountRules.Standard/Models/RequirementModel.cs
+++ b/src/Plugins/DiscountRules.Standard/Models/RequirementModel.cs
@@ -49,7 +49,7 @@ namespace DiscountRules.HasAllProducts.Models
#region Nested classes
- public partial class AddProductModel : BaseModel
+ public class AddProductModel : BaseModel
{
public AddProductModel()
{
@@ -82,7 +82,7 @@ namespace DiscountRules.HasAllProducts.Models
public bool IsLoggedInAsVendor { get; set; }
}
- public partial class ProductModel : BaseEntityModel
+ public class ProductModel : BaseEntityModel
{
public string Name { get; set; }
@@ -105,7 +105,7 @@ namespace DiscountRules.HasOneProduct.Models
#region Nested classes
- public partial class AddProductModel : BaseModel
+ public class AddProductModel : BaseModel
{
public AddProductModel()
{
@@ -137,7 +137,7 @@ namespace DiscountRules.HasOneProduct.Models
public bool IsLoggedInAsVendor { get; set; }
}
- public partial class ProductModel : BaseEntityModel
+ public class ProductModel : BaseEntityModel
{
public string Name { get; set; }
diff --git a/src/Plugins/DiscountRules.Standard/Models/RequirementProducts.cs b/src/Plugins/DiscountRules.Standard/Models/RequirementProducts.cs
deleted file mode 100644
index 87da2170b..000000000
--- a/src/Plugins/DiscountRules.Standard/Models/RequirementProducts.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace DiscountRules.Standard.Models
-{
- public class RequirementProducts
- {
- public RequirementProducts()
- {
- Products = new List<string>();
- }
- public IList<string> Products { get; set; }
- }
-}
diff --git a/src/Plugins/DiscountRules.Standard/Models/RequirementSpentAmount.cs b/src/Plugins/DiscountRules.Standard/Models/RequirementSpentAmount.cs
deleted file mode 100644
index ef8e87208..000000000
--- a/src/Plugins/DiscountRules.Standard/Models/RequirementSpentAmount.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace DiscountRules.Standard.Models
-{
- public class RequirementSpentAmount
- {
- public double SpentAmount { get; set; }
- }
-}
diff --git a/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs
index 1cccbaf12..a31d81ff6 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs
@@ -3,12 +3,8 @@ using Grand.Business.Core.Utilities.Catalog;
namespace DiscountRules.Provider
{
- public partial class CustomerGroupDiscountRule : IDiscountRule
+ public class CustomerGroupDiscountRule : IDiscountRule
{
- public CustomerGroupDiscountRule()
- {
- }
-
/// <summary>
/// Check discount requirement
/// </summary>
@@ -28,15 +24,11 @@ namespace DiscountRules.Provider
if (string.IsNullOrEmpty(request.DiscountRule.Metadata))
return result;
- foreach (var customerGroup in request.Customer.Groups.ToList())
- if (request.DiscountRule.Metadata == customerGroup)
- {
- //valid
- result.IsValid = true;
- return result;
- }
+ if (request.Customer.Groups.ToList().All(customerGroup => request.DiscountRule.Metadata != customerGroup))
+ return await Task.FromResult(result);
+ result.IsValid = true;
+ return result;
- return await Task.FromResult(result);
}
/// <summary>
@@ -48,9 +40,9 @@ namespace DiscountRules.Provider
public string GetConfigurationUrl(string discountId, string discountRequirementId)
{
//configured
- string result = "Admin/CustomerGroups/Configure/?discountId=" + discountId;
+ var result = "Admin/CustomerGroups/Configure/?discountId=" + discountId;
if (!string.IsNullOrEmpty(discountRequirementId))
- result += string.Format("&discountRequirementId={0}", discountRequirementId);
+ result += $"&discountRequirementId={discountRequirementId}";
return result;
}
diff --git a/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs
index 84a701292..79e6a4482 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs
@@ -6,7 +6,7 @@ using Grand.Domain.Orders;
namespace DiscountRules.Provider
{
- public partial class HadSpentAmountDiscountRule : IDiscountRule
+ public class HadSpentAmountDiscountRule : IDiscountRule
{
private readonly IOrderService _orderService;
private readonly ITranslationService _translationService;
@@ -30,30 +30,29 @@ namespace DiscountRules.Provider
//invalid by default
var result = new DiscountRuleValidationResult();
- if (double.TryParse(request.DiscountRule.Metadata, out var spentAmountRequirement))
+ if (!double.TryParse(request.DiscountRule.Metadata, out var spentAmountRequirement)) return result;
+
+ if (spentAmountRequirement == 0)
{
- if (spentAmountRequirement == 0)
- {
- //valid
- result.IsValid = true;
- return result;
- }
+ //valid
+ result.IsValid = true;
+ return result;
+ }
- if (request.Customer == null)
- return result;
+ if (request.Customer == null)
+ return result;
- var orders = await _orderService.SearchOrders(storeId: request.Store.Id,
- customerId: request.Customer.Id,
- os: (int)OrderStatusSystem.Complete);
- double spentAmount = orders.Sum(o => o.OrderTotal);
- if (spentAmount > spentAmountRequirement)
- {
- result.IsValid = true;
- }
- else
- {
- result.UserError = _translationService.GetResource("Plugins.DiscountRules.Standard.HadSpentAmount.NotEnough");
- }
+ var orders = await _orderService.SearchOrders(storeId: request.Store.Id,
+ customerId: request.Customer.Id,
+ os: (int)OrderStatusSystem.Complete);
+ var spentAmount = orders.Sum(o => o.OrderTotal);
+ if (spentAmount > spentAmountRequirement)
+ {
+ result.IsValid = true;
+ }
+ else
+ {
+ result.UserError = _translationService.GetResource("Plugins.DiscountRules.Standard.HadSpentAmount.NotEnough");
}
return result;
}
@@ -67,9 +66,9 @@ namespace DiscountRules.Provider
public string GetConfigurationUrl(string discountId, string discountRequirementId)
{
//configured
- string result = "Admin/HadSpentAmount/Configure/?discountId=" + discountId;
+ var result = "Admin/HadSpentAmount/Configure/?discountId=" + discountId;
if (!string.IsNullOrEmpty(discountRequirementId))
- result += string.Format("&discountRequirementId={0}", discountRequirementId);
+ result += $"&discountRequirementId={discountRequirementId}";
return result;
}
diff --git a/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs
index 6345009c3..bfcf58d5d 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs
@@ -4,7 +4,7 @@ using Grand.Domain.Orders;
namespace DiscountRules.Provider
{
- public partial class HasAllProductsDiscountRule : IDiscountRule
+ public class HasAllProductsDiscountRule : IDiscountRule
{
private readonly ShoppingCartSettings _shoppingCartSettings;
@@ -48,80 +48,65 @@ namespace DiscountRules.Provider
select new { ProductId = g.Key, TotalQuantity = g.Sum(x => x.Quantity) };
var cart = cartQuery.ToList();
- bool allFound = true;
+ var allFound = true;
foreach (var restrictedProduct in restrictedProductIds.Select(x => x.Trim()))
{
- if (String.IsNullOrWhiteSpace(restrictedProduct))
+ if (string.IsNullOrWhiteSpace(restrictedProduct))
continue;
- bool found1 = false;
+ var found1 = false;
foreach (var sci in cart)
{
- if (restrictedProduct.Contains(":"))
+ if (restrictedProduct.Contains(':'))
{
- if (restrictedProduct.Contains("-"))
+ if (restrictedProduct.Contains('-'))
{
//the third way (the quantity rage specified)
//{Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
- string restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
- int quantityMin;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[0], out quantityMin))
+ var restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[0], out var quantityMin))
//parsing error; exit;
return result;
- int quantityMax;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[1], out quantityMax))
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[1], out var quantityMax))
//parsing error; exit;
return result;
- if (sci.ProductId == restrictedProductId && quantityMin <= sci.TotalQuantity && sci.TotalQuantity <= quantityMax)
- {
- found1 = true;
- break;
- }
+ if (sci.ProductId != restrictedProductId || quantityMin > sci.TotalQuantity ||
+ sci.TotalQuantity > quantityMax) continue;
+ found1 = true;
+ break;
}
else
{
//the second way (the quantity specified)
//{Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
- string restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
- int quantity;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1], out quantity))
+ var restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1], out var quantity))
//parsing error; exit;
return result;
- if (sci.ProductId == restrictedProductId && sci.TotalQuantity == quantity)
- {
- found1 = true;
- break;
- }
- }
- }
- else
- {
- //the first way (the quantity is not specified)
- if (sci.ProductId == restrictedProduct)
- {
+ if (sci.ProductId != restrictedProductId || sci.TotalQuantity != quantity) continue;
found1 = true;
break;
}
}
- }
- if (!found1)
- {
- allFound = false;
+ //the first way (the quantity is not specified)
+ if (sci.ProductId != restrictedProduct) continue;
+ found1 = true;
break;
}
- }
- if (allFound)
- {
- //valid
- result.IsValid = true;
- return result;
+ if (found1) continue;
+ allFound = false;
+ break;
}
- return await Task.FromResult(result);
+ if (!allFound) return await Task.FromResult(result);
+ //valid
+ result.IsValid = true;
+ return result;
+
}
/// <summary>
@@ -133,9 +118,9 @@ namespace DiscountRules.Provider
public string GetConfigurationUrl(string discountId, string discountRequirementId)
{
//configured
- string result = "Admin/HasAllProducts/Configure/?discountId=" + discountId;
+ var result = "Admin/HasAllProducts/Configure/?discountId=" + discountId;
if (!string.IsNullOrEmpty(discountRequirementId))
- result += string.Format("&discountRequirementId={0}", discountRequirementId);
+ result += $"&discountRequirementId={discountRequirementId}";
return result;
}
diff --git a/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs
index e7f7ce393..b2eb41f15 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs
@@ -4,7 +4,7 @@ using Grand.Domain.Orders;
namespace DiscountRules.Provider
{
- public partial class HasOneProductDiscountRule : IDiscountRule
+ public class HasOneProductDiscountRule : IDiscountRule
{
private readonly ShoppingCartSettings _shoppingCartSettings;
@@ -48,7 +48,7 @@ namespace DiscountRules.Provider
var cart = cartQuery.ToList();
//process
- bool found = false;
+ var found = false;
foreach (var restrictedProduct in restrictedProductIds)
{
if (string.IsNullOrWhiteSpace(restrictedProduct))
@@ -62,50 +62,40 @@ namespace DiscountRules.Provider
{
//the third way (the quantity rage specified)
//{Product ID}:{Min quantity}-{Max quantity}. For example, 77:1-3, 123:2-5, 156:3-8
- string restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
+ var restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
- int quantityMin;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[0], out quantityMin))
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[0], out var quantityMin))
//parsing error; exit;
return result;
- int quantityMax;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[1], out quantityMax))
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1].Split(new[] { '-' })[1], out var quantityMax))
//parsing error; exit;
return result;
- if (sci.ProductId == restrictedProductId && quantityMin <= sci.TotalQuantity && sci.TotalQuantity <= quantityMax)
- {
- found = true;
- break;
- }
+ if (sci.ProductId != restrictedProductId || quantityMin > sci.TotalQuantity ||
+ sci.TotalQuantity > quantityMax) continue;
+ found = true;
+ break;
}
else
{
//the second way (the quantity specified)
//{Product ID}:{Quantity}. For example, 77:1, 123:2, 156:3
- string restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
+ var restrictedProductId = restrictedProduct.Split(new[] { ':' })[0];
- int quantity;
- if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1], out quantity))
+ if (!int.TryParse(restrictedProduct.Split(new[] { ':' })[1], out var quantity))
//parsing error; exit;
return result;
- if (sci.ProductId == restrictedProductId && sci.TotalQuantity == quantity)
- {
- found = true;
- break;
- }
- }
- }
- else
- {
- //the first way (the quantity is not specified)
- if (sci.ProductId == restrictedProduct)
- {
+ if (sci.ProductId != restrictedProductId || sci.TotalQuantity != quantity) continue;
found = true;
break;
}
}
+
+ //the first way (the quantity is not specified)
+ if (sci.ProductId != restrictedProduct) continue;
+ found = true;
+ break;
}
if (found)
@@ -114,14 +104,11 @@ namespace DiscountRules.Provider
}
}
- if (found)
- {
- //valid
- result.IsValid = true;
- return result;
- }
+ if (!found) return await Task.FromResult(result);
+ //valid
+ result.IsValid = true;
+ return result;
- return await Task.FromResult(result);
}
/// <summary>
@@ -133,9 +120,9 @@ namespace DiscountRules.Provider
public string GetConfigurationUrl(string discountId, string discountRequirementId)
{
//configured
- string result = "Admin/HasOneProduct/Configure/?discountId=" + discountId;
+ var result = "Admin/HasOneProduct/Configure/?discountId=" + discountId;
if (!string.IsNullOrEmpty(discountRequirementId))
- result += string.Format("&discountRequirementId={0}", discountRequirementId);
+ result += $"&discountRequirementId={discountRequirementId}";
return result;
}
diff --git a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
index 31ce2e72b..749f50133 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
@@ -8,7 +8,7 @@ using Microsoft.Extensions.DependencyInjection;
namespace DiscountRules.Provider
{
- public partial class ShoppingCartDiscountRule : IDiscountRule
+ public class ShoppingCartDiscountRule : IDiscountRule
{
private readonly IWorkContext _workContext;
private readonly IProductService _productService;
@@ -39,38 +39,36 @@ namespace DiscountRules.Provider
var result = new DiscountRuleValidationResult();
- if (double.TryParse(request.DiscountRule.Metadata, out var spentAmountRequirement))
+ if (!double.TryParse(request.DiscountRule.Metadata, out var spentAmountRequirement)) return result;
+
+ if (spentAmountRequirement == 0)
{
- if (spentAmountRequirement == 0)
- {
- result.IsValid = true;
- return result;
- }
-
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
- .Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, request.Store.Id)
- .ToList();
+ result.IsValid = true;
+ return result;
+ }
- if (cart.Count == 0)
- {
- result.IsValid = false;
- return result;
- }
- double spentAmount = 0;
+ var cart = _workContext.CurrentCustomer.ShoppingCartItems
+ .Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, request.Store.Id)
+ .ToList();
- var priceCalculationService = _serviceProvider.GetRequiredService<IPricingService>();
+ if (cart.Count == 0)
+ {
+ result.IsValid = false;
+ return result;
+ }
+ double spentAmount = 0;
- foreach (var ca in cart)
- {
- bool calculateWithDiscount = false;
- var product = await _productService.GetProductById(ca.ProductId);
- if (product != null)
- spentAmount += (await priceCalculationService.GetSubTotal(ca, product, calculateWithDiscount)).subTotal;
- }
+ var priceCalculationService = _serviceProvider.GetRequiredService<IPricingService>();
- result.IsValid = spentAmount > spentAmountRequirement;
+ foreach (var ca in cart)
+ {
+ var product = await _productService.GetProductById(ca.ProductId);
+ if (product != null)
+ spentAmount += (await priceCalculationService.GetSubTotal(ca, product, false)).subTotal;
}
+
+ result.IsValid = spentAmount > spentAmountRequirement;
return result;
}
@@ -83,9 +81,9 @@ namespace DiscountRules.Provider
public string GetConfigurationUrl(string discountId, string discountRequirementId)
{
//configured
- string result = "Admin/ShoppingCartAmount/Configure/?discountId=" + discountId;
+ var result = "Admin/ShoppingCartAmount/Configure/?discountId=" + discountId;
if (!string.IsNullOrEmpty(discountRequirementId))
- result += string.Format("&discountRequirementId={0}", discountRequirementId);
+ result += $"&discountRequirementId={discountRequirementId}";
return result;
}
public string FriendlyName => "SubTotal in Shopping Cart x.xx ";
diff --git a/src/Plugins/ExchangeRate.McExchange/EcbExchange.cs b/src/Plugins/ExchangeRate.McExchange/EcbExchange.cs
index 5fc2d2f7c..00964491b 100644
--- a/src/Plugins/ExchangeRate.McExchange/EcbExchange.cs
+++ b/src/Plugins/ExchangeRate.McExchange/EcbExchange.cs
@@ -16,19 +16,20 @@ namespace ExchangeRate.McExchange
public async Task<IList<Grand.Domain.Directory.ExchangeRate>> GetCurrencyLiveRates()
{
var httpClient = _httpClientFactory.CreateClient(Constant.DefaultHttpClientName);
- using var response = await httpClient.GetStreamAsync(Constant.EcbUrl);
+ await using var response = await httpClient.GetStreamAsync(Constant.EcbUrl);
var document = new XmlDocument();
document.Load(response);
- var nsmgr = new XmlNamespaceManager(document.NameTable);
- nsmgr.AddNamespace("ns", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
- nsmgr.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
+ var nameTable = new XmlNamespaceManager(document.NameTable);
+ nameTable.AddNamespace("ns", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
+ nameTable.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
- var node = document.SelectSingleNode("gesmes:Envelope/ns:Cube/ns:Cube", nsmgr);
+ var node = document.SelectSingleNode("gesmes:Envelope/ns:Cube/ns:Cube", nameTable);
var updateDate = DateTime.ParseExact(node.Attributes["time"].Value, "yyyy-MM-dd", null);
- var provider = new NumberFormatInfo();
- provider.NumberDecimalSeparator = ".";
- provider.NumberGroupSeparator = "";
+ var provider = new NumberFormatInfo {
+ NumberDecimalSeparator = ".",
+ NumberGroupSeparator = ""
+ };
var exchangeRates = new List<Grand.Domain.Directory.ExchangeRate>();
foreach (XmlNode node2 in node.ChildNodes)
diff --git a/src/Plugins/ExchangeRate.McExchange/Manifest.cs b/src/Plugins/ExchangeRate.McExchange/Manifest.cs
index 5bae7c39f..f7fa51dc7 100644
--- a/src/Plugins/ExchangeRate.McExchange/Manifest.cs
+++ b/src/Plugins/ExchangeRate.McExchange/Manifest.cs
@@ -7,5 +7,5 @@ using Grand.Infrastructure.Plugins;
SystemName = "CurrencyExchange.MoneyConverter",
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/ExchangeRate.McExchange/McExchangeRatePlugin.cs b/src/Plugins/ExchangeRate.McExchange/McExchangeRatePlugin.cs
index 4d6c6811d..404e3d9b6 100644
--- a/src/Plugins/ExchangeRate.McExchange/McExchangeRatePlugin.cs
+++ b/src/Plugins/ExchangeRate.McExchange/McExchangeRatePlugin.cs
@@ -7,20 +7,5 @@ namespace ExchangeRate.McExchange
{
public class McExchangeRatePlugin : BasePlugin
{
- public McExchangeRatePlugin()
- {
- }
-
- public override async Task Install()
- {
- //locales
- await base.Install();
- }
-
- public override async Task Uninstall()
- {
- //locales
- await base.Uninstall();
- }
}
}
diff --git a/src/Plugins/ExchangeRate.McExchange/NbpExchange.cs b/src/Plugins/ExchangeRate.McExchange/NbpExchange.cs
index e2543a0bf..8d8787d15 100644
--- a/src/Plugins/ExchangeRate.McExchange/NbpExchange.cs
+++ b/src/Plugins/ExchangeRate.McExchange/NbpExchange.cs
@@ -1,3 +1,4 @@
+using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Net.Mime;
@@ -18,7 +19,7 @@ namespace ExchangeRate.McExchange
var currentDate = DateTime.Today.AddDays(-1);
var httpClient = _httpClientFactory.CreateClient(Constant.DefaultHttpClientName);
httpClient.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Xml);
- using var response = await httpClient.GetStreamAsync($"{Constant.NbpUrl}{currentDate.AddDays(-7):yyyy-MM-dd}/{currentDate:yyyy-MM-dd}");
+ await using var response = await httpClient.GetStreamAsync($"{Constant.NbpUrl}{currentDate.AddDays(-7):yyyy-MM-dd}/{currentDate:yyyy-MM-dd}");
var document = new XmlDocument();
document.Load(response);
@@ -28,11 +29,13 @@ namespace ExchangeRate.McExchange
.First();
var updateDate = DateTime.ParseExact(node.InnerText, "yyyy-MM-dd", null);
+ Debug.Assert(node.ParentNode != null, "node.ParentNode != null");
var ratesNode = node.ParentNode.SelectSingleNode("Rates");
- var provider = new NumberFormatInfo();
- provider.CurrencyDecimalSeparator = ".";
- provider.NumberGroupSeparator = "";
+ var provider = new NumberFormatInfo {
+ CurrencyDecimalSeparator = ".",
+ NumberGroupSeparator = ""
+ };
var exchangeRates = new List<Grand.Domain.Directory.ExchangeRate>();
foreach (XmlNode node2 in ratesNode.ChildNodes)
diff --git a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
index 4092f953a..393783cca 100644
--- a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
+++ b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
@@ -81,23 +81,23 @@ namespace Payments.BrainTree
public async Task<PaymentTransaction> SavePaymentInfo(IDictionary<string, string> model)
{
if (model.TryGetValue("CardNonce", out var cardNonce) && !StringValues.IsNullOrEmpty(cardNonce))
- _httpContextAccessor.HttpContext!.Session.SetString("CardNonce", cardNonce.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("CardNonce", cardNonce);
if (model.TryGetValue("CardholderName", out var cardholderName) &&
!StringValues.IsNullOrEmpty(cardholderName))
- _httpContextAccessor.HttpContext!.Session.SetString("CardholderName", cardholderName.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("CardholderName", cardholderName);
if (model.TryGetValue("CardNumber", out var cardNumber) && !StringValues.IsNullOrEmpty(cardNumber))
- _httpContextAccessor.HttpContext!.Session.SetString("CardNumber", cardNumber.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("CardNumber", cardNumber);
if (model.TryGetValue("ExpireMonth", out var expireMonth) && !StringValues.IsNullOrEmpty(expireMonth))
- _httpContextAccessor.HttpContext!.Session.SetString("ExpireMonth", expireMonth.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("ExpireMonth", expireMonth);
if (model.TryGetValue("ExpireYear", out var expireYear) && !StringValues.IsNullOrEmpty(expireYear))
- _httpContextAccessor.HttpContext!.Session.SetString("ExpireYear", expireYear.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("ExpireYear", expireYear);
if (model.TryGetValue("CardCode", out var creditCardCvv2) && !StringValues.IsNullOrEmpty(creditCardCvv2))
- _httpContextAccessor.HttpContext!.Session.SetString("CardCode", creditCardCvv2.ToString());
+ _httpContextAccessor.HttpContext!.Session.SetString("CardCode", creditCardCvv2);
return await Task.FromResult<PaymentTransaction>(null);
}
@@ -129,7 +129,7 @@ namespace Payments.BrainTree
//new transaction request
var transactionRequest = new TransactionRequest {
- Amount = Convert.ToDecimal(paymentTransaction.TransactionAmount),
+ Amount = Convert.ToDecimal(paymentTransaction.TransactionAmount)
};
if (_brainTreePaymentSettings.Use3DS)
@@ -203,7 +203,7 @@ namespace Payments.BrainTree
/// <summary>
/// Returns a value indicating whether payment method should be hidden during checkout
/// </summary>
- /// <param name="cart">Shoping cart</param>
+ /// <param name="cart">Shopping cart</param>
/// <returns>true - hide; false - display.</returns>
public async Task<bool> HidePaymentMethod(IList<ShoppingCartItem> cart)
{
@@ -217,7 +217,7 @@ namespace Payments.BrainTree
/// <summary>
/// Gets additional handling fee
/// </summary>
- /// <param name="cart">Shoping cart</param>
+ /// <param name="cart">Shopping cart</param>
/// <returns>Additional handling fee</returns>
public async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
@@ -230,8 +230,8 @@ namespace Payments.BrainTree
//percentage
var orderTotalCalculationService = _serviceProvider.GetRequiredService<IOrderCalculationService>();
var subtotal = await orderTotalCalculationService.GetShoppingCartSubTotal(cart, true);
- result = (double)((((float)subtotal.subTotalWithDiscount) *
- ((float)_brainTreePaymentSettings.AdditionalFee)) / 100f);
+ result = (float)subtotal.subTotalWithDiscount *
+ (float)_brainTreePaymentSettings.AdditionalFee / 100f;
}
else
{
@@ -239,12 +239,10 @@ namespace Payments.BrainTree
result = _brainTreePaymentSettings.AdditionalFee;
}
- if (result > 0)
- {
- var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
- var workContext = _serviceProvider.GetRequiredService<IWorkContext>();
- result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
- }
+ if (!(result > 0)) return await Task.FromResult(result);
+ var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
+ var workContext = _serviceProvider.GetRequiredService<IWorkContext>();
+ result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
//return result;
return await Task.FromResult(result);
@@ -343,11 +341,7 @@ namespace Payments.BrainTree
/// <summary>
/// Gets a payment method type
/// </summary>
- public PaymentMethodType PaymentMethodType {
- get {
- return PaymentMethodType.Standard;
- }
- }
+ public PaymentMethodType PaymentMethodType => PaymentMethodType.Standard;
public string ConfigurationUrl => BrainTreeDefaults.ConfigurationUrl;
diff --git a/src/Plugins/Payments.BrainTree/BrainTreeWidgetProvider.cs b/src/Plugins/Payments.BrainTree/BrainTreeWidgetProvider.cs
index 612cda578..10d0cbafd 100644
--- a/src/Plugins/Payments.BrainTree/BrainTreeWidgetProvider.cs
+++ b/src/Plugins/Payments.BrainTree/BrainTreeWidgetProvider.cs
@@ -28,7 +28,7 @@ namespace Payments.BrainTree
public async Task<IList<string>> GetWidgetZones()
{
- return await Task.FromResult(new string[] { "checkout_payment_info_top" });
+ return await Task.FromResult(new[] { "checkout_payment_info_top" });
}
public Task<string> GetPublicViewComponentName(string widgetZone)
diff --git a/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs b/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
index 3f7c5ab9e..7dbce19ff 100644
--- a/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
+++ b/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
@@ -57,7 +57,7 @@ namespace Payments.BrainTree.Controllers
PrivateKey = privateKey
};
- ViewBag.ClientToken = gateway.ClientToken.Generate();
+ ViewBag.ClientToken = await gateway.ClientToken.GenerateAsync();
ViewBag.OrderTotal = (await _orderTotalCalculationService.GetShoppingCartTotal(cart)).shoppingCartTotal;
return View("PaymentInfo_3DS", model);
@@ -69,7 +69,7 @@ namespace Payments.BrainTree.Controllers
var year = Convert.ToString(DateTime.Now.Year + i);
model.ExpireYears.Add(new SelectListItem {
Text = year,
- Value = year,
+ Value = year
});
}
@@ -79,7 +79,7 @@ namespace Payments.BrainTree.Controllers
var text = i < 10 ? "0" + i : i.ToString();
model.ExpireMonths.Add(new SelectListItem {
Text = text,
- Value = i.ToString(),
+ Value = i.ToString()
});
}
@@ -103,13 +103,11 @@ namespace Payments.BrainTree.Controllers
selectedYear.Selected = true;
var validator = new PaymentInfoValidator(_brainTreePaymentSettings, _translationService);
- var results = validator.Validate(model);
- if (!results.IsValid)
- {
- var query = from error in results.Errors
- select error.ErrorMessage;
- model.Errors = string.Join(", ", query);
- }
+ var results = await validator.ValidateAsync(model);
+ if (results.IsValid) return View("PaymentInfo", model);
+ var query = from error in results.Errors
+ select error.ErrorMessage;
+ model.Errors = string.Join(", ", query);
return View("PaymentInfo", model);
}
}
diff --git a/src/Plugins/Payments.BrainTree/EndpointProvider.cs b/src/Plugins/Payments.BrainTree/EndpointProvider.cs
index 9da4d3db7..b7e67a18b 100644
--- a/src/Plugins/Payments.BrainTree/EndpointProvider.cs
+++ b/src/Plugins/Payments.BrainTree/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Payments.BrainTree
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
diff --git a/src/Plugins/Payments.BrainTree/Manifest.cs b/src/Plugins/Payments.BrainTree/Manifest.cs
index 686cf9bf3..fb84cc94f 100644
--- a/src/Plugins/Payments.BrainTree/Manifest.cs
+++ b/src/Plugins/Payments.BrainTree/Manifest.cs
@@ -8,5 +8,5 @@ using Payments.BrainTree;
SystemName = BrainTreeDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs b/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
index 9d9b7aac3..8c3b8a1aa 100644
--- a/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
+++ b/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
@@ -60,7 +60,7 @@ namespace Payments.CashOnDelivery.Areas.Admin.Controllers
AdditionalFeePercentage = cashOnDeliveryPaymentSettings.AdditionalFeePercentage,
ShippableProductRequired = cashOnDeliveryPaymentSettings.ShippableProductRequired,
DisplayOrder = cashOnDeliveryPaymentSettings.DisplayOrder,
- SkipPaymentInfo = cashOnDeliveryPaymentSettings.SkipPaymentInfo,
+ SkipPaymentInfo = cashOnDeliveryPaymentSettings.SkipPaymentInfo
};
model.DescriptionText = cashOnDeliveryPaymentSettings.DescriptionText;
diff --git a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
index 24c0d4b29..6e6cd43c6 100644
--- a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
+++ b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
@@ -7,7 +7,6 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Infrastructure;
-using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Payments.CashOnDelivery
@@ -52,8 +51,9 @@ namespace Payments.CashOnDelivery
}
public async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)
{
- var result = new ProcessPaymentResult();
- result.NewPaymentTransactionStatus = TransactionStatus.Pending;
+ var result = new ProcessPaymentResult {
+ NewPaymentTransactionStatus = TransactionStatus.Pending
+ };
return await Task.FromResult(result);
}
@@ -90,7 +90,7 @@ namespace Payments.CashOnDelivery
//percentage
var orderTotalCalculationService = _serviceProvider.GetRequiredService<IOrderCalculationService>();
var subtotal = await orderTotalCalculationService.GetShoppingCartSubTotal(cart, true);
- result = (double)((((float)subtotal.subTotalWithDiscount) * ((float)_cashOnDeliveryPaymentSettings.AdditionalFee)) / 100f);
+ result = (float)subtotal.subTotalWithDiscount * (float)_cashOnDeliveryPaymentSettings.AdditionalFee / 100f;
}
else
{
@@ -98,12 +98,10 @@ namespace Payments.CashOnDelivery
result = _cashOnDeliveryPaymentSettings.AdditionalFee;
}
- if (result > 0)
- {
- var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
- var workContext = _serviceProvider.GetRequiredService<IWorkContext>();
- result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
- }
+ if (!(result > 0)) return result;
+ var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
+ var workContext = _serviceProvider.GetRequiredService<IWorkContext>();
+ result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
//return result;
return result;
diff --git a/src/Plugins/Payments.CashOnDelivery/EndpointProvider.cs b/src/Plugins/Payments.CashOnDelivery/EndpointProvider.cs
index e7968d4e1..bda0bb361 100644
--- a/src/Plugins/Payments.CashOnDelivery/EndpointProvider.cs
+++ b/src/Plugins/Payments.CashOnDelivery/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Payments.CashOnDelivery
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
diff --git a/src/Plugins/Payments.CashOnDelivery/Manifest.cs b/src/Plugins/Payments.CashOnDelivery/Manifest.cs
index 4183604b0..88762f4fa 100644
--- a/src/Plugins/Payments.CashOnDelivery/Manifest.cs
+++ b/src/Plugins/Payments.CashOnDelivery/Manifest.cs
@@ -8,5 +8,5 @@ using Payments.CashOnDelivery;
SystemName = CashOnDeliveryPaymentDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Payments.CashOnDelivery/Models/ConfigurationModel.cs b/src/Plugins/Payments.CashOnDelivery/Models/ConfigurationModel.cs
index 85f3c92b0..261ef1385 100644
--- a/src/Plugins/Payments.CashOnDelivery/Models/ConfigurationModel.cs
+++ b/src/Plugins/Payments.CashOnDelivery/Models/ConfigurationModel.cs
@@ -35,7 +35,7 @@ namespace Payments.CashOnDelivery.Models
#region Nested class
- public partial class ConfigurationLocalizedModel : ILocalizedModelLocal
+ public class ConfigurationLocalizedModel : ILocalizedModelLocal
{
public string LanguageId { get; set; }
diff --git a/src/Plugins/Payments.CashOnDelivery/Views/PaymentCashOnDelivery/PaymentInfo.cshtml b/src/Plugins/Payments.CashOnDelivery/Views/PaymentCashOnDelivery/PaymentInfo.cshtml
index da5723413..738ce4a19 100644
--- a/src/Plugins/Payments.CashOnDelivery/Views/PaymentCashOnDelivery/PaymentInfo.cshtml
+++ b/src/Plugins/Payments.CashOnDelivery/Views/PaymentCashOnDelivery/PaymentInfo.cshtml
@@ -2,10 +2,6 @@
Layout = "";
}
@model Payments.CashOnDelivery.Models.PaymentInfoModel
-<table width="100%" cellpadding="0" cellspacing="0">
- <tr>
- <td>
- @Html.Raw(Model.DescriptionText)
- </td>
- </tr>
-</table>
+<div>
+ @Html.Raw(Model.DescriptionText)
+</div>
diff --git a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs
index e881331eb..0382219b4 100644
--- a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs
+++ b/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs
@@ -38,14 +38,14 @@ namespace Payments.PayPalStandard.Areas.Admin.Controllers
_permissionService = permissionService;
}
- protected virtual async Task<string> GetActiveStore(IStoreService storeService, IWorkContext workContext)
+ private async Task<string> GetActiveStore()
{
- var stores = await storeService.GetAllStores();
+ var stores = await _storeService.GetAllStores();
if (stores.Count < 2)
- return stores.FirstOrDefault().Id;
+ return stores.FirstOrDefault()?.Id;
- var storeId = workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);
- var store = await storeService.GetStoreById(storeId);
+ var storeId = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);
+ var store = await _storeService.GetStoreById(storeId);
return store != null ? store.Id : "";
}
@@ -56,20 +56,20 @@ namespace Payments.PayPalStandard.Areas.Admin.Controllers
return AccessDeniedView();
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore();
var payPalStandardPaymentSettings = _settingService.LoadSetting<PayPalStandardPaymentSettings>(storeScope);
- var model = new ConfigurationModel();
- model.UseSandbox = payPalStandardPaymentSettings.UseSandbox;
- model.BusinessEmail = payPalStandardPaymentSettings.BusinessEmail;
- model.PdtToken = payPalStandardPaymentSettings.PdtToken;
- model.PdtValidateOrderTotal = payPalStandardPaymentSettings.PdtValidateOrderTotal;
- model.AdditionalFee = payPalStandardPaymentSettings.AdditionalFee;
- model.AdditionalFeePercentage = payPalStandardPaymentSettings.AdditionalFeePercentage;
- model.PassProductNamesAndTotals = payPalStandardPaymentSettings.PassProductNamesAndTotals;
- model.DisplayOrder = payPalStandardPaymentSettings.DisplayOrder;
-
- model.StoreScope = storeScope;
+ var model = new ConfigurationModel {
+ UseSandbox = payPalStandardPaymentSettings.UseSandbox,
+ BusinessEmail = payPalStandardPaymentSettings.BusinessEmail,
+ PdtToken = payPalStandardPaymentSettings.PdtToken,
+ PdtValidateOrderTotal = payPalStandardPaymentSettings.PdtValidateOrderTotal,
+ AdditionalFee = payPalStandardPaymentSettings.AdditionalFee,
+ AdditionalFeePercentage = payPalStandardPaymentSettings.AdditionalFeePercentage,
+ PassProductNamesAndTotals = payPalStandardPaymentSettings.PassProductNamesAndTotals,
+ DisplayOrder = payPalStandardPaymentSettings.DisplayOrder,
+ StoreScope = storeScope
+ };
return View(model);
}
@@ -84,7 +84,7 @@ namespace Payments.PayPalStandard.Areas.Admin.Controllers
return await Configure();
//load settings for a chosen store scope
- var storeScope = await this.GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore();
var payPalStandardPaymentSettings = _settingService.LoadSetting<PayPalStandardPaymentSettings>(storeScope);
//save settings
diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
index 345b4d7d6..83f897de3 100644
--- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
+++ b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
@@ -10,7 +10,6 @@ using Grand.Infrastructure;
using Grand.SharedKernel;
using Grand.Web.Common.Controllers;
using MediatR;
-using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Payments.PayPalStandard.Services;
@@ -57,10 +56,7 @@ namespace Payments.PayPalStandard.Controllers
private string QueryString(string name)
{
- if (StringValues.IsNullOrEmpty(HttpContext.Request.Query[name]))
- return default;
-
- return HttpContext.Request.Query[name].ToString();
+ return StringValues.IsNullOrEmpty(HttpContext.Request.Query[name]) ? default : HttpContext.Request.Query[name].ToString();
}
public async Task<IActionResult> PDTHandler()
@@ -71,7 +67,7 @@ namespace Payments.PayPalStandard.Controllers
!processor.IsPaymentMethodActive(_paymentSettings))
throw new GrandException("PayPal Standard module cannot be loaded");
- (var status, var values, var _) = await _paypalHttpClient.GetPdtDetails(tx);
+ var (status, values, _) = await _paypalHttpClient.GetPdtDetails(tx);
if (status)
{
@@ -79,9 +75,13 @@ namespace Payments.PayPalStandard.Controllers
Guid orderNumberGuid = Guid.Empty;
try
{
- orderNumberGuid = new Guid(orderNumber);
+ if (orderNumber != null) orderNumberGuid = new Guid(orderNumber);
+ }
+ catch
+ {
+ // ignored
}
- catch { }
+
Order order = await _orderService.GetOrderByGuid(orderNumberGuid);
if (order != null)
{
@@ -130,14 +130,15 @@ namespace Payments.PayPalStandard.Controllers
Note = sb.ToString(),
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow,
- OrderId = order.Id,
+ OrderId = order.Id
});
//load settings for a chosen store scope
//validate order total
if (_payPalStandardPaymentSettings.PdtValidateOrderTotal && !Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal * order.CurrencyRate, 2)))
{
- string errorStr = string.Format("PayPal PDT. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.OrderNumber);
+ var errorStr =
+ $"PayPal PDT. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.OrderNumber}.";
_ = _logger.Error(errorStr);
//order note
@@ -154,11 +155,11 @@ namespace Payments.PayPalStandard.Controllers
//mark order as paid
if (newPaymentStatus == PaymentStatus.Paid)
{
- if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery() { PaymentTransaction = paymentTransaction }))
+ if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }))
{
paymentTransaction.AuthorizationTransactionId = txn_id;
await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);
- await _mediator.Send(new MarkAsPaidCommand() { PaymentTransaction = paymentTransaction });
+ await _mediator.Send(new MarkAsPaidCommand { PaymentTransaction = paymentTransaction });
}
}
}
@@ -173,21 +174,25 @@ namespace Payments.PayPalStandard.Controllers
{
orderNumberGuid = new Guid(custom);
}
- catch { }
+ catch
+ {
+ // ignored
+ }
+
Order order = await _orderService.GetOrderByGuid(orderNumberGuid);
if (order != null)
{
return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
}
- else
- return RedirectToAction("Index", "Home", new { area = "" });
+
+ return RedirectToAction("Index", "Home", new { area = "" });
}
}
[HttpPost]
- public async Task<IActionResult> IPNHandler()
+ public async Task<IActionResult> IpnHandler()
{
- string strRequest = string.Empty;
+ string strRequest;
using (var stream = new StreamReader(Request.Body))
{
strRequest = await stream.ReadToEndAsync();
@@ -201,25 +206,20 @@ namespace Payments.PayPalStandard.Controllers
if (success)
{
#region values
- double mc_gross = 0;
+ double mcGross = 0;
try
{
- mc_gross = double.Parse(values["mc_gross"], new CultureInfo("en-US"));
+ mcGross = double.Parse(values["mc_gross"], new CultureInfo("en-US"));
+ }
+ catch
+ {
+ // ignored
}
- catch { }
-
- values.TryGetValue("payer_status", out var payer_status);
- values.TryGetValue("payment_status", out var payment_status);
- values.TryGetValue("pending_reason", out var pending_reason);
- values.TryGetValue("mc_currency", out var mc_currency);
- values.TryGetValue("txn_id", out var txn_id);
- values.TryGetValue("txn_type", out var txn_type);
- values.TryGetValue("rp_invoice_id", out var rp_invoice_id);
- values.TryGetValue("payment_type", out var payment_type);
- values.TryGetValue("payer_id", out var payer_id);
- values.TryGetValue("receiver_id", out var receiver_id);
- values.TryGetValue("invoice", out var invoice);
- values.TryGetValue("payment_fee", out var payment_fee);
+
+ values.TryGetValue("payment_status", out var paymentStatus);
+ values.TryGetValue("pending_reason", out var pendingReason);
+ values.TryGetValue("txn_id", value: out var txnId);
+ values.TryGetValue("txn_type", out var txnType);
#endregion
@@ -230,10 +230,10 @@ namespace Payments.PayPalStandard.Controllers
sb.AppendLine(kvp.Key + ": " + kvp.Value);
}
- var newPaymentStatus = PaypalHelper.GetPaymentStatus(payment_status, pending_reason);
+ var newPaymentStatus = PaypalHelper.GetPaymentStatus(paymentStatus, pendingReason);
sb.AppendLine("New payment status: " + newPaymentStatus);
- switch (txn_type)
+ switch (txnType)
{
case "recurring_payment_profile_created":
//do nothing here
@@ -244,18 +244,18 @@ namespace Payments.PayPalStandard.Controllers
default:
#region Standard payment
{
- string orderNumber = string.Empty;
- values.TryGetValue("custom", out orderNumber);
+ values.TryGetValue("custom", out var orderNumber);
Guid orderNumberGuid = Guid.Empty;
try
{
- orderNumberGuid = new Guid(orderNumber);
+ if (orderNumber != null) orderNumberGuid = Guid.Parse(orderNumber);
}
catch
{
+ // ignored
}
- var order = await _orderService.GetOrderByGuid(orderNumberGuid);
+ var order = orderNumberGuid != Guid.Empty ? await _orderService.GetOrderByGuid(orderNumberGuid) : null;
if (order != null)
{
//order note
@@ -263,31 +263,28 @@ namespace Payments.PayPalStandard.Controllers
Note = sb.ToString(),
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow,
- OrderId = order.Id,
+ OrderId = order.Id
});
var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);
switch (newPaymentStatus)
{
- case PaymentStatus.Pending:
- {
- }
- break;
case PaymentStatus.Authorized:
{
//validate order total
- if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
+ if (Math.Round(mcGross, 2).Equals(Math.Round(order.OrderTotal, 2)))
{
//valid
- if (await _mediator.Send(new CanMarkPaymentTransactionAsAuthorizedQuery() { PaymentTransaction = paymentTransaction }))
+ if (await _mediator.Send(new CanMarkPaymentTransactionAsAuthorizedQuery { PaymentTransaction = paymentTransaction }))
{
- await _mediator.Send(new MarkAsAuthorizedCommand() { PaymentTransaction = paymentTransaction });
+ await _mediator.Send(new MarkAsAuthorizedCommand { PaymentTransaction = paymentTransaction });
}
}
else
{
//not valid
- string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.Id);
+ var errorStr =
+ $"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";
//log
_ = _logger.Error(errorStr);
//order note
@@ -295,7 +292,7 @@ namespace Payments.PayPalStandard.Controllers
Note = errorStr,
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow,
- OrderId = order.Id,
+ OrderId = order.Id
});
}
}
@@ -303,21 +300,22 @@ namespace Payments.PayPalStandard.Controllers
case PaymentStatus.Paid:
{
//validate order total
- if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
+ if (Math.Round(mcGross, 2).Equals(Math.Round(order.OrderTotal, 2)))
{
//valid
- if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery() { PaymentTransaction = paymentTransaction }))
+ if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }))
{
- paymentTransaction.AuthorizationTransactionId = txn_id;
+ paymentTransaction.AuthorizationTransactionId = txnId;
await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);
- await _mediator.Send(new MarkAsPaidCommand() { PaymentTransaction = paymentTransaction });
+ await _mediator.Send(new MarkAsPaidCommand { PaymentTransaction = paymentTransaction });
}
}
else
{
//not valid
- string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.Id);
+ var errorStr =
+ $"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";
//log
_ = _logger.Error(errorStr);
//order note
@@ -325,42 +323,50 @@ namespace Payments.PayPalStandard.Controllers
Note = errorStr,
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow,
- OrderId = order.Id,
+ OrderId = order.Id
});
}
}
break;
case PaymentStatus.Refunded:
{
- var totalToRefund = Math.Abs(mc_gross);
+ var totalToRefund = Math.Abs(mcGross);
if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))
{
//refund
- if (await _mediator.Send(new CanRefundOfflineQuery() { PaymentTransaction = paymentTransaction }))
+ if (await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction }))
{
- await _mediator.Send(new RefundOfflineCommand() { PaymentTransaction = paymentTransaction });
+ await _mediator.Send(new RefundOfflineCommand { PaymentTransaction = paymentTransaction });
}
}
else
{
//partial refund
- if (await _mediator.Send(new CanPartiallyRefundOfflineQuery() { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund }))
+ if (await _mediator.Send(new CanPartiallyRefundOfflineQuery { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund }))
{
- await _mediator.Send(new PartiallyRefundOfflineCommand() { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund });
+ await _mediator.Send(new PartiallyRefundOfflineCommand { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund });
}
}
}
break;
case PaymentStatus.Voided:
{
- if (await _mediator.Send(new CanVoidOfflineQuery() { PaymentTransaction = paymentTransaction }))
+ if (await _mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction }))
{
- await _mediator.Send(new VoidOfflineCommand() { PaymentTransaction = paymentTransaction });
+ await _mediator.Send(new VoidOfflineCommand { PaymentTransaction = paymentTransaction });
}
}
break;
- default:
+ case PaymentStatus.Pending:
+ break;
+ case PaymentStatus.PartiallyPaid:
+ break;
+ case PaymentStatus.PartiallyRefunded:
+ break;
+ case PaymentStatus.PendingRefunded:
break;
+ default:
+ throw new ArgumentOutOfRangeException();
}
}
else
@@ -374,10 +380,8 @@ namespace Payments.PayPalStandard.Controllers
return Ok();
}
- else
- {
- _ = _logger.Error("PayPal IPN failed.", new GrandException(strRequest));
- }
+
+ _ = _logger.Error("PayPal IPN failed.", new GrandException(strRequest));
return BadRequest();
@@ -387,10 +391,7 @@ namespace Payments.PayPalStandard.Controllers
{
var order = (await _orderService.SearchOrders(storeId: _workContext.CurrentStore.Id,
customerId: _workContext.CurrentCustomer.Id, pageSize: 1)).FirstOrDefault();
- if (order != null)
- return RedirectToRoute("OrderDetails", new { orderId = order.Id });
-
- return RedirectToRoute("HomePage");
+ return order != null ? RedirectToRoute("OrderDetails", new { orderId = order.Id }) : RedirectToRoute("HomePage");
}
public IActionResult PaymentInfo()
diff --git a/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs b/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs
index bbc0cb5a8..a9fd8db19 100644
--- a/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs
+++ b/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Payments.PayPalStandard
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
@@ -22,7 +22,7 @@ namespace Payments.PayPalStandard
//IPN
endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.IPNHandler",
"Plugins/PaymentPayPalStandard/IPNHandler",
- new { controller = "PaymentPayPalStandard", action = "IPNHandler" }
+ new { controller = "PaymentPayPalStandard", action = "IpnHandler" }
);
//Cancel
endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.CancelOrder",
diff --git a/src/Plugins/Payments.PayPalStandard/Manifest.cs b/src/Plugins/Payments.PayPalStandard/Manifest.cs
index 329a28e82..af3ad3e2a 100644
--- a/src/Plugins/Payments.PayPalStandard/Manifest.cs
+++ b/src/Plugins/Payments.PayPalStandard/Manifest.cs
@@ -8,5 +8,5 @@ using Payments.PayPalStandard;
SystemName = PayPalStandardPaymentDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs
index b85151f6c..bf7ca7bac 100644
--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs
+++ b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs
@@ -91,7 +91,7 @@ namespace Payments.PayPalStandard
/// <summary>
/// Create common query parameters for the request
/// </summary>
- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
+ /// <param name="order"></param>
/// <returns>Created query parameters</returns>
private async Task<IDictionary<string, string>> CreateQueryParameters(Order order)
{
@@ -99,7 +99,7 @@ namespace Payments.PayPalStandard
var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');
var stateProvince = "";
var countryCode = "";
- if (!String.IsNullOrEmpty(order.ShippingAddress?.StateProvinceId))
+ if (!string.IsNullOrEmpty(order.ShippingAddress?.StateProvinceId))
{
var countryService = _serviceProvider.GetRequiredService<ICountryService>();
var country = await countryService.GetCountryById(order.ShippingAddress?.CountryId);
@@ -107,7 +107,7 @@ namespace Payments.PayPalStandard
if (state != null)
stateProvince = state.Abbreviation;
}
- if (!String.IsNullOrEmpty(order.ShippingAddress?.CountryId))
+ if (!string.IsNullOrEmpty(order.ShippingAddress?.CountryId))
{
var country = await _serviceProvider.GetRequiredService<ICountryService>().GetCountryById(order.ShippingAddress?.CountryId);
if (country != null)
@@ -158,7 +158,7 @@ namespace Payments.PayPalStandard
/// Add order items to the request query parameters
/// </summary>
/// <param name="parameters">Query parameters</param>
- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
+ /// <param name="order"></param>
private async Task AddItemsParameters(IDictionary<string, string> parameters, Order order)
{
//upload order items
@@ -181,7 +181,7 @@ namespace Payments.PayPalStandard
parameters.Add($"amount_{itemCount}", roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture));
parameters.Add($"quantity_{itemCount}", item.Quantity.ToString());
- cartTotal += (item.PriceExclTax);
+ cartTotal += item.PriceExclTax;
roundedCartTotal += roundedItemPrice * item.Quantity;
itemCount++;
}
@@ -196,7 +196,7 @@ namespace Payments.PayPalStandard
var attributePrice = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer);
if (attributePrice.checkoutPrice > 0)
{
- double roundedAttributePrice = Math.Round(await currencyService.ConvertFromPrimaryStoreCurrency(attributePrice.checkoutPrice, workContext.WorkingCurrency), 2);
+ var roundedAttributePrice = Math.Round(await currencyService.ConvertFromPrimaryStoreCurrency(attributePrice.checkoutPrice, workContext.WorkingCurrency), 2);
//add query parameters
if (attributeValue.ca != null)
{
@@ -219,7 +219,7 @@ namespace Payments.PayPalStandard
parameters.Add($"amount_{itemCount}", roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture));
parameters.Add($"quantity_{itemCount}", "1");
- cartTotal += (order.OrderShippingExclTax);
+ cartTotal += order.OrderShippingExclTax;
roundedCartTotal += roundedShippingPrice;
itemCount++;
}
@@ -232,7 +232,7 @@ namespace Payments.PayPalStandard
parameters.Add($"amount_{itemCount}", roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture));
parameters.Add($"quantity_{itemCount}", "1");
- cartTotal += (order.PaymentMethodAdditionalFeeExclTax);
+ cartTotal += order.PaymentMethodAdditionalFeeExclTax;
roundedCartTotal += roundedPaymentMethodPrice;
itemCount++;
}
@@ -245,15 +245,14 @@ namespace Payments.PayPalStandard
parameters.Add($"amount_{itemCount}", roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture));
parameters.Add($"quantity_{itemCount}", "1");
- cartTotal += (order.OrderTax);
+ cartTotal += order.OrderTax;
roundedCartTotal += roundedTaxAmount;
- itemCount++;
}
if (cartTotal > order.OrderTotal)
{
//get the difference between what the order total is and what it should be and use that as the "discount"
- var discountTotal = Math.Round(cartTotal - (order.OrderTotal), 2);
+ var discountTotal = Math.Round(cartTotal - order.OrderTotal, 2);
roundedCartTotal -= discountTotal;
//gift voucher or loyalty points amount applied to cart in nopCommerce - shows in PayPal as "discount"
@@ -268,7 +267,7 @@ namespace Payments.PayPalStandard
/// Add order total to the request query parameters
/// </summary>
/// <param name="parameters">Query parameters</param>
- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
+ /// <param name="order"></param>
private async Task AddOrderTotalParameters(IDictionary<string, string> parameters, Order order)
{
//round order total
@@ -298,7 +297,7 @@ namespace Payments.PayPalStandard
/// <summary>
/// Process a payment
/// </summary>
- /// <param name="processPaymentRequest">Payment info required for an order processing</param>
+ /// <param name="paymentTransaction"></param>
/// <returns>Process payment result</returns>
public async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)
{
@@ -310,10 +309,11 @@ namespace Payments.PayPalStandard
//nothing
return Task.CompletedTask;
}
+
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
- /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
+ /// <param name="paymentTransaction"></param>
public async Task PostRedirectPayment(PaymentTransaction paymentTransaction)
{
var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);
@@ -335,7 +335,7 @@ namespace Payments.PayPalStandard
var redirectUrl = QueryHelpers.AddQueryString(GetPaypalUrl(), parameters);
if (redirectUrl.Length <= 2048)
{
- _httpContextAccessor.HttpContext.Response.Redirect(redirectUrl);
+ _httpContextAccessor.HttpContext?.Response.Redirect(redirectUrl);
return;
}
}
@@ -348,7 +348,7 @@ namespace Payments.PayPalStandard
.ToDictionary(parameter => parameter.Key, parameter => parameter.Value);
var url = QueryHelpers.AddQueryString(GetPaypalUrl(), queryParameters);
- _httpContextAccessor.HttpContext.Response.Redirect(url);
+ _httpContextAccessor.HttpContext?.Response.Redirect(url);
}
/// <summary>
@@ -380,18 +380,17 @@ namespace Payments.PayPalStandard
//percentage
var orderTotalCalculationService = _serviceProvider.GetRequiredService<IOrderCalculationService>();
var subtotal = await orderTotalCalculationService.GetShoppingCartSubTotal(cart, true);
- result = (double)((((float)subtotal.subTotalWithDiscount) * ((float)_paypalStandardPaymentSettings.AdditionalFee)) / 100f);
+ result = (float)subtotal.subTotalWithDiscount * (float)_paypalStandardPaymentSettings.AdditionalFee / 100f;
}
else
{
//fixed value
result = _paypalStandardPaymentSettings.AdditionalFee;
}
- if (result > 0)
- {
- var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
- result = await currencyService.ConvertFromPrimaryStoreCurrency(result, _workContext.WorkingCurrency);
- }
+
+ if (!(result > 0)) return await Task.FromResult(result);
+ var currencyService = _serviceProvider.GetRequiredService<ICurrencyService>();
+ result = await currencyService.ConvertFromPrimaryStoreCurrency(result, _workContext.WorkingCurrency);
//return result;
return await Task.FromResult(result);
}
diff --git a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs b/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs
index d774b738c..54c20163f 100644
--- a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs
+++ b/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs
@@ -22,24 +22,17 @@ namespace Payments.PayPalStandard
{
var result = PaymentStatus.Pending;
- if (paymentStatus == null)
- paymentStatus = string.Empty;
+ paymentStatus ??= string.Empty;
- if (pendingReason == null)
- pendingReason = string.Empty;
+ pendingReason ??= string.Empty;
switch (paymentStatus.ToLowerInvariant())
{
case "pending":
- switch (pendingReason.ToLowerInvariant())
- {
- case "authorization":
- result = PaymentStatus.Authorized;
- break;
- default:
- result = PaymentStatus.Pending;
- break;
- }
+ result = pendingReason.ToLowerInvariant() switch {
+ "authorization" => PaymentStatus.Authorized,
+ _ => PaymentStatus.Pending
+ };
break;
case "processed":
case "completed":
@@ -56,8 +49,6 @@ namespace Payments.PayPalStandard
case "reversed":
result = PaymentStatus.Refunded;
break;
- default:
- break;
}
return result;
}
diff --git a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
index 480fd7a1d..35417d871 100644
--- a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
+++ b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
@@ -26,7 +26,7 @@ namespace Payments.PayPalStandard.Services
"https://ipnpb.paypal.com/cgi-bin/webscr";
}
- public virtual async Task<(bool success, Dictionary<string, string> values)> VerifyIpn(string formString)
+ public async Task<(bool success, Dictionary<string, string> values)> VerifyIpn(string formString)
{
var formContent = new StringContent($"cmd=_notify-validate&{formString}",
Encoding.UTF8, "application/x-www-form-urlencoded");
@@ -51,7 +51,7 @@ namespace Payments.PayPalStandard.Services
var line = l.Trim();
var equalPox = line.IndexOf('=');
if (equalPox >= 0)
- values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
+ values.Add(line[..equalPox], line[(equalPox + 1)..]);
}
return (success, values);
}
@@ -67,7 +67,7 @@ namespace Payments.PayPalStandard.Services
PaypalHelper.PayPalUrl;
}
- public virtual async Task<(bool status, Dictionary<string, string> values, string response)> GetPdtDetails(string tx)
+ public async Task<(bool status, Dictionary<string, string> values, string response)> GetPdtDetails(string tx)
{
var formContent = new StringContent($"cmd=_notify-synch&at={_paypalStandardPaymentSettings.PdtToken}&tx={tx}",
Encoding.UTF8, "application/x-www-form-urlencoded");
@@ -97,7 +97,7 @@ namespace Payments.PayPalStandard.Services
{
var equalPox = line.IndexOf('=');
if (equalPox >= 0)
- values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
+ values.Add(line[..equalPox], line[(equalPox + 1)..]);
}
}
diff --git a/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml b/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml
index 4a4040aea..85dd44163 100644
--- a/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml
+++ b/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml
@@ -1,10 +1,6 @@
@{
Layout = "";
}
-<table width="100%" cellpadding="0" cellspacing="0">
- <tr>
- <td>
- <b>@Loc["Plugins.Payments.PayPalStandard.Fields.RedirectionTip"]</b>
- </td>
- </tr>
-</table>
+<div>
+ <b>@Loc["Plugins.Payments.PayPalStandard.Fields.RedirectionTip"]</b>
+</div>
\ No newline at end of file
diff --git a/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs b/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs
index 40f8a3758..c5d4d5145 100644
--- a/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs
+++ b/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs
@@ -65,10 +65,10 @@ namespace Shipping.ByWeight.Controllers
}
public IActionResult Configure()
{
- var model = new ShippingByWeightListModel();
-
- model.LimitMethodsToCreated = _shippingByWeightSettings.LimitMethodsToCreated;
- model.DisplayOrder = _shippingByWeightSettings.DisplayOrder;
+ var model = new ShippingByWeightListModel {
+ LimitMethodsToCreated = _shippingByWeightSettings.LimitMethodsToCreated,
+ DisplayOrder = _shippingByWeightSettings.DisplayOrder
+ };
return View(model);
}
@@ -109,39 +109,39 @@ namespace Shipping.ByWeight.Controllers
AdditionalFixedCost = x.AdditionalFixedCost,
PercentageRateOfSubtotal = x.PercentageRateOfSubtotal,
RatePerWeightUnit = x.RatePerWeightUnit,
- LowerWeightLimit = x.LowerWeightLimit,
+ LowerWeightLimit = x.LowerWeightLimit
};
//shipping method
var shippingMethod = await _shippingMethodService.GetShippingMethodById(x.ShippingMethodId);
- m.ShippingMethodName = (shippingMethod != null) ? shippingMethod.Name : "Unavailable";
+ m.ShippingMethodName = shippingMethod != null ? shippingMethod.Name : "Unavailable";
//store
var store = await _storeService.GetStoreById(x.StoreId);
- m.StoreName = (store != null) ? store.Shortcut : "*";
+ m.StoreName = store != null ? store.Shortcut : "*";
//warehouse
var warehouse = await _warehouseService.GetWarehouseById(x.WarehouseId);
- m.WarehouseName = (warehouse != null) ? warehouse.Name : "*";
+ m.WarehouseName = warehouse != null ? warehouse.Name : "*";
//country
var c = await _countryService.GetCountryById(x.CountryId);
- m.CountryName = (c != null) ? c.Name : "*";
+ m.CountryName = c != null ? c.Name : "*";
//state
var s = c?.StateProvinces.FirstOrDefault(y => y.Id == x.StateProvinceId);
- m.StateProvinceName = (s != null) ? s.Name : "*";
+ m.StateProvinceName = s != null ? s.Name : "*";
//zip
- m.Zip = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
+ m.Zip = !string.IsNullOrEmpty(x.Zip) ? x.Zip : "*";
var htmlSb = new StringBuilder("<div>");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.From"), m.From);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.From")}: {m.From}");
htmlSb.Append("<br />");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.To"), m.To);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.To")}: {m.To}");
htmlSb.Append("<br />");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.AdditionalFixedCost"), m.AdditionalFixedCost);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.AdditionalFixedCost")}: {m.AdditionalFixedCost}");
htmlSb.Append("<br />");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.RatePerWeightUnit"), m.RatePerWeightUnit);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.RatePerWeightUnit")}: {m.RatePerWeightUnit}");
htmlSb.Append("<br />");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.LowerWeightLimit"), m.LowerWeightLimit);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.LowerWeightLimit")}: {m.LowerWeightLimit}");
htmlSb.Append("<br />");
- htmlSb.AppendFormat("{0}: {1}", _translationService.GetResource("Plugins.Shipping.ByWeight.Fields.PercentageRateOfSubtotal"), m.PercentageRateOfSubtotal);
+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.PercentageRateOfSubtotal")}: {m.PercentageRateOfSubtotal}");
htmlSb.Append("</div>");
m.DataHtml = htmlSb.ToString();
@@ -170,10 +170,11 @@ namespace Shipping.ByWeight.Controllers
public async Task<IActionResult> AddPopup()
{
- var model = new ShippingByWeightModel();
- model.PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode;
- model.BaseWeightIn = (await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)).Name;
- model.To = 1000000;
+ var model = new ShippingByWeightModel {
+ PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode,
+ BaseWeightIn = (await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)).Name,
+ To = 1000000
+ };
var shippingMethods = await _shippingMethodService.GetAllShippingMethods();
if (shippingMethods.Count == 0)
@@ -182,19 +183,19 @@ namespace Shipping.ByWeight.Controllers
//stores
model.AvailableStores.Add(new SelectListItem { Text = "*", Value = " " });
foreach (var store in await _storeService.GetAllStores())
- model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id.ToString() });
+ model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id });
//warehouses
model.AvailableWarehouses.Add(new SelectListItem { Text = "*", Value = " " });
foreach (var warehouses in await _warehouseService.GetAllWarehouses())
- model.AvailableWarehouses.Add(new SelectListItem { Text = warehouses.Name, Value = warehouses.Id.ToString() });
+ model.AvailableWarehouses.Add(new SelectListItem { Text = warehouses.Name, Value = warehouses.Id });
//shipping methods
foreach (var sm in shippingMethods)
- model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id.ToString() });
+ model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id });
//countries
model.AvailableCountries.Add(new SelectListItem { Text = "*", Value = " " });
var countries = await _countryService.GetAllCountries(showHidden: true);
foreach (var c in countries)
- model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() });
+ model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id });
//states
model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" });
@@ -266,24 +267,24 @@ namespace Shipping.ByWeight.Controllers
//stores
model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "" });
foreach (var store in await _storeService.GetAllStores())
- model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id.ToString(), Selected = (selectedStore != null && store.Id == selectedStore.Id) });
+ model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id, Selected = selectedStore != null && store.Id == selectedStore.Id });
//warehouses
model.AvailableWarehouses.Add(new SelectListItem { Text = "*", Value = "" });
foreach (var warehouse in await _warehouseService.GetAllWarehouses())
- model.AvailableWarehouses.Add(new SelectListItem { Text = warehouse.Name, Value = warehouse.Id.ToString(), Selected = (selectedWarehouse != null && warehouse.Id == selectedWarehouse.Id) });
+ model.AvailableWarehouses.Add(new SelectListItem { Text = warehouse.Name, Value = warehouse.Id, Selected = selectedWarehouse != null && warehouse.Id == selectedWarehouse.Id });
//shipping methods
foreach (var sm in shippingMethods)
- model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id.ToString(), Selected = (selectedShippingMethod != null && sm.Id == selectedShippingMethod.Id) });
+ model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id, Selected = selectedShippingMethod != null && sm.Id == selectedShippingMethod.Id });
//countries
model.AvailableCountries.Add(new SelectListItem { Text = "*", Value = "" });
var countries = await _countryService.GetAllCountries(showHidden: true);
foreach (var c in countries)
- model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = (selectedCountry != null && c.Id == selectedCountry.Id) });
+ model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id, Selected = selectedCountry != null && c.Id == selectedCountry.Id });
//states
var states = selectedCountry != null ? await _countryService.GetStateProvincesByCountryId(selectedCountry.Id) : new List<StateProvince>();
model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" });
foreach (var s in states)
- model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (selectedState != null && s.Id == selectedState.Id) });
+ model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id, Selected = selectedState != null && s.Id == selectedState.Id });
return View(model);
}
diff --git a/src/Plugins/Shipping.ByWeight/ByWeightShippingPlugin.cs b/src/Plugins/Shipping.ByWeight/ByWeightShippingPlugin.cs
index a2d1e055e..48b8be3bb 100644
--- a/src/Plugins/Shipping.ByWeight/ByWeightShippingPlugin.cs
+++ b/src/Plugins/Shipping.ByWeight/ByWeightShippingPlugin.cs
@@ -36,7 +36,7 @@ namespace Shipping.ByWeight
{
//settings
var settings = new ByWeightShippingSettings {
- LimitMethodsToCreated = false,
+ LimitMethodsToCreated = false
};
await _settingService.SaveSetting(settings);
@@ -64,18 +64,10 @@ namespace Shipping.ByWeight
await base.Install();
}
- /// <summary>
- /// Uninstall plugin
- /// </summary>
- public override async Task Uninstall()
- {
- await base.Uninstall();
- }
-
/// <summary>
/// Returns a value indicating whether shipping methods should be hidden during checkout
/// </summary>
- /// <param name="cart">Shoping cart</param>
+ /// <param name="cart">Shopping cart</param>
/// <returns>true - hide; false - display.</returns>
public async Task<bool> HideShipmentMethods(IList<ShoppingCartItem> cart)
{
diff --git a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
index 6a4de547e..575781c67 100644
--- a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
+++ b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
@@ -75,7 +75,7 @@ namespace Shipping.ByWeight
}
//additional fixed cost
- double shippingTotal = shippingByWeightRecord.AdditionalFixedCost;
+ var shippingTotal = shippingByWeightRecord.AdditionalFixedCost;
//charge amount per weight unit
if (shippingByWeightRecord.RatePerWeightUnit > 0)
{
@@ -87,7 +87,7 @@ namespace Shipping.ByWeight
//percentage rate of subtotal
if (shippingByWeightRecord.PercentageRateOfSubtotal > 0)
{
- shippingTotal += Math.Round((double)((((float)subTotal) * ((float)shippingByWeightRecord.PercentageRateOfSubtotal)) / 100f), 2);
+ shippingTotal += Math.Round((float)subTotal * (float)shippingByWeightRecord.PercentageRateOfSubtotal / 100f, 2);
}
if (shippingTotal < 0)
@@ -132,14 +132,12 @@ namespace Shipping.ByWeight
{
//bundled product
var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);
- if (associatedProduct != null && associatedProduct.IsShipEnabled)
+ if (associatedProduct is { IsShipEnabled: true })
{
attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;
}
}
break;
- default:
- break;
}
}
}
@@ -150,7 +148,7 @@ namespace Shipping.ByWeight
/// Gets shopping cart weight
/// </summary>
/// <param name="request">Request</param>
- /// <param name="includeCheckoutAttributes">A value indicating whether we should calculate weights of selected checkotu attributes</param>
+ /// <param name="includeCheckoutAttributes">A value indicating whether we should calculate weights of selected checkout attributes</param>
/// <returns>Total weight</returns>
private async Task<double> GetTotalWeight(GetShippingOptionRequest request, bool includeCheckoutAttributes = true)
{
@@ -204,14 +202,14 @@ namespace Shipping.ByWeight
}
var storeId = getShippingOptionRequest.StoreId;
- if (String.IsNullOrEmpty(storeId))
+ if (string.IsNullOrEmpty(storeId))
storeId = _workContext.CurrentStore.Id;
- string countryId = getShippingOptionRequest.ShippingAddress.CountryId;
- string stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId;
+ var countryId = getShippingOptionRequest.ShippingAddress.CountryId;
+ var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId;
//string warehouseId = getShippingOptionRequest.WarehouseFrom != null ? getShippingOptionRequest.WarehouseFrom.Id : "";
- string zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
+ var zip = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
double subTotal = 0;
var priceCalculationService = _serviceProvider.GetRequiredService<IPricingService>();
@@ -225,7 +223,7 @@ namespace Shipping.ByWeight
subTotal += (await priceCalculationService.GetSubTotal(packageItem.ShoppingCartItem, product)).subTotal;
}
- double weight = await GetTotalWeight(getShippingOptionRequest);
+ var weight = await GetTotalWeight(getShippingOptionRequest);
var shippingMethods = await _shippingMethodService.GetAllShippingMethods(countryId, _workContext.CurrentCustomer);
foreach (var shippingMethod in shippingMethods)
@@ -236,19 +234,19 @@ namespace Shipping.ByWeight
var _rate = await GetRate(subTotal, weight, shippingMethod.Id, storeId, item, countryId, stateProvinceId, zip);
if (_rate.HasValue)
{
- if (rate == null)
- rate = 0;
+ rate ??= 0;
rate += _rate.Value;
}
}
- if (rate != null && rate.HasValue)
+ if (rate is { })
{
- var shippingOption = new ShippingOption();
- shippingOption.Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);
- shippingOption.Description = shippingMethod.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id);
- shippingOption.Rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rate.Value, _workContext.WorkingCurrency);
+ var shippingOption = new ShippingOption {
+ Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ Description = shippingMethod.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rate.Value, _workContext.WorkingCurrency)
+ };
response.ShippingOptions.Add(shippingOption);
}
}
@@ -270,7 +268,7 @@ namespace Shipping.ByWeight
/// <summary>
/// Returns a value indicating whether shipping methods should be hidden during checkout
/// </summary>
- /// <param name="cart">Shoping cart</param>
+ /// <param name="cart">Shopping cart</param>
/// <returns>true - hide; false - display.</returns>
public async Task<bool> HideShipmentMethods(IList<ShoppingCartItem> cart)
{
diff --git a/src/Plugins/Shipping.ByWeight/Domain/ShippingByWeightRecord.cs b/src/Plugins/Shipping.ByWeight/Domain/ShippingByWeightRecord.cs
index 86bc54dac..994fa81af 100644
--- a/src/Plugins/Shipping.ByWeight/Domain/ShippingByWeightRecord.cs
+++ b/src/Plugins/Shipping.ByWeight/Domain/ShippingByWeightRecord.cs
@@ -5,7 +5,7 @@ namespace Shipping.ByWeight.Domain
/// <summary>
/// Represents a shipping by weight record
/// </summary>
- public partial class ShippingByWeightRecord : BaseEntity
+ public class ShippingByWeightRecord : BaseEntity
{
/// <summary>
/// Gets or sets the store identifier
diff --git a/src/Plugins/Shipping.ByWeight/Manifest.cs b/src/Plugins/Shipping.ByWeight/Manifest.cs
index 8e1d49f1c..97b20e129 100644
--- a/src/Plugins/Shipping.ByWeight/Manifest.cs
+++ b/src/Plugins/Shipping.ByWeight/Manifest.cs
@@ -8,5 +8,5 @@ using Shipping.ByWeight;
SystemName = ByWeightShippingDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs
index 9a0ce8572..903e03e8d 100644
--- a/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs
+++ b/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs
@@ -3,7 +3,7 @@ using Shipping.ByWeight.Domain;
namespace Shipping.ByWeight.Services
{
- public partial interface IShippingByWeightService
+ public interface IShippingByWeightService
{
Task DeleteShippingByWeightRecord(ShippingByWeightRecord shippingByWeightRecord);
diff --git a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs
index 738c6f6f7..829c7f1ab 100644
--- a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs
+++ b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs
@@ -5,7 +5,7 @@ using Shipping.ByWeight.Domain;
namespace Shipping.ByWeight.Services
{
- public partial class ShippingByWeightService : IShippingByWeightService
+ public class ShippingByWeightService : IShippingByWeightService
{
#region Constants
private const string SHIPPINGBYWEIGHT_ALL_KEY = "Grand.shippingbyweight.all-{0}-{1}";
@@ -44,7 +44,7 @@ namespace Shipping.ByWeight.Services
public virtual async Task<IPagedList<ShippingByWeightRecord>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue)
{
- string key = string.Format(SHIPPINGBYWEIGHT_ALL_KEY, pageIndex, pageSize);
+ var key = string.Format(SHIPPINGBYWEIGHT_ALL_KEY, pageIndex, pageSize);
return await _cacheBase.GetAsync(key, () =>
{
var query = from sbw in _sbwRepository.Table
@@ -58,8 +58,7 @@ namespace Shipping.ByWeight.Services
string storeId, string warehouseId,
string countryId, string stateProvinceId, string zip, double weight)
{
- if (zip == null)
- zip = string.Empty;
+ zip ??= string.Empty;
zip = zip.Trim();
var existingRates = (await GetAll())
@@ -67,28 +66,28 @@ namespace Shipping.ByWeight.Services
.ToList();
if (!string.IsNullOrEmpty(warehouseId))
- existingRates = existingRates.Where(x => x.WarehouseId == warehouseId).Any()
+ existingRates = existingRates.Any(x => x.WarehouseId == warehouseId)
? existingRates.Where(x => x.WarehouseId == warehouseId).ToList()
: existingRates.Where(x => string.IsNullOrEmpty(x.WarehouseId)).ToList();
if (!string.IsNullOrEmpty(storeId))
- existingRates = existingRates.Where(x => x.StoreId == storeId).Any()
+ existingRates = existingRates.Any(x => x.StoreId == storeId)
? existingRates.Where(x => x.StoreId == storeId).ToList()
: existingRates.Where(x => string.IsNullOrEmpty(x.StoreId)).ToList();
if (!string.IsNullOrEmpty(countryId))
- existingRates = existingRates.Where(x => x.CountryId == countryId).Any()
+ existingRates = existingRates.Any(x => x.CountryId == countryId)
? existingRates.Where(x => x.CountryId == countryId).ToList()
: existingRates.Where(x => string.IsNullOrEmpty(x.CountryId)).ToList();
if (!string.IsNullOrEmpty(stateProvinceId))
- existingRates = existingRates.Where(x => x.StateProvinceId == stateProvinceId).Any()
+ existingRates = existingRates.Any(x => x.StateProvinceId == stateProvinceId)
? existingRates.Where(x => x.StateProvinceId == stateProvinceId).ToList()
: existingRates.Where(x => string.IsNullOrEmpty(x.StateProvinceId)).ToList();
if (!string.IsNullOrEmpty(zip))
- existingRates = existingRates.Where(x => x.Zip == zip).Any()
- ? existingRates.Where(x => x.Zip == zip).ToList()
+ existingRates = existingRates.Any(x => x.Zip == zip)
+ ? existingRates.Where(x => x.Zip == zip).ToList()
: existingRates.Where(x => string.IsNullOrEmpty(x.Zip)).ToList();
return existingRates.FirstOrDefault();
diff --git a/src/Plugins/Shipping.FixedRateShipping/Areas/Admin/Controllers/ShippingFixedRateController.cs b/src/Plugins/Shipping.FixedRateShipping/Areas/Admin/Controllers/ShippingFixedRateController.cs
index 9fa3efdb6..4f971f0a1 100644
--- a/src/Plugins/Shipping.FixedRateShipping/Areas/Admin/Controllers/ShippingFixedRateController.cs
+++ b/src/Plugins/Shipping.FixedRateShipping/Areas/Admin/Controllers/ShippingFixedRateController.cs
@@ -64,21 +64,23 @@ namespace Shipping.FixedRateShipping.Controllers
if (!await _permissionService.Authorize(StandardPermission.ManageShippingSettings))
return Content("Access denied");
- string shippingMethodId = model.ShippingMethodId;
+ var shippingMethodId = model.ShippingMethodId;
var rate = new FixedShippingRate()
{
Rate = model.Rate
};
- await _settingService.SetSetting(string.Format("ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{0}", shippingMethodId), rate);
+ await _settingService.SetSetting(
+ $"ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{shippingMethodId}", rate);
return new JsonResult("");
}
[NonAction]
- protected double GetShippingRate(string shippingMethodId)
+ private double GetShippingRate(string shippingMethodId)
{
- var rate = _settingService.GetSettingByKey<FixedShippingRate>(string.Format("ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{0}", shippingMethodId))?.Rate;
+ var rate = _settingService.GetSettingByKey<FixedShippingRate>(
+ $"ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{shippingMethodId}")?.Rate;
return rate ?? 0;
}
}
diff --git a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
index a93fc4596..e8fc51e3d 100644
--- a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
+++ b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
@@ -43,7 +43,7 @@ namespace Shipping.FixedRateShipping
private double GetRate(string shippingMethodId)
{
- string key = string.Format("ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{0}", shippingMethodId);
+ var key = $"ShippingRateComputationMethod.FixedRate.Rate.ShippingMethodId{shippingMethodId}";
var rate = this._settingService.GetSettingByKey<FixedShippingRate>(key)?.Rate;
return rate ?? 0;
}
@@ -69,7 +69,7 @@ namespace Shipping.FixedRateShipping
return response;
}
- string restrictByCountryId = (getShippingOptionRequest.ShippingAddress != null && !String.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId)) ? getShippingOptionRequest.ShippingAddress.CountryId : "";
+ var restrictByCountryId = getShippingOptionRequest.ShippingAddress != null && !string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId) ? getShippingOptionRequest.ShippingAddress.CountryId : "";
var shippingMethods = await _shippingMethodService.GetAllShippingMethods(restrictByCountryId, getShippingOptionRequest.Customer);
foreach (var shippingMethod in shippingMethods)
{
@@ -95,13 +95,13 @@ namespace Shipping.FixedRateShipping
if (getShippingOptionRequest == null)
throw new ArgumentNullException(nameof(getShippingOptionRequest));
- string restrictByCountryId = (getShippingOptionRequest.ShippingAddress != null && !String.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId)) ? getShippingOptionRequest.ShippingAddress.CountryId : "";
+ var restrictByCountryId = getShippingOptionRequest.ShippingAddress != null && !string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId) ? getShippingOptionRequest.ShippingAddress.CountryId : "";
var shippingMethods = await _shippingMethodService.GetAllShippingMethods(restrictByCountryId);
var rates = new List<double>();
foreach (var shippingMethod in shippingMethods)
{
- double rate = GetRate(shippingMethod.Id);
+ var rate = GetRate(shippingMethod.Id);
if (!rates.Contains(rate))
rates.Add(rate);
}
diff --git a/src/Plugins/Shipping.FixedRateShipping/Manifest.cs b/src/Plugins/Shipping.FixedRateShipping/Manifest.cs
index 595676bf3..1b9b79d3c 100644
--- a/src/Plugins/Shipping.FixedRateShipping/Manifest.cs
+++ b/src/Plugins/Shipping.FixedRateShipping/Manifest.cs
@@ -8,5 +8,5 @@ using Shipping.FixedRateShipping;
SystemName = FixedRateShippingDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Admin/Controllers/ShippingPointController.cs b/src/Plugins/Shipping.ShippingPoint/Areas/Admin/Controllers/ShippingPointController.cs
index 87fd9f476..cec9220da 100644
--- a/src/Plugins/Shipping.ShippingPoint/Areas/Admin/Controllers/ShippingPointController.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Admin/Controllers/ShippingPointController.cs
@@ -1,5 +1,4 @@
-using Grand.Business.Core.Interfaces.Catalog.Prices;
-using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Utilities.Common.Security;
@@ -7,7 +6,6 @@ using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
-using Grand.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Shipping.ShippingPoint.Models;
@@ -20,31 +18,22 @@ namespace Shipping.ShippingPoint.Controllers
[PermissionAuthorize(PermissionSystemName.ShippingSettings)]
public class ShippingPointController : BaseShippingController
{
- private readonly IWorkContext _workContext;
- private readonly IUserFieldService _userFieldService;
private readonly ITranslationService _translationService;
private readonly IShippingPointService _shippingPointService;
private readonly ICountryService _countryService;
private readonly IStoreService _storeService;
- private readonly IPriceFormatter _priceFormatter;
public ShippingPointController(
- IWorkContext workContext,
- IUserFieldService userFieldService,
ITranslationService translationService,
- IShippingPointService ShippingPointService,
+ IShippingPointService shippingPointService,
ICountryService countryService,
- IStoreService storeService,
- IPriceFormatter priceFormatter
- )
+ IStoreService storeService
+ )
{
- _workContext = workContext;
- _userFieldService = userFieldService;
_translationService = translationService;
- _shippingPointService = ShippingPointService;
+ _shippingPointService = shippingPointService;
_countryService = countryService;
_storeService = storeService;
- _priceFormatter = priceFormatter;
}
public IActionResult Configure()
@@ -55,40 +44,42 @@ namespace Shipping.ShippingPoint.Controllers
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command)
{
- var shippingPoints = await _shippingPointService.GetAllStoreShippingPoint(storeId: "", pageIndex: command.Page - 1, pageSize: command.PageSize);
+ var shippingPoints = await _shippingPointService.GetAllStoreShippingPoint(storeId: "",
+ pageIndex: command.Page - 1, pageSize: command.PageSize);
var viewModel = new List<ShippingPointModel>();
foreach (var shippingPoint in shippingPoints)
{
var storeName = await _storeService.GetStoreById(shippingPoint.StoreId);
- viewModel.Add(new ShippingPointModel
- {
+ viewModel.Add(new ShippingPointModel {
ShippingPointName = shippingPoint.ShippingPointName,
Description = shippingPoint.Description,
Id = shippingPoint.Id,
OpeningHours = shippingPoint.OpeningHours,
PickupFee = shippingPoint.PickupFee,
- StoreName = storeName != null ? storeName.Shortcut : _translationService.GetResource("Admin.Settings.StoreScope.AllStores"),
-
+ StoreName = storeName != null
+ ? storeName.Shortcut
+ : _translationService.GetResource("Admin.Settings.StoreScope.AllStores")
});
}
- return Json(new DataSourceResult
- {
+ return Json(new DataSourceResult {
Data = viewModel,
Total = shippingPoints.TotalCount
});
}
- private async Task<ShippingPointModel> PrepareShippingPointModel(ShippingPointModel model)
+ private async Task PrepareShippingPointModel(ShippingPointModel model)
{
- model.AvailableCountries.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = string.Empty });
+ model.AvailableCountries.Add(new SelectListItem
+ { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = string.Empty });
foreach (var country in await _countryService.GetAllCountries(showHidden: true))
- model.AvailableCountries.Add(new SelectListItem { Text = country.Name, Value = country.Id.ToString() });
- model.AvailableStores.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Settings.StoreScope.AllStores"), Value = string.Empty });
+ model.AvailableCountries.Add(new SelectListItem { Text = country.Name, Value = country.Id });
+ model.AvailableStores.Add(new SelectListItem {
+ Text = _translationService.GetResource("Admin.Settings.StoreScope.AllStores"), Value = string.Empty
+ });
foreach (var store in await _storeService.GetAllStores())
- model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id.ToString() });
- return model;
+ model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id });
}
public async Task<IActionResult> Create()
@@ -128,12 +119,12 @@ namespace Shipping.ShippingPoint.Controllers
{
if (ModelState.IsValid)
{
- var shippingPoint = await _shippingPointService.GetStoreShippingPointById(model.Id);
- shippingPoint = model.ToEntity();
+ var shippingPoint = model.ToEntity();
await _shippingPointService.UpdateStoreShippingPoint(shippingPoint);
return Content("");
}
+
ViewBag.RefreshPage = true;
await PrepareShippingPointModel(model);
@@ -149,6 +140,5 @@ namespace Shipping.ShippingPoint.Controllers
return new JsonResult("");
}
-
}
-}
+}
\ No newline at end of file
diff --git a/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs b/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
index a544f60ca..f4300ce7b 100644
--- a/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
@@ -40,7 +40,7 @@ namespace Shipping.ShippingPoint.Controllers
var rateBase = await _currencyService.ConvertFromPrimaryStoreCurrency(shippingPoint.PickupFee, _workContext.WorkingCurrency);
var fee = _priceFormatter.FormatShippingPrice(rateBase);
- var viewModel = new PointModel() {
+ var viewModel = new PointModel {
ShippingPointName = shippingPoint.ShippingPointName,
Description = shippingPoint.Description,
PickupFee = fee,
@@ -48,7 +48,7 @@ namespace Shipping.ShippingPoint.Controllers
Address1 = shippingPoint.Address1,
City = shippingPoint.City,
CountryName = (await _countryService.GetCountryById(shippingPoint.CountryId))?.Name,
- ZipPostalCode = shippingPoint.ZipPostalCode,
+ ZipPostalCode = shippingPoint.ZipPostalCode
};
return View(viewModel);
}
@@ -64,7 +64,7 @@ namespace Shipping.ShippingPoint.Controllers
var shippingPointsModel = new List<SelectListItem> {
new() { Value = "", Text = _translationService.GetResource("Shipping.ShippingPoint.SelectShippingOption") }
};
- shippingPointsModel.AddRange(shippingPoints.Select(shippingPoint => new SelectListItem() { Value = shippingPoint.Id, Text = shippingPoint.ShippingPointName }));
+ shippingPointsModel.AddRange(shippingPoints.Select(shippingPoint => new SelectListItem { Value = shippingPoint.Id, Text = shippingPoint.ShippingPointName }));
return View(shippingPointsModel);
diff --git a/src/Plugins/Shipping.ShippingPoint/Domain/ShippingPoints.cs b/src/Plugins/Shipping.ShippingPoint/Domain/ShippingPoints.cs
index 06db70bd6..ff3894278 100644
--- a/src/Plugins/Shipping.ShippingPoint/Domain/ShippingPoints.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Domain/ShippingPoints.cs
@@ -40,7 +40,7 @@ namespace Shipping.ShippingPoint.Domain
public double PickupFee { get; set; }
/// <summary>
- /// Gets or sets an oppening hours
+ /// Gets or sets an opening hours
/// </summary>
public string OpeningHours { get; set; }
diff --git a/src/Plugins/Shipping.ShippingPoint/EndpointProvider.cs b/src/Plugins/Shipping.ShippingPoint/EndpointProvider.cs
index 628c4d308..d4538a4e4 100644
--- a/src/Plugins/Shipping.ShippingPoint/EndpointProvider.cs
+++ b/src/Plugins/Shipping.ShippingPoint/EndpointProvider.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Routing;
namespace Shipping.ShippingPoint
{
- public partial class EndpointProvider : IEndpointProvider
+ public class EndpointProvider : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
diff --git a/src/Plugins/Shipping.ShippingPoint/Manifest.cs b/src/Plugins/Shipping.ShippingPoint/Manifest.cs
index 72f764079..0240b16af 100644
--- a/src/Plugins/Shipping.ShippingPoint/Manifest.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Manifest.cs
@@ -8,5 +8,5 @@ using Shipping.ShippingPoint;
SystemName = ShippingPointRateDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "2.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Shipping.ShippingPoint/MapperConfiguration.cs b/src/Plugins/Shipping.ShippingPoint/MapperConfiguration.cs
index b5c3bd1a3..4a549e95f 100644
--- a/src/Plugins/Shipping.ShippingPoint/MapperConfiguration.cs
+++ b/src/Plugins/Shipping.ShippingPoint/MapperConfiguration.cs
@@ -7,10 +7,7 @@ namespace Shipping.ShippingPoint
{
public class MapperConfiguration : Profile, IAutoMapperProfile
{
- public int Order
- {
- get { return 0; }
- }
+ public int Order => 0;
public MapperConfiguration()
{
diff --git a/src/Plugins/Shipping.ShippingPoint/MappingExtensions.cs b/src/Plugins/Shipping.ShippingPoint/MappingExtensions.cs
index eec771a9f..c70717437 100644
--- a/src/Plugins/Shipping.ShippingPoint/MappingExtensions.cs
+++ b/src/Plugins/Shipping.ShippingPoint/MappingExtensions.cs
@@ -15,11 +15,5 @@ namespace Shipping.ShippingPoint
{
return model.MapTo<ShippingPointModel, ShippingPoints>();
}
-
- public static ShippingPoints ToEntity(this ShippingPointModel model, ShippingPoints destination)
- {
- return model.MapTo(destination);
- }
-
}
}
diff --git a/src/Plugins/Shipping.ShippingPoint/Services/IShippingPointService.cs b/src/Plugins/Shipping.ShippingPoint/Services/IShippingPointService.cs
index edc238b86..b3592429b 100644
--- a/src/Plugins/Shipping.ShippingPoint/Services/IShippingPointService.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Services/IShippingPointService.cs
@@ -17,36 +17,29 @@ namespace Shipping.ShippingPoint.Services
/// <returns>Pickup points</returns>
Task<IPagedList<ShippingPoints>> GetAllStoreShippingPoint(string storeId = "", int pageIndex = 0, int pageSize = int.MaxValue);
- /// <summary>
- ///
- /// </summary>
- /// <param name="pointName"></param>
- /// <returns></returns>
- Task<ShippingPoints> GetStoreShippingPointByPointName(string pointName);
-
/// <summary>
/// Gets a pickup point
/// </summary>
- /// <param name="ShippingPointId">Pickup point identifier</param>
+ /// <param name="shippingPointId">Pickup point identifier</param>
/// <returns>Pickup point</returns>
- Task<ShippingPoints> GetStoreShippingPointById(string ShippingPointId);
+ Task<ShippingPoints> GetStoreShippingPointById(string shippingPointId);
/// <summary>
/// Inserts a pickup point
/// </summary>
- /// <param name="ShippingPoint">Pickup point</param>
- Task InsertStoreShippingPoint(Domain.ShippingPoints ShippingPoint);
+ /// <param name="shippingPoint">Pickup point</param>
+ Task InsertStoreShippingPoint(ShippingPoints shippingPoint);
/// <summary>
/// Updates a pickup point
/// </summary>
- /// <param name="ShippingPoint">Pickup point</param>
- Task UpdateStoreShippingPoint(Domain.ShippingPoints ShippingPoint);
+ /// <param name="shippingPoint">Pickup point</param>
+ Task UpdateStoreShippingPoint(ShippingPoints shippingPoint);
/// <summary>
/// Deletes a pickup point
/// </summary>
- /// <param name="ShippingPoint">Pickup point</param>
- Task DeleteStoreShippingPoint(Domain.ShippingPoints ShippingPoint);
+ /// <param name="shippingPoint">Pickup point</param>
+ Task DeleteStoreShippingPoint(ShippingPoints shippingPoint);
}
}
diff --git a/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs b/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs
index fc4ad3ffc..6d667c1a6 100644
--- a/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs
@@ -48,7 +48,7 @@ namespace Shipping.ShippingPoint.Services
public virtual async Task<IPagedList<ShippingPoints>> GetAllStoreShippingPoint(string storeId = "", int pageIndex = 0, int pageSize = int.MaxValue)
{
var query = from gp in _shippingPointRepository.Table
- where (gp.StoreId == storeId || string.IsNullOrEmpty(gp.StoreId)) || storeId == ""
+ where gp.StoreId == storeId || string.IsNullOrEmpty(gp.StoreId) || storeId == ""
select gp;
var records = query.ToList();
@@ -60,13 +60,13 @@ namespace Shipping.ShippingPoint.Services
/// <summary>
///
/// </summary>
- /// <param name="pickupPointId"></param>
+ /// <param name="pointName"></param>
/// <returns></returns>
public virtual Task<ShippingPoints> GetStoreShippingPointByPointName(string pointName)
{
- return Task.FromResult((from shippingOoint in _shippingPointRepository.Table
- where shippingOoint.ShippingPointName == pointName
- select shippingOoint).FirstOrDefault());
+ return Task.FromResult((from shippingPoint in _shippingPointRepository.Table
+ where shippingPoint.ShippingPointName == pointName
+ select shippingPoint).FirstOrDefault());
}
/// <summary>
diff --git a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
index 946eb691c..05c7e86bb 100644
--- a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
+++ b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
@@ -64,8 +64,7 @@ namespace Shipping.ShippingPoint
var response = new GetShippingOptionResponse();
- response.ShippingOptions.Add(new ShippingOption()
- {
+ response.ShippingOptions.Add(new ShippingOption {
Name = _translationService.GetResource("Shipping.ShippingPoint.PluginName"),
Description = _translationService.GetResource("Shipping.ShippingPoint.PluginDescription"),
Rate = 0,
@@ -97,14 +96,14 @@ namespace Shipping.ShippingPoint
var shippingMethodName = shippingOption?.Split(new[] { ':' })[0];
if (string.IsNullOrEmpty(shippingOptionId))
- return new List<string>() { _translationService.GetResource("Shipping.ShippingPoint.SelectBeforeProceed") };
+ return new List<string> { _translationService.GetResource("Shipping.ShippingPoint.SelectBeforeProceed") };
if (shippingMethodName != _translationService.GetResource("Shipping.ShippingPoint.PluginName"))
throw new ArgumentException("shippingMethodName");
var chosenShippingOption = await _shippingPointService.GetStoreShippingPointById(shippingOptionId);
if (chosenShippingOption == null)
- return new List<string>() { _translationService.GetResource("Shipping.ShippingPoint.SelectBeforeProceed") };
+ return new List<string> { _translationService.GetResource("Shipping.ShippingPoint.SelectBeforeProceed") };
//override price
var offeredShippingOptions = await _workContext.CurrentCustomer.GetUserField<List<ShippingOption>>(_userFieldService, SystemCustomerFieldNames.OfferedShippingOptions, _workContext.CurrentStore.Id);
@@ -125,8 +124,7 @@ namespace Shipping.ShippingPoint
forCustomer,
_workContext.CurrentStore.Id);
- var serializedObject = new Domain.ShippingPointSerializable()
- {
+ var serializedObject = new Domain.ShippingPointSerializable {
Id = chosenShippingOption.Id,
ShippingPointName = chosenShippingOption.ShippingPointName,
Description = chosenShippingOption.Description,
@@ -136,7 +134,7 @@ namespace Shipping.ShippingPoint
City = chosenShippingOption.City,
Address1 = chosenShippingOption.Address1,
ZipPostalCode = chosenShippingOption.ZipPostalCode,
- StoreId = chosenShippingOption.StoreId,
+ StoreId = chosenShippingOption.StoreId
};
var stringBuilder = new StringBuilder();
diff --git a/src/Plugins/Shipping.ShippingPoint/Views/SelectedShippingPoint/Get.cshtml b/src/Plugins/Shipping.ShippingPoint/Views/SelectedShippingPoint/Get.cshtml
index fae1ee58b..29efd47ad 100644
--- a/src/Plugins/Shipping.ShippingPoint/Views/SelectedShippingPoint/Get.cshtml
+++ b/src/Plugins/Shipping.ShippingPoint/Views/SelectedShippingPoint/Get.cshtml
@@ -9,7 +9,7 @@
<div class="col-md-10">@Loc["Shipping.ShippingPoint.MethodAndFee", Model.ShippingPointName, Model.PickupFee]</div>
</div>
<div class="row">
- <div class="col-md-2 text-right"><label for="">@Loc["Shipping.ShippingPoint.Address"]</label></div>
+ <div class="col-md-2 text-right"><label>@Loc["Shipping.ShippingPoint.Address"]</label></div>
<div class="col-md-10">@Model.CountryName,&nbsp;@Model.ZipPostalCode&nbsp;@Model.City,&nbsp;@Model.Address1</div>
</div>
</div>
diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
index ed90472b1..8384e94a2 100644
--- a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
+++ b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
@@ -46,14 +46,14 @@ namespace Tax.CountryStateZip.Controllers
model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "" });
var stores = await _storeService.GetAllStores();
foreach (var s in stores)
- model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id.ToString() });
+ model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
//tax categories
foreach (var tc in taxCategories)
- model.AvailableTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString() });
+ 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.ToString() });
+ model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id });
//states
model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" });
var defaultCountry = countries.FirstOrDefault();
@@ -61,7 +61,7 @@ namespace Tax.CountryStateZip.Controllers
{
var states = await _countryService.GetStateProvincesByCountryId(defaultCountry.Id);
foreach (var s in states)
- model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() });
+ model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id });
}
return View(model);
@@ -83,22 +83,22 @@ namespace Tax.CountryStateZip.Controllers
CountryId = x.CountryId,
StateProvinceId = x.StateProvinceId,
Zip = x.Zip,
- Percentage = x.Percentage,
+ Percentage = x.Percentage
};
//store
var store = await _storeService.GetStoreById(x.StoreId);
- m.StoreName = (store != null) ? store.Shortcut : "*";
+ m.StoreName = store != null ? store.Shortcut : "*";
//tax category
var tc = await _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
- m.TaxCategoryName = (tc != null) ? tc.Name : "";
+ m.TaxCategoryName = tc != null ? tc.Name : "";
//country
var c = await _countryService.GetCountryById(x.CountryId);
- m.CountryName = (c != null) ? c.Name : "Unavailable";
+ m.CountryName = c != null ? c.Name : "Unavailable";
//state
var s = c?.StateProvinces.FirstOrDefault(z=>z.Id == x.StateProvinceId);
- m.StateProvinceName = (s != null) ? s.Name : "*";
+ m.StateProvinceName = s != null ? s.Name : "*";
//zip
- m.Zip = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
+ m.Zip = !string.IsNullOrEmpty(x.Zip) ? x.Zip : "*";
taxRatesModel.Add(m);
}
diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Views/TaxCountryStateZip/Configure.cshtml b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Views/TaxCountryStateZip/Configure.cshtml
index 13706787a..ed53c9171 100644
--- a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Views/TaxCountryStateZip/Configure.cshtml
+++ b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Views/TaxCountryStateZip/Configure.cshtml
@@ -1,5 +1,4 @@
@model TaxRateListModel
-@using Grand.Web.Common
@using Tax.CountryStateZip.Models
@using Grand.Domain.Common;
@using Microsoft.AspNetCore.Routing
diff --git a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
index 6387edcee..6d5d4063c 100644
--- a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
+++ b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
@@ -79,10 +79,8 @@ namespace Tax.CountryStateZip
var taxCategoryId = calculateTaxRequest.TaxCategoryId;
var countryId = calculateTaxRequest.Address.CountryId;
var stateProvinceId = calculateTaxRequest.Address.StateProvinceId;
- var zip = calculateTaxRequest.Address.ZipPostalCode;
+ var zip = calculateTaxRequest.Address.ZipPostalCode ?? string.Empty;
- if (zip == null)
- zip = string.Empty;
zip = zip.Trim();
var existingRates = allTaxRates.Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId).ToList();
diff --git a/src/Plugins/Tax.CountryStateZip/Domain/TaxRate.cs b/src/Plugins/Tax.CountryStateZip/Domain/TaxRate.cs
index 0b73f5c83..993b4b130 100644
--- a/src/Plugins/Tax.CountryStateZip/Domain/TaxRate.cs
+++ b/src/Plugins/Tax.CountryStateZip/Domain/TaxRate.cs
@@ -5,7 +5,7 @@ namespace Tax.CountryStateZip.Domain
/// <summary>
/// Represents a tax rate
/// </summary>
- public partial class TaxRate : BaseEntity
+ public class TaxRate : BaseEntity
{
/// <summary>
/// Gets or sets the store identifier
diff --git a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs
index df2ccd439..f91cc3d2d 100644
--- a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs
+++ b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs
@@ -9,7 +9,7 @@ namespace Tax.CountryStateZip.Infrastructure.Cache
/// <summary>
/// Model cache event consumer (used for caching of presentation layer models)
/// </summary>
- public partial class ModelCacheEventConsumer :
+ public class ModelCacheEventConsumer :
//tax rates
INotificationHandler<EntityInserted<TaxRate>>,
INotificationHandler<EntityUpdated<TaxRate>>,
diff --git a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/TaxRateForCaching.cs b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/TaxRateForCaching.cs
index dc23094d8..7abce78f9 100644
--- a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/TaxRateForCaching.cs
+++ b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/TaxRateForCaching.cs
@@ -3,7 +3,7 @@ namespace Tax.CountryStateZip.Infrastructure.Cache
/// <summary>
/// Represents a tax rate
/// </summary>
- public partial class TaxRateForCaching
+ public class TaxRateForCaching
{
public string Id { get; set; }
public string StoreId { get; set; }
diff --git a/src/Plugins/Tax.CountryStateZip/Manifest.cs b/src/Plugins/Tax.CountryStateZip/Manifest.cs
index afb537d5f..09d2f89bf 100644
--- a/src/Plugins/Tax.CountryStateZip/Manifest.cs
+++ b/src/Plugins/Tax.CountryStateZip/Manifest.cs
@@ -8,5 +8,5 @@ using Tax.CountryStateZip;
SystemName = CountryStateZipTaxDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs
index 9cb2b6bd8..8a30f0e78 100644
--- a/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs
+++ b/src/Plugins/Tax.CountryStateZip/Services/ITaxRateService.cs
@@ -6,7 +6,7 @@ namespace Tax.CountryStateZip.Services
/// <summary>
/// Tax rate service interface
/// </summary>
- public partial interface ITaxRateService
+ public interface ITaxRateService
{
/// <summary>
/// Deletes a tax rate
diff --git a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs
index ee11a035b..881d3628c 100644
--- a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs
+++ b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs
@@ -10,7 +10,7 @@ namespace Tax.CountryStateZip.Services
/// <summary>
/// Tax rate service
/// </summary>
- public partial class TaxRateService : ITaxRateService
+ public class TaxRateService : ITaxRateService
{
#region Constants
private const string TAXRATE_ALL_KEY = "Grand.taxrate.all-{0}-{1}";
@@ -69,7 +69,7 @@ namespace Tax.CountryStateZip.Services
/// <returns>Tax rates</returns>
public virtual async Task<IPagedList<TaxRate>> GetAllTaxRates(int pageIndex = 0, int pageSize = int.MaxValue)
{
- string key = string.Format(TAXRATE_ALL_KEY, pageIndex, pageSize);
+ var key = string.Format(TAXRATE_ALL_KEY, pageIndex, pageSize);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from tr in _taxRateRepository.Table
diff --git a/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs b/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
index df7e3e044..39bf5c833 100644
--- a/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
+++ b/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
@@ -51,18 +51,19 @@ namespace Tax.FixedRate.Controllers
[HttpPost]
public async Task<IActionResult> TaxRateUpdate(FixedTaxRateModel model)
{
- string taxCategoryId = model.TaxCategoryId;
- double rate = model.Rate;
+ var taxCategoryId = model.TaxCategoryId;
+ var rate = model.Rate;
- await _settingService.SetSetting(string.Format("Tax.TaxProvider.FixedRate.TaxCategoryId{0}", taxCategoryId), new FixedTaxRate() { Rate = rate });
+ await _settingService.SetSetting($"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}", new FixedTaxRate() { Rate = rate });
return new JsonResult("");
}
[NonAction]
- protected double GetTaxRate(string taxCategoryId)
+ private double GetTaxRate(string taxCategoryId)
{
- var rate = _settingService.GetSettingByKey<FixedTaxRate>(string.Format("Tax.TaxProvider.FixedRate.TaxCategoryId{0}", taxCategoryId))?.Rate;
+ var rate = _settingService.GetSettingByKey<FixedTaxRate>(
+ $"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}")?.Rate;
return rate ?? 0;
}
}
diff --git a/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs b/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs
index 3a32ed74c..556695dda 100644
--- a/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs
+++ b/src/Plugins/Tax.FixedRate/FixedRateTaxProvider.cs
@@ -48,9 +48,10 @@ namespace Tax.FixedRate
/// </summary>
/// <param name="taxCategoryId">The tax category identifier</param>
/// <returns>Tax rate</returns>
- protected double GetTaxRate(string taxCategoryId)
+ private double GetTaxRate(string taxCategoryId)
{
- var rate = _settingService.GetSettingByKey<FixedTaxRate>(string.Format("Tax.TaxProvider.FixedRate.TaxCategoryId{0}", taxCategoryId))?.Rate;
+ var rate = _settingService.GetSettingByKey<FixedTaxRate>(
+ $"Tax.TaxProvider.FixedRate.TaxCategoryId{taxCategoryId}")?.Rate;
return rate ?? 0;
}
diff --git a/src/Plugins/Tax.FixedRate/Manifest.cs b/src/Plugins/Tax.FixedRate/Manifest.cs
index 82b2c3699..050aae708 100644
--- a/src/Plugins/Tax.FixedRate/Manifest.cs
+++ b/src/Plugins/Tax.FixedRate/Manifest.cs
@@ -8,5 +8,5 @@ using Tax.FixedRate;
SystemName = FixedRateTaxDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs b/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
index 7a9022dcc..5e8df8caf 100644
--- a/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
+++ b/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
@@ -37,7 +37,7 @@ namespace Widgets.FacebookPixel.Controllers
{
var stores = await storeService.GetAllStores();
if (stores.Count < 2)
- return stores.FirstOrDefault().Id;
+ return stores.FirstOrDefault()!.Id;
var storeId = workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);
var store = await storeService.GetStoreById(storeId);
@@ -50,15 +50,16 @@ namespace Widgets.FacebookPixel.Controllers
//load settings for a chosen store scope
var storeScope = await GetActiveStore(_storeService, _workContext);
var facebookPixelSettings = _settingService.LoadSetting<FacebookPixelSettings>(storeScope);
- var model = new ConfigurationModel();
- model.PixelId = facebookPixelSettings.PixelId;
- model.PixelScript = facebookPixelSettings.PixelScript;
- model.AddToCartScript = facebookPixelSettings.AddToCartScript;
- model.DetailsOrderScript = facebookPixelSettings.DetailsOrderScript;
- model.AllowToDisableConsentCookie = facebookPixelSettings.AllowToDisableConsentCookie;
- model.ConsentName = facebookPixelSettings.ConsentName;
- model.ConsentDescription = facebookPixelSettings.ConsentDescription;
- model.ConsentDefaultState = facebookPixelSettings.ConsentDefaultState;
+ var model = new ConfigurationModel {
+ PixelId = facebookPixelSettings.PixelId,
+ PixelScript = facebookPixelSettings.PixelScript,
+ AddToCartScript = facebookPixelSettings.AddToCartScript,
+ DetailsOrderScript = facebookPixelSettings.DetailsOrderScript,
+ AllowToDisableConsentCookie = facebookPixelSettings.AllowToDisableConsentCookie,
+ ConsentName = facebookPixelSettings.ConsentName,
+ ConsentDescription = facebookPixelSettings.ConsentDescription,
+ ConsentDefaultState = facebookPixelSettings.ConsentDefaultState
+ };
return View(model);
}
diff --git a/src/Plugins/Widgets.FacebookPixel/Manifest.cs b/src/Plugins/Widgets.FacebookPixel/Manifest.cs
index 33523b3a6..e39dd1e99 100644
--- a/src/Plugins/Widgets.FacebookPixel/Manifest.cs
+++ b/src/Plugins/Widgets.FacebookPixel/Manifest.cs
@@ -8,5 +8,5 @@ using Widgets.FacebookPixel;
SystemName = FacebookPixelDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.00"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
index e3f8b6de7..5ca9afade 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
@@ -27,7 +27,6 @@ namespace Widgets.GoogleAnalytics.Controllers
public WidgetsGoogleAnalyticsController(IWorkContext workContext,
IStoreService storeService,
ISettingService settingService,
- ILogger logger,
ITranslationService translationService)
{
_workContext = workContext;
@@ -39,7 +38,7 @@ namespace Widgets.GoogleAnalytics.Controllers
{
var stores = await storeService.GetAllStores();
if (stores.Count < 2)
- return stores.FirstOrDefault().Id;
+ return stores.FirstOrDefault()!.Id;
var storeId = workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);
var store = await storeService.GetStoreById(storeId);
@@ -52,17 +51,18 @@ namespace Widgets.GoogleAnalytics.Controllers
//load settings for a chosen store scope
var storeScope = await GetActiveStore(_storeService, _workContext);
var googleAnalyticsSettings = _settingService.LoadSetting<GoogleAnalyticsEcommerceSettings>(storeScope);
- var model = new ConfigurationModel();
- model.GoogleId = googleAnalyticsSettings.GoogleId;
- model.TrackingScript = googleAnalyticsSettings.TrackingScript;
- model.EcommerceScript = googleAnalyticsSettings.EcommerceScript;
- model.EcommerceDetailScript = googleAnalyticsSettings.EcommerceDetailScript;
- model.IncludingTax = googleAnalyticsSettings.IncludingTax;
- model.AllowToDisableConsentCookie = googleAnalyticsSettings.AllowToDisableConsentCookie;
- model.ConsentDefaultState = googleAnalyticsSettings.ConsentDefaultState;
- model.ConsentName = googleAnalyticsSettings.ConsentName;
- model.ConsentDescription = googleAnalyticsSettings.ConsentDescription;
- model.StoreScope = storeScope;
+ var model = new ConfigurationModel {
+ GoogleId = googleAnalyticsSettings.GoogleId,
+ TrackingScript = googleAnalyticsSettings.TrackingScript,
+ EcommerceScript = googleAnalyticsSettings.EcommerceScript,
+ EcommerceDetailScript = googleAnalyticsSettings.EcommerceDetailScript,
+ IncludingTax = googleAnalyticsSettings.IncludingTax,
+ AllowToDisableConsentCookie = googleAnalyticsSettings.AllowToDisableConsentCookie,
+ ConsentDefaultState = googleAnalyticsSettings.ConsentDefaultState,
+ ConsentName = googleAnalyticsSettings.ConsentName,
+ ConsentDescription = googleAnalyticsSettings.ConsentDescription,
+ StoreScope = storeScope
+ };
return View(model);
}
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
index 0b90c1f26..99b594e9a 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
@@ -58,8 +58,8 @@ namespace Widgets.GoogleAnalytics.Components
return Content("");
//Special case, if we are in last step of checkout, we can use order total for conversion value
- if (controller.ToString().Equals("checkout", StringComparison.OrdinalIgnoreCase) &&
- action.ToString().Equals("completed", StringComparison.OrdinalIgnoreCase))
+ if (controller.ToString()!.Equals("checkout", StringComparison.OrdinalIgnoreCase) &&
+ action.ToString()!.Equals("completed", StringComparison.OrdinalIgnoreCase))
{
var lastOrder = await GetLastOrder();
globalScript += await GetEcommerceScript(lastOrder);
@@ -106,15 +106,15 @@ namespace Widgets.GoogleAnalytics.Components
var analyticsEcommerceScript = _googleAnalyticsEcommerceSettings.EcommerceScript + "\n";
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{GOOGLEID}", _googleAnalyticsEcommerceSettings.GoogleId);
- analyticsEcommerceScript = analyticsEcommerceScript.Replace("{ORDERID}", order.Id.ToString());
+ analyticsEcommerceScript = analyticsEcommerceScript.Replace("{ORDERID}", order.Id);
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TOTAL}", order.OrderTotal.ToString("0.00", usCulture));
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{CURRENCY}", order.CustomerCurrencyCode);
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TAX}", order.OrderTax.ToString("0.00", usCulture));
var orderShipping = _googleAnalyticsEcommerceSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax;
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{SHIP}", orderShipping.ToString("0.00", usCulture));
analyticsEcommerceScript = analyticsEcommerceScript.Replace("{CITY}", order.BillingAddress == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.City));
- analyticsEcommerceScript = analyticsEcommerceScript.Replace("{STATEPROVINCE}", order.BillingAddress == null || String.IsNullOrEmpty(order.BillingAddress.StateProvinceId) ? "" : FixIllegalJavaScriptChars(state?.Name));
- analyticsEcommerceScript = analyticsEcommerceScript.Replace("{COUNTRY}", order.BillingAddress == null || String.IsNullOrEmpty(order.BillingAddress.CountryId) ? "" : FixIllegalJavaScriptChars(country?.Name));
+ analyticsEcommerceScript = analyticsEcommerceScript.Replace("{STATEPROVINCE}", order.BillingAddress == null || string.IsNullOrEmpty(order.BillingAddress.StateProvinceId) ? "" : FixIllegalJavaScriptChars(state?.Name));
+ analyticsEcommerceScript = analyticsEcommerceScript.Replace("{COUNTRY}", order.BillingAddress == null || string.IsNullOrEmpty(order.BillingAddress.CountryId) ? "" : FixIllegalJavaScriptChars(country?.Name));
var sb = new StringBuilder();
@@ -124,16 +124,16 @@ namespace Widgets.GoogleAnalytics.Components
foreach (var item in order.OrderItems)
{
var product = await productService.GetProductById(item.ProductId);
- string analyticsEcommerceDetailScript = _googleAnalyticsEcommerceSettings.EcommerceDetailScript;
+ var analyticsEcommerceDetailScript = _googleAnalyticsEcommerceSettings.EcommerceDetailScript;
//get category
- string category = "";
+ var category = "";
if (product.ProductCategories.Any())
{
- var defaultProductCategory = await categoryService.GetCategoryById(product.ProductCategories.OrderBy(x => x.DisplayOrder).FirstOrDefault().CategoryId);
+ var defaultProductCategory = await categoryService.GetCategoryById(product.ProductCategories.MinBy(x => x.DisplayOrder).CategoryId);
if (defaultProductCategory != null)
category = defaultProductCategory.Name;
}
- analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{ORDERID}", order.Id.ToString());
+ analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{ORDERID}", order.Id);
//The SKU code is a required parameter for every item that is added to the transaction
analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTSKU}", FixIllegalJavaScriptChars(item.Sku));
analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTID}", FixIllegalJavaScriptChars(item.ProductId));
@@ -156,7 +156,7 @@ namespace Widgets.GoogleAnalytics.Components
private string FixIllegalJavaScriptChars(string text)
{
- if (String.IsNullOrEmpty(text))
+ if (string.IsNullOrEmpty(text))
return text;
//replace ' with \' (http://stackoverflow.com/questions/4292761/need-to-url-encode-labels-when-tracking-events-with-google-analytics)
diff --git a/src/Plugins/Widgets.GoogleAnalytics/GoogleAnalyticPlugin.cs b/src/Plugins/Widgets.GoogleAnalytics/GoogleAnalyticPlugin.cs
index 7a0abb639..8ed08746b 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/GoogleAnalyticPlugin.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/GoogleAnalyticPlugin.cs
@@ -29,18 +29,6 @@ namespace Widgets.GoogleAnalytics
return GoogleAnalyticDefaults.ConfigurationUrl;
}
- /// <summary>
- /// Gets widget zones where this widget should be rendered
- /// </summary>
- /// <returns>Widget zones</returns>
- public IList<string> GetWidgetZones()
- {
- return new List<string>
- {
- "body_end_html_tag_before", "clean_body_end_html_tag_before"
- };
- }
-
/// <summary>
/// Install plugin
/// </summary>
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Manifest.cs b/src/Plugins/Widgets.GoogleAnalytics/Manifest.cs
index 473e0f678..0679acc64 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Manifest.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Manifest.cs
@@ -8,5 +8,5 @@ using Widgets.GoogleAnalytics;
SystemName = GoogleAnalyticDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.01"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Widgets.Slider/Areas/Admin/Controllers/WidgetsSliderController.cs b/src/Plugins/Widgets.Slider/Areas/Admin/Controllers/WidgetsSliderController.cs
index a531b1b92..0a85fb444 100644
--- a/src/Plugins/Widgets.Slider/Areas/Admin/Controllers/WidgetsSliderController.cs
+++ b/src/Plugins/Widgets.Slider/Areas/Admin/Controllers/WidgetsSliderController.cs
@@ -42,10 +42,11 @@ namespace Widgets.Slider.Areas.Admin.Controllers
}
public IActionResult Configure()
{
- var model = new ConfigurationModel();
- model.DisplayOrder = _sliderWidgetSettings.DisplayOrder;
- model.CustomerGroups = _sliderWidgetSettings.LimitedToGroups?.ToArray();
- model.Stores = _sliderWidgetSettings.LimitedToStores?.ToArray();
+ var model = new ConfigurationModel {
+ DisplayOrder = _sliderWidgetSettings.DisplayOrder,
+ CustomerGroups = _sliderWidgetSettings.LimitedToGroups?.ToArray(),
+ Stores = _sliderWidgetSettings.LimitedToStores?.ToArray()
+ };
return View(model);
}
diff --git a/src/Plugins/Widgets.Slider/Assets/vue-style.css b/src/Plugins/Widgets.Slider/Assets/vue-style.css
index 72772b988..48254d044 100644
--- a/src/Plugins/Widgets.Slider/Assets/vue-style.css
+++ b/src/Plugins/Widgets.Slider/Assets/vue-style.css
@@ -1,123 +1,137 @@
-#GrandCarousel .carousel-item {
- background-color: #E8E9EA;
-}
- #GrandCarousel .carousel-item .carousel-caption {
- position: absolute;
- top: 0;
- right: 0;
- bottom: 0;
- left: 0;
- padding: 0;
-}
- #GrandCarousel .carousel-indicators li {
- background-color: #555;
-}
- #GrandCarousel .carousel-item .carousel-caption .slideRow {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
-}
- #GrandCarousel .carousel-item .slide-title h2 {
- font-size: 38px;
- font-weight: 300;
- color: #1D1F20;
-}
- #GrandCarousel .carousel-item .slide-content {
- font-size: 20px;
- font-weight: 300;
- color: #000;
- text-align: left;
-}
- #GrandCarousel .carousel-item .slide-price .actual {
- font-size: 32px;
- font-weight: 500;
- color: #1d1f20;
- margin-right: 15px;
- margin-bottom: 0;
-}
- #GrandCarousel .carousel-item .slide-price .old-price {
- font-size: 24px;
- font-weight: 300;
- color: #888;
- text-decoration: line-through;
- margin-bottom: 0;
-}
- #GrandCarousel .carousel-item .animate-top {
- color: #000;
- font-size: 30px;
- font-weight: 300;
- line-height: 1;
- opacity: .9;
- padding: 15px 0 0 0;
-}
- #GrandCarousel .carousel-item .animate-center-title {
- color: #000;
- font-size: 56px;
- font-weight: 500;
- line-height: 1;
- opacity: .9
-}
- #GrandCarousel .carousel-item .animate-center-content {
- color: #000;
- font-size: 26px;
- font-weight: 500;
- opacity: .9;
- padding: 0 0 15px 0;
-}
- #GrandCarousel .carousel-item .animate-bottom.btn {
- width: 100%;
- margin: 15px 0 0 0;
- color: #fff;
- background-color: #87C255;
- border-color: #87C255;
-}
- #GrandCarousel .carousel-item .slide-button {
- display: table;
-}
- .animate__delay-05s {
- -webkit-animation-delay: 0.5s;
- animation-delay: 0.5s;
- -webkit-animation-delay: calc(var(--animate-delay)*0.5);
- animation-delay: calc(var(--animate-delay)*0.5);
-}
- .animate__delay-15s {
- -webkit-animation-delay: 1.5s;
- animation-delay: 1.5s;
- -webkit-animation-delay: calc(var(--animate-delay)*1.5);
- animation-delay: calc(var(--animate-delay)*1.5);
-}
- .animate__delay-25s {
- -webkit-animation-delay: 2.5s;
- animation-delay: 2.5s;
- -webkit-animation-delay: calc(var(--animate-delay)*2.5);
- animation-delay: calc(var(--animate-delay)*2.5);
-}
- @media (max-width: 1199px) {
- #GrandCarousel .carousel-item .slide-content {
- display: none;
+#GrandCarousel .carousel-item .carousel-caption {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ padding: 0;
+}
+
+#GrandCarousel .carousel-indicators li {
+ background-color: #555;
+}
+
+#GrandCarousel .carousel-item .carousel-caption .slideRow {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+}
+
+#GrandCarousel .carousel-item .slide-title h2 {
+ font-size: 38px;
+ font-weight: 300;
+ color: #1D1F20;
+}
+
+#GrandCarousel .carousel-item .slide-content {
+ font-size: 20px;
+ font-weight: 300;
+ color: #000;
+ text-align: left;
+}
+
+#GrandCarousel .carousel-item .slide-price .actual {
+ font-size: 32px;
+ font-weight: 500;
+ color: #1d1f20;
+ margin-right: 15px;
+ margin-bottom: 0;
+}
+
+#GrandCarousel .carousel-item .slide-price .old-price {
+ font-size: 24px;
+ font-weight: 300;
+ color: #888;
+ text-decoration: line-through;
+ margin-bottom: 0;
+}
+
+#GrandCarousel .carousel-item .animate-top {
+ color: #000;
+ font-size: 30px;
+ font-weight: 300;
+ line-height: 1;
+ opacity: .9;
+ padding: 15px 0 0 0;
+}
+
+#GrandCarousel .carousel-item .animate-center-title {
+ color: #000;
+ font-size: 56px;
+ font-weight: 500;
+ line-height: 1;
+ opacity: .9
+}
+
+#GrandCarousel .carousel-item .animate-center-content {
+ color: #000;
+ font-size: 26px;
+ font-weight: 500;
+ opacity: .9;
+ padding: 0 0 15px 0;
+}
+
+#GrandCarousel .carousel-item .animate-bottom.btn {
+ width: 100%;
+ margin: 15px 0 0 0;
+ color: #fff;
+ background-color: #87C255;
+ border-color: #87C255;
+}
+
+#GrandCarousel .carousel-item .slide-button {
+ display: table;
+}
+
+.animate__delay-05s {
+ -webkit-animation-delay: 0.5s;
+ animation-delay: 0.5s;
+ -webkit-animation-delay: calc(var(--animate-delay) * 0.5);
+ animation-delay: calc(var(--animate-delay) * 0.5);
+}
+
+.animate__delay-15s {
+ -webkit-animation-delay: 1.5s;
+ animation-delay: 1.5s;
+ -webkit-animation-delay: calc(var(--animate-delay) * 1.5);
+ animation-delay: calc(var(--animate-delay) * 1.5);
+}
+
+.animate__delay-25s {
+ -webkit-animation-delay: 2.5s;
+ animation-delay: 2.5s;
+ -webkit-animation-delay: calc(var(--animate-delay) * 2.5);
+ animation-delay: calc(var(--animate-delay) * 2.5);
+}
+
+@media (max-width: 1199px) {
+ #GrandCarousel .carousel-item .slide-content {
+ display: none;
}
}
- @media (max-width: 991px) {
- #GrandCarousel .carousel-item .slide-title h2 {
- font-size: 28px;
+
+@media (max-width: 991px) {
+ #GrandCarousel .carousel-item .slide-title h2 {
+ font-size: 28px;
}
}
- @media (max-width: 767px) {
- #GrandCarousel {
- display: none;
+
+@media (max-width: 767px) {
+ #GrandCarousel {
+ display: none;
}
}
- [dark-theme="true"] #GrandCarousel .carousel-item {
- background-color: #2d3133;
+
+[dark-theme="true"] #GrandCarousel .carousel-item .slide-title h2, [dark-theme="true"] #GrandCarousel .carousel-item .slide-price .actual, [dark-theme="true"] #GrandCarousel .carousel-item .animate-top, [dark-theme="true"] #GrandCarousel .carousel-item .animate-center-title, [dark-theme="true"] #GrandCarousel .carousel-item .animate-center-content, [dark-theme="true"] #GrandCarousel .carousel-item .animate-bottom {
+ color: #fff;
}
- [dark-theme="true"] #GrandCarousel .carousel-item .slide-title h2, [dark-theme="true"] #GrandCarousel .carousel-item .slide-price .actual, [dark-theme="true"] #GrandCarousel .carousel-item .animate-top, [dark-theme="true"] #GrandCarousel .carousel-item .animate-center-title, [dark-theme="true"] #GrandCarousel .carousel-item .animate-center-content, [dark-theme="true"] #GrandCarousel .carousel-item .animate-bottom {
- color: #fff;
+
+[dark-theme="true"] #GrandCarousel .carousel-item .slide-content {
+ color: #dfdfdf;
}
- [dark-theme="true"] #GrandCarousel .carousel-item .slide-content {
- color: #dfdfdf;
-}
- [dark-theme="true"] #GrandCarousel .carousel-indicators li {
- background-color: #fff;
+
+[dark-theme="true"] #GrandCarousel .carousel-indicators li {
+ background-color: #fff;
}
diff --git a/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs b/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
index aff8aecf6..7edf5bcd6 100644
--- a/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
+++ b/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
@@ -26,18 +26,16 @@ namespace Widgets.Slider.ViewComponents
_workContext = workContext;
}
- protected async Task<string> GetPictureUrl(string pictureId)
+ private async Task<string> GetPictureUrl(string pictureId)
{
- var url = await _pictureService.GetPictureUrl(pictureId, showDefaultPicture: false);
- if (url == null)
- url = "";
+ var url = await _pictureService.GetPictureUrl(pictureId, showDefaultPicture: false) ?? "";
return url;
}
- protected async Task PrepareModel(IList<PictureSlider> sliders, PublicInfoModel model)
+ private async Task PrepareModel(IList<PictureSlider> sliders, PublicInfoModel model)
{
- int i = 1;
+ var i = 1;
foreach (var item in sliders.OrderBy(x => x.DisplayOrder))
{
model.Slide.Add(new PublicInfoModel.Slider() {
diff --git a/src/Plugins/Widgets.Slider/Domain/PictureSlider.cs b/src/Plugins/Widgets.Slider/Domain/PictureSlider.cs
index 5ca0920d4..4972ced75 100644
--- a/src/Plugins/Widgets.Slider/Domain/PictureSlider.cs
+++ b/src/Plugins/Widgets.Slider/Domain/PictureSlider.cs
@@ -4,7 +4,7 @@ using Grand.Domain.Stores;
namespace Widgets.Slider.Domain
{
- public partial class PictureSlider : BaseEntity, ITranslationEntity, IStoreLinkEntity
+ public class PictureSlider : BaseEntity, ITranslationEntity, IStoreLinkEntity
{
public PictureSlider()
{
diff --git a/src/Plugins/Widgets.Slider/Extensions.cs b/src/Plugins/Widgets.Slider/Extensions.cs
index 525383d9b..a7bf28f6c 100644
--- a/src/Plugins/Widgets.Slider/Extensions.cs
+++ b/src/Plugins/Widgets.Slider/Extensions.cs
@@ -34,7 +34,7 @@ namespace Widgets.Slider
PropertyInfo[] props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
foreach (var prop in props)
{
- bool insert = true;
+ var insert = true;
foreach (var i in interfaces)
{
@@ -49,7 +49,7 @@ namespace Widgets.Slider
{
LanguageId = item.LanguageId,
LocaleKey = prop.Name,
- LocaleValue = prop.GetValue(item).ToString(),
+ LocaleValue = prop.GetValue(item)?.ToString(),
});
}
}
diff --git a/src/Plugins/Widgets.Slider/Infrastructure/Mapper/SliderMapperConfiguration.cs b/src/Plugins/Widgets.Slider/Infrastructure/Mapper/SliderMapperConfiguration.cs
index 979cc4840..133e5b0b7 100644
--- a/src/Plugins/Widgets.Slider/Infrastructure/Mapper/SliderMapperConfiguration.cs
+++ b/src/Plugins/Widgets.Slider/Infrastructure/Mapper/SliderMapperConfiguration.cs
@@ -7,43 +7,30 @@ namespace Widgets.Slider.Infrastructure.Mapper
{
public class SliderMapperConfiguration : Profile, IAutoMapperProfile
{
- protected string SetObjectEntry(SlideModel model)
+ private string SetObjectEntry(SlideModel model)
{
- if (model.SliderTypeId == (int)SliderType.HomePage)
- return "";
-
- if (model.SliderTypeId == (int)SliderType.Category)
- return model.CategoryId;
-
- if (model.SliderTypeId == (int)SliderType.Collection)
- return model.CollectionId;
-
- if (model.SliderTypeId == (int)SliderType.Brand)
- return model.BrandId;
-
- return "";
+ return model.SliderTypeId switch {
+ (int)SliderType.HomePage => "",
+ (int)SliderType.Category => model.CategoryId,
+ (int)SliderType.Collection => model.CollectionId,
+ (int)SliderType.Brand => model.BrandId,
+ _ => ""
+ };
}
- protected string GetCategoryId(PictureSlider pictureSlider)
- {
- if (pictureSlider.SliderTypeId == SliderType.Category)
- return pictureSlider.ObjectEntry;
- return "";
+ private string GetCategoryId(PictureSlider pictureSlider)
+ {
+ return pictureSlider.SliderTypeId == SliderType.Category ? pictureSlider.ObjectEntry : "";
}
- protected string GetCollectionId(PictureSlider pictureSlider)
+ private string GetCollectionId(PictureSlider pictureSlider)
{
- if (pictureSlider.SliderTypeId == SliderType.Collection)
- return pictureSlider.ObjectEntry;
-
- return "";
+ return pictureSlider.SliderTypeId == SliderType.Collection ? pictureSlider.ObjectEntry : "";
}
- protected string GetBrandId(PictureSlider pictureSlider)
- {
- if (pictureSlider.SliderTypeId == SliderType.Brand)
- return pictureSlider.ObjectEntry;
- return "";
+ private string GetBrandId(PictureSlider pictureSlider)
+ {
+ return pictureSlider.SliderTypeId == SliderType.Brand ? pictureSlider.ObjectEntry : "";
}
public SliderMapperConfiguration()
@@ -67,9 +54,6 @@ namespace Widgets.Slider.Infrastructure.Mapper
.ForMember(dest => dest.UserFields, mo => mo.Ignore())
.ForMember(dest => dest.PictureUrl, mo => mo.Ignore());
}
- public int Order
- {
- get { return 0; }
- }
+ public int Order => 0;
}
}
diff --git a/src/Plugins/Widgets.Slider/Manifest.cs b/src/Plugins/Widgets.Slider/Manifest.cs
index 3bc4f79b2..fdeb546a4 100644
--- a/src/Plugins/Widgets.Slider/Manifest.cs
+++ b/src/Plugins/Widgets.Slider/Manifest.cs
@@ -8,5 +8,5 @@ using Widgets.Slider;
SystemName = SliderWidgetDefaults.ProviderSystemName,
SupportedVersion = GrandVersion.SupportedPluginVersion,
Author = "grandnode team",
- Version = "1.01"
+ Version = "2.1.1"
)]
\ No newline at end of file
diff --git a/src/Plugins/Widgets.Slider/Models/SlideModel.cs b/src/Plugins/Widgets.Slider/Models/SlideModel.cs
index 8403fdb45..ee6ec9431 100644
--- a/src/Plugins/Widgets.Slider/Models/SlideModel.cs
+++ b/src/Plugins/Widgets.Slider/Models/SlideModel.cs
@@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations;
namespace Widgets.Slider.Models
{
- public partial class SlideModel : BaseEntityModel, ILocalizedModel<SlideLocalizedModel>, IStoreLinkModel
+ public class SlideModel : BaseEntityModel, ILocalizedModel<SlideLocalizedModel>, IStoreLinkModel
{
public SlideModel()
{
@@ -57,7 +57,7 @@ namespace Widgets.Slider.Models
}
- public partial class SlideLocalizedModel : ILocalizedModelLocal
+ public class SlideLocalizedModel : ILocalizedModelLocal
{
public string LanguageId { get; set; }
diff --git a/src/Plugins/Widgets.Slider/Services/ISliderService.cs b/src/Plugins/Widgets.Slider/Services/ISliderService.cs
index 8ed4bf97f..19b51a58e 100644
--- a/src/Plugins/Widgets.Slider/Services/ISliderService.cs
+++ b/src/Plugins/Widgets.Slider/Services/ISliderService.cs
@@ -2,7 +2,7 @@
namespace Widgets.Slider.Services
{
- public partial interface ISliderService
+ public interface ISliderService
{
/// <summary>
/// Delete a slider
@@ -40,11 +40,5 @@ namespace Widgets.Slider.Services
/// </summary>
/// <param name="slide">Picture Slider</param>
Task UpdatePictureSlider(PictureSlider slide);
-
- /// <summary>
- /// Delete slide
- /// </summary>
- /// <param name="slide">Picture Slider</param>
- Task DeletePictureSlider(PictureSlider slide);
}
}
diff --git a/src/Plugins/Widgets.Slider/Services/SliderService.cs b/src/Plugins/Widgets.Slider/Services/SliderService.cs
index 912a0abe7..27e139819 100644
--- a/src/Plugins/Widgets.Slider/Services/SliderService.cs
+++ b/src/Plugins/Widgets.Slider/Services/SliderService.cs
@@ -6,11 +6,11 @@ using Widgets.Slider.Domain;
namespace Widgets.Slider.Services
{
- public partial class SliderService : ISliderService
+ public class SliderService : ISliderService
{
#region Fields
- private readonly IRepository<PictureSlider> _reporistoryPictureSlider;
+ private readonly IRepository<PictureSlider> _repositoryPictureSlider;
private readonly IAclService _aclService;
private readonly IWorkContext _workContext;
private readonly ICacheBase _cacheBase;
@@ -23,16 +23,17 @@ namespace Widgets.Slider.Services
/// {1} : Slider type
/// {2} : Object entry / categoryId || collectionId
/// </remarks>
- public const string SLIDERS_MODEL_KEY = "Grand.slider-{0}-{1}-{2}";
- public const string SLIDERS_PATTERN_KEY = "Grand.slider";
+ private const string SLIDERS_MODEL_KEY = "Grand.slider-{0}-{1}-{2}";
+
+ private const string SLIDERS_PATTERN_KEY = "Grand.slider";
#endregion
- public SliderService(IRepository<PictureSlider> reporistoryPictureSlider,
+ public SliderService(IRepository<PictureSlider> repositoryPictureSlider,
IWorkContext workContext, IAclService aclService,
ICacheBase cacheManager)
{
- _reporistoryPictureSlider = reporistoryPictureSlider;
+ _repositoryPictureSlider = repositoryPictureSlider;
_workContext = workContext;
_aclService = aclService;
_cacheBase = cacheManager;
@@ -41,15 +42,15 @@ namespace Widgets.Slider.Services
/// Delete a slider
/// </summary>
/// <param name="slider">Slider</param>
- public virtual async Task DeleteSlider(PictureSlider slide)
+ public virtual async Task DeleteSlider(PictureSlider slider)
{
- if (slide == null)
- throw new ArgumentNullException(nameof(slide));
+ if (slider == null)
+ throw new ArgumentNullException(nameof(slider));
//clear cache
await _cacheBase.RemoveByPrefix(SLIDERS_PATTERN_KEY);
- await _reporistoryPictureSlider.DeleteAsync(slide);
+ await _repositoryPictureSlider.DeleteAsync(slider);
}
/// <summary>
@@ -58,7 +59,7 @@ namespace Widgets.Slider.Services
/// <returns>Picture Sliders</returns>
public virtual async Task<IList<PictureSlider>> GetPictureSliders()
{
- return await Task.FromResult(_reporistoryPictureSlider.Table.OrderBy(x => x.SliderTypeId).ThenBy(x => x.DisplayOrder).ToList());
+ return await Task.FromResult(_repositoryPictureSlider.Table.OrderBy(x => x.SliderTypeId).ThenBy(x => x.DisplayOrder).ToList());
}
/// <summary>
@@ -67,10 +68,10 @@ namespace Widgets.Slider.Services
/// <returns>Picture Sliders</returns>
public virtual async Task<IList<PictureSlider>> GetPictureSliders(SliderType sliderType, string objectEntry = "")
{
- string cacheKey = string.Format(SLIDERS_MODEL_KEY, _workContext.CurrentStore.Id, sliderType.ToString(), objectEntry);
+ var cacheKey = string.Format(SLIDERS_MODEL_KEY, _workContext.CurrentStore.Id, sliderType.ToString(), objectEntry);
return await _cacheBase.GetAsync(cacheKey, async () =>
{
- var query = from s in _reporistoryPictureSlider.Table
+ var query = from s in _repositoryPictureSlider.Table
where s.SliderTypeId == sliderType && s.Published
select s;
@@ -90,7 +91,7 @@ namespace Widgets.Slider.Services
/// <returns>Tax rate</returns>
public virtual Task<PictureSlider> GetById(string slideId)
{
- return _reporistoryPictureSlider.GetByIdAsync(slideId);
+ return _repositoryPictureSlider.GetByIdAsync(slideId);
}
/// <summary>
@@ -105,7 +106,7 @@ namespace Widgets.Slider.Services
//clear cache
await _cacheBase.RemoveByPrefix(SLIDERS_PATTERN_KEY);
- await _reporistoryPictureSlider.InsertAsync(slide);
+ await _repositoryPictureSlider.InsertAsync(slide);
}
/// <summary>
@@ -120,7 +121,7 @@ namespace Widgets.Slider.Services
//clear cache
await _cacheBase.RemoveByPrefix(SLIDERS_PATTERN_KEY);
- await _reporistoryPictureSlider.UpdateAsync(slide);
+ await _repositoryPictureSlider.UpdateAsync(slide);
}
/// <summary>
@@ -135,7 +136,7 @@ namespace Widgets.Slider.Services
//clear cache
await _cacheBase.RemoveByPrefix(SLIDERS_PATTERN_KEY);
- await _reporistoryPictureSlider.DeleteAsync(slide);
+ await _repositoryPictureSlider.DeleteAsync(slide);
}
}
diff --git a/src/Plugins/Widgets.Slider/SliderWidgetPlugin.cs b/src/Plugins/Widgets.Slider/SliderWidgetPlugin.cs
index 99db25a39..36e35cf8a 100644
--- a/src/Plugins/Widgets.Slider/SliderWidgetPlugin.cs
+++ b/src/Plugins/Widgets.Slider/SliderWidgetPlugin.cs
@@ -9,7 +9,7 @@ using Widgets.Slider.Domain;
namespace Widgets.Slider
{
/// <summary>
- /// PLugin
+ /// Plugin
/// </summary>
public class SliderWidgetPlugin : BasePlugin, IPlugin
{
@@ -42,8 +42,8 @@ namespace Widgets.Slider
//pictures
var sampleImagesPath = CommonPath.MapPath("Plugins/Widgets.Slider/Assets/slider/sample-images/");
- var byte1 = File.ReadAllBytes(sampleImagesPath + "banner1.png");
- var byte2 = File.ReadAllBytes(sampleImagesPath + "banner2.png");
+ var byte1 = await File.ReadAllBytesAsync(sampleImagesPath + "banner1.png");
+ var byte2 = await File.ReadAllBytesAsync(sampleImagesPath + "banner2.png");
var pictureSlider1 = new PictureSlider()
{
diff --git a/src/Plugins/Widgets.Slider/Views/Shared/Components/WidgetSlider/Default.cshtml b/src/Plugins/Widgets.Slider/Views/Shared/Components/WidgetSlider/Default.cshtml
index 98ed376a9..fc895c4ab 100644
--- a/src/Plugins/Widgets.Slider/Views/Shared/Components/WidgetSlider/Default.cshtml
+++ b/src/Plugins/Widgets.Slider/Views/Shared/Components/WidgetSlider/Default.cshtml
@@ -1,18 +1,6 @@
@model Widgets.Slider.Models.PublicInfoModel
<link rel="stylesheet" type="text/css" asp-src="/Plugins/Widgets.Slider/Assets/vue-style.css" />
-<script asp-location="Header">
- document.addEventListener('DOMContentLoaded', function () {
- // fire if first slide has set full width
- if (document.querySelector('#GrandCarousel .carousel-item').getAttribute('data-width') == 'full') {
- var mainContainer = document.querySelector(".main-container");
- var GrandCarousel = document.getElementById("GrandCarousel");
- var parentDiv = mainContainer.parentNode;
-
- parentDiv.insertBefore(GrandCarousel, mainContainer);
- }
- });
-</script>
<b-carousel id="GrandCarousel" fade controls indicators img-width="1024" img-height="267" :interval="6000">
@foreach (var item in Model.Slide)