Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Fix 404 when a store owner opens a shipping provider's configuration (#838)
Krzysztof Pajak4f8e654b15c3
diff --git a/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs b/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.csindex 758218bbe..35d5c4cbf 100644--- a/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs+++ b/src/Plugins/Shipping.ByWeight/Areas/Admin/Controllers/ShippingByWeightController.cs@@ -92,7 +92,8 @@ public class ShippingByWeightController : BaseShippingController[AutoValidateAntiforgeryToken]public async Task<IActionResult> RatesList(DataSourceRequest command){- var records = await _shippingByWeightService.GetAll(command.Page - 1, command.PageSize);+ //main admin sees the records of every store+ var records = await _shippingByWeightService.GetAll("", command.Page - 1, command.PageSize);var sbwModel = new List<ShippingByWeightModel>();foreach (var x in records)diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Controllers/ShippingByWeightController.cs b/src/Plugins/Shipping.ByWeight/Areas/Store/Controllers/ShippingByWeightController.csnew file mode 100644index 000000000..c48f82d2d--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Controllers/ShippingByWeightController.cs@@ -0,0 +1,351 @@+using Grand.Business.Core.Interfaces.Catalog.Directory;+using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Directory;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Rendering;+using Shipping.ByWeight.Domain;+using Shipping.ByWeight.Models;+using Shipping.ByWeight.Services;+using System.Text;++namespace Shipping.ByWeight.Areas.Store.Controllers;++/// <summary>+/// Store-manager configuration of the "by weight" shipping rate provider.+/// A store owner can add, edit and delete rate records, but only the ones that belong+/// to his own store (<see cref="CurrentStoreId" />). Records owned by other stores or+/// global (store = *) records are never returned nor mutated, and the plugin settings+/// are saved as a per-store override rather than system wide.+/// </summary>+[Area("Store")]+[AuthorizeStore]+[AuthorizeMenu]+[PermissionAuthorize(PermissionSystemName.ShippingSettings)]+public class ShippingByWeightController : BaseController+{+ private readonly IContextAccessor _contextAccessor;+ private readonly ICountryService _countryService;+ private readonly ICurrencyService _currencyService;+ private readonly CurrencySettings _currencySettings;+ private readonly IMeasureService _measureService;+ private readonly MeasureSettings _measureSettings;+ private readonly ISettingService _settingService;+ private readonly IShippingByWeightService _shippingByWeightService;+ private readonly IShippingMethodService _shippingMethodService;+ private readonly ITranslationService _translationService;+ private readonly IWarehouseService _warehouseService;++ public ShippingByWeightController(+ IWarehouseService warehouseService,+ IShippingMethodService shippingMethodService,+ ICountryService countryService,+ IShippingByWeightService shippingByWeightService,+ ISettingService settingService,+ ITranslationService translationService,+ ICurrencyService currencyService,+ CurrencySettings currencySettings,+ IMeasureService measureService,+ MeasureSettings measureSettings,+ IContextAccessor contextAccessor)+ {+ _warehouseService = warehouseService;+ _shippingMethodService = shippingMethodService;+ _countryService = countryService;+ _shippingByWeightService = shippingByWeightService;+ _settingService = settingService;+ _translationService = translationService;+ _currencyService = currencyService;+ _currencySettings = currencySettings;+ _measureService = measureService;+ _measureSettings = measureSettings;+ _contextAccessor = contextAccessor;+ }++ /// <summary>+ /// The store the current staff/store-manager is bound to.+ /// </summary>+ private string CurrentStoreId => _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ public async Task<IActionResult> Configure()+ {+ //per-store override of the plugin settings - the global values are the fallback+ var settings = await _settingService.LoadSetting<ByWeightShippingSettings>(CurrentStoreId);++ var model = new ShippingByWeightListModel {+ LimitMethodsToCreated = settings.LimitMethodsToCreated,+ DisplayOrder = settings.DisplayOrder+ };++ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> SaveGeneralSettings(ShippingByWeightListModel model)+ {+ var settings = await _settingService.LoadSetting<ByWeightShippingSettings>(CurrentStoreId);+ settings.LimitMethodsToCreated = model.LimitMethodsToCreated;+ settings.DisplayOrder = model.DisplayOrder;++ //save as a per-store override - never touch the system-wide value+ await _settingService.SaveSetting(settings, CurrentStoreId);++ return Json(new { Result = true });+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> RatesList(DataSourceRequest command)+ {+ //only the current store records - filtered and paged in the service layer+ var records = await _shippingByWeightService.GetAll(CurrentStoreId, command.Page - 1, command.PageSize);++ var sbwModel = new List<ShippingByWeightModel>();+ foreach (var x in records)+ {+ var m = new ShippingByWeightModel {+ Id = x.Id,+ StoreId = x.StoreId,+ WarehouseId = x.WarehouseId,+ ShippingMethodId = x.ShippingMethodId,+ CountryId = x.CountryId,+ From = x.From,+ To = x.To,+ AdditionalFixedCost = x.AdditionalFixedCost,+ PercentageRateOfSubtotal = x.PercentageRateOfSubtotal,+ RatePerWeightUnit = x.RatePerWeightUnit,+ LowerWeightLimit = x.LowerWeightLimit+ };+ //shipping method+ var shippingMethod = await _shippingMethodService.GetShippingMethodById(x.ShippingMethodId);+ m.ShippingMethodName = shippingMethod != null ? shippingMethod.Name : "Unavailable";+ //warehouse+ var warehouse = await _warehouseService.GetWarehouseById(x.WarehouseId);+ m.WarehouseName = warehouse != null ? warehouse.Name : "*";+ //country+ var c = await _countryService.GetCountryById(x.CountryId);+ m.CountryName = c != null ? c.Name : "*";+ //state+ var s = c?.StateProvinces.FirstOrDefault(y => y.Id == x.StateProvinceId);+ m.StateProvinceName = s != null ? s.Name : "*";+ //zip+ m.Zip = !string.IsNullOrEmpty(x.Zip) ? x.Zip : "*";++ var htmlSb = new StringBuilder("<div>");+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.From")}: {m.From}");+ htmlSb.Append("<br />");+ htmlSb.Append($"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.To")}: {m.To}");+ htmlSb.Append("<br />");+ htmlSb.Append(+ $"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.AdditionalFixedCost")}: {m.AdditionalFixedCost}");+ htmlSb.Append("<br />");+ htmlSb.Append(+ $"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.RatePerWeightUnit")}: {m.RatePerWeightUnit}");+ htmlSb.Append("<br />");+ htmlSb.Append(+ $"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.LowerWeightLimit")}: {m.LowerWeightLimit}");+ htmlSb.Append("<br />");+ htmlSb.Append(+ $"{_translationService.GetResource("Plugins.Shipping.ByWeight.Fields.PercentageRateOfSubtotal")}: {m.PercentageRateOfSubtotal}");+ htmlSb.Append("</div>");+ m.DataHtml = htmlSb.ToString();++ sbwModel.Add(m);+ }++ var gridModel = new DataSourceResult {+ Data = sbwModel,+ Total = records.TotalCount+ };++ return Json(gridModel);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ public async Task<IActionResult> RateDelete(string id)+ {+ var sbw = await _shippingByWeightService.GetById(id);+ //guard: a store owner can only delete his own store records+ if (sbw == null || sbw.StoreId != CurrentStoreId)+ return new JsonResult("");++ await _shippingByWeightService.DeleteShippingByWeightRecord(sbw);++ return new JsonResult("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> AddPopup()+ {+ var model = new ShippingByWeightModel {+ //the owner cannot create records for another store+ StoreId = CurrentStoreId,+ //CurrencySettings is resolved per current store, so this already honours a store override+ PrimaryStoreCurrencyCode =+ (await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode,+ BaseWeightIn = (await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)).Name,+ To = 1000000+ };++ var shippingMethods = await _shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);+ if (shippingMethods.Count == 0)+ return Content("No shipping methods can be loaded");++ await PrepareSelectLists(model, shippingMethods, null, null, null);++ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> AddPopup(ShippingByWeightModel model)+ {+ var sbw = new ShippingByWeightRecord {+ //force the current store - the owner cannot create records for another store+ StoreId = CurrentStoreId,+ WarehouseId = model.WarehouseId,+ CountryId = model.CountryId,+ StateProvinceId = model.StateProvinceId,+ Zip = model.Zip == "*" ? null : model.Zip,+ ShippingMethodId = model.ShippingMethodId,+ From = model.From,+ To = model.To,+ AdditionalFixedCost = model.AdditionalFixedCost,+ RatePerWeightUnit = model.RatePerWeightUnit,+ PercentageRateOfSubtotal = model.PercentageRateOfSubtotal,+ LowerWeightLimit = model.LowerWeightLimit+ };+ await _shippingByWeightService.InsertShippingByWeightRecord(sbw);++ ViewBag.RefreshPage = true;++ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ public async Task<IActionResult> EditPopup(string id)+ {+ var sbw = await _shippingByWeightService.GetById(id);+ //guard: a store owner can only open his own store records+ if (sbw == null || sbw.StoreId != CurrentStoreId)+ return RedirectToAction("Configure");++ var model = new ShippingByWeightModel {+ Id = sbw.Id,+ StoreId = sbw.StoreId,+ WarehouseId = sbw.WarehouseId,+ CountryId = sbw.CountryId,+ StateProvinceId = sbw.StateProvinceId,+ Zip = sbw.Zip,+ ShippingMethodId = sbw.ShippingMethodId,+ From = sbw.From,+ To = sbw.To,+ AdditionalFixedCost = sbw.AdditionalFixedCost,+ PercentageRateOfSubtotal = sbw.PercentageRateOfSubtotal,+ RatePerWeightUnit = sbw.RatePerWeightUnit,+ LowerWeightLimit = sbw.LowerWeightLimit,+ //CurrencySettings is resolved per current store, so this already honours a store override+ PrimaryStoreCurrencyCode =+ (await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode,+ BaseWeightIn = (await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)).Name+ };++ var shippingMethods = await _shippingMethodService.GetAllShippingMethods(storeId: CurrentStoreId);+ if (shippingMethods.Count == 0)+ return Content("No shipping methods can be loaded");++ await PrepareSelectLists(model, shippingMethods, sbw.WarehouseId, sbw.ShippingMethodId, sbw.CountryId,+ sbw.StateProvinceId);++ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> EditPopup(ShippingByWeightModel model)+ {+ var sbw = await _shippingByWeightService.GetById(model.Id);+ //guard: a store owner can only edit his own store records+ if (sbw == null || sbw.StoreId != CurrentStoreId)+ return RedirectToAction("Configure");++ //StoreId is deliberately not taken from the model - the record stays in the owner's store+ sbw.WarehouseId = model.WarehouseId;+ sbw.CountryId = model.CountryId;+ sbw.StateProvinceId = model.StateProvinceId;+ sbw.Zip = model.Zip == "*" ? null : model.Zip;+ sbw.ShippingMethodId = model.ShippingMethodId;+ sbw.From = model.From;+ sbw.To = model.To;+ sbw.AdditionalFixedCost = model.AdditionalFixedCost;+ sbw.RatePerWeightUnit = model.RatePerWeightUnit;+ sbw.PercentageRateOfSubtotal = model.PercentageRateOfSubtotal;+ sbw.LowerWeightLimit = model.LowerWeightLimit;+ await _shippingByWeightService.UpdateShippingByWeightRecord(sbw);++ ViewBag.RefreshPage = true;++ return View(model);+ }++ /// <summary>+ /// Fills the drop-downs of the add/edit form. No store selector is offered - the record+ /// always belongs to the owner's own store - and warehouses are limited to the ones the+ /// store may use (its own, plus the ones shared by every store).+ /// </summary>+ [NonAction]+ private async Task PrepareSelectLists(ShippingByWeightModel model,+ IList<Grand.Domain.Shipping.ShippingMethod> shippingMethods,+ string selectedWarehouseId, string selectedShippingMethodId, string selectedCountryId,+ string selectedStateProvinceId = null)+ {+ //warehouses+ model.AvailableWarehouses.Add(new SelectListItem { Text = "*", Value = "" });+ var warehouses = (await _warehouseService.GetAllWarehouses())+ .Where(x => string.IsNullOrEmpty(x.StoreId) || x.StoreId == CurrentStoreId);+ foreach (var warehouse in warehouses)+ model.AvailableWarehouses.Add(new SelectListItem {+ Text = warehouse.Name, Value = warehouse.Id,+ Selected = warehouse.Id == selectedWarehouseId+ });+ //shipping methods+ foreach (var sm in shippingMethods)+ model.AvailableShippingMethods.Add(new SelectListItem {+ Text = sm.Name, Value = sm.Id,+ Selected = sm.Id == selectedShippingMethodId+ });+ //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,+ Selected = c.Id == selectedCountryId+ });+ //states+ model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" });+ var selectedCountry = countries.FirstOrDefault(x => x.Id == selectedCountryId);+ if (selectedCountry == null) return;++ foreach (var s in await _countryService.GetStateProvincesByCountryId(selectedCountry.Id))+ model.AvailableStates.Add(new SelectListItem {+ Text = s.Name, Value = s.Id,+ Selected = s.Id == selectedStateProvinceId+ });+ }+}diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/AddPopup.cshtml b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/AddPopup.cshtmlnew file mode 100644index 000000000..cd5e9f4a6--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/AddPopup.cshtml@@ -0,0 +1,41 @@+@{+ Layout = "";+}+@model Shipping.ByWeight.Models.ShippingByWeightModel+<form id="AddPopup" asp-controller="ShippingByWeight" asp-action="AddPopup" asp-route-area="Store" method="post"+ asp-route-btnId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["btnId"])"+ asp-route-formId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["formId"])">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-list-alt"></i>+ @Loc["Admin.Common.AddNew"]+ </div>+ </div>+ <div class="x_content form">+ <partial name="_CreateOrUpdate" model="Model"/>+ </div>+ </div>+ </div>+ </div>+ <script>+ var mfp = $.magnificPopup.instance;+ $("#AddPopup").submit(function (e) {+ e.preventDefault();+ var form = $(this);+ var url = form.attr('action');+ $.ajax({+ type: "POST",+ url: url,+ data: form.serialize(),+ success: function (data) {+ mfp.close();+ $('#btnRefresh').click();+ }+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/Configure.cshtml b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/Configure.cshtmlnew file mode 100644index 000000000..360e3fd9a--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/Configure.cshtml@@ -0,0 +1,235 @@+@model Shipping.ByWeight.Models.ShippingByWeightListModel+@{+ Layout = "~/Areas/Store/Views/Shared/_StoreLayout.cshtml";+ ViewBag.Title = Loc["Admin.Configuration.Shipping.Providers"];+}+<input id="active-menu-item" type="hidden" value="/Store/Shipping/Providers"/>++<form asp-controller="ShippingByWeight" asp-action="Configure" asp-route-area="Store" method="post" id="shipping-byweight-form">++ <div class="note note-info">+ <strong>@Loc["Plugins.Shipping.ByWeight.Formula"]:</strong>+ @Loc["Plugins.Shipping.ByWeight.Formula.Value"]+ </div>++ @{+ var addNewUrl = Url.Action("AddPopup", "ShippingByWeight", new { area = "Store", btnId = "btnRefresh", formId = "shipping-byweight-form" });+ }++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption level-caption">+ <i class="fa fa-list-alt"></i>+ @Loc["Shipping.ByWeight.FriendlyName"]+ </div>+ </div>+ <div class="x_content form">+ <div id="shipping-byweight-grid"></div>+ </div>+ <div class="panel-footer">+ <a id="btnAddNewOption" href="@(addNewUrl)" class="btn default">+ @Loc["Plugins.Shipping.ByWeight.AddRecord"]+ </a>+ <input type="submit" id="btnRefresh" style="display: none"/>+ </div>+ </div>+ </div>+ </div>++ <script>+ $(document).ready(function () {+ $('#btnAddNewOption').magnificPopup({+ type: 'ajax',+ settings: { cache: false, async: false },+ midClick: true,+ callbacks: {+ parseAjax: function (mfpResponse) {+ mfpResponse.data = $('<div></div>').html(mfpResponse.data);+ },+ ajaxContentAdded: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ $("#shipping-byweight-grid").kendoGrid({+ dataBound: function () {+ $('.editpopup').magnificPopup({+ type: 'ajax',+ settings: { cache: false, async: false },+ callbacks: {+ parseAjax: function (mfpResponse) {+ mfpResponse.data = $('<div></div>').html(mfpResponse.data);+ },+ ajaxContentAdded: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ },+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("RatesList", "ShippingByWeight", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ destroy: {+ url: "@Html.Raw(Url.Action("RateDelete", "ShippingByWeight", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id"+ }+ },+ requestEnd: function (e) {+ if (e.type == "update") {+ this.read();+ }+ },+ error: function (e) {+ display_kendoui_grid_error(e);+ // Cancel the changes+ this.cancelChanges();+ },+ pageSize: 15,+ serverPaging: true,+ serverFiltering: true,+ serverSorting: true+ },+ pageable: {+ refresh: true,+ pageSizes: [15, 30, 50]+ },+ editable: {+ confirmation: false,+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "WarehouseName",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.Warehouse"]",+ width: 300+ }, {+ field: "CountryName",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.Country"]",+ width: 200+ }, {+ field: "StateProvinceName",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.StateProvince"]",+ width: 200+ }, {+ field: "Zip",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.Zip"]",+ width: 200+ }, {+ field: "ShippingMethodName",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.ShippingMethod"]",+ width: 200+ }, {+ field: "DataHtml",+ title: "@Loc["Plugins.Shipping.ByWeight.Fields.DataHtml"]",+ width: 200,+ encoded: false+ }, {+ field: "Id",+ title: "@Loc["Admin.Common.Edit"]",+ width: 100,+ template: "<a href=\"@Url.Action("EditPopup", "ShippingByWeight", new { area = "Store" })?id=#=Id#&btnId=btnRefresh&formId=shipping-byweight-form\" class='k-button editpopup k-button-icontext'>@Loc["Admin.Common.Edit"]</a>"+ }, {+ command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },+ title: "@Loc["Admin.Common.Delete"]",+ width: 100+ }]+ });+ });+ </script>++ <script>+ $(document).ready(function () {+ $('#btnRefresh').click(function () {+ //refresh grid+ var grid = $("#shipping-byweight-grid").data('kendoGrid');+ grid.dataSource.read();++ //return false to don't reload a page+ return false;+ });+ });+ </script>++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="LimitMethodsToCreated" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <label class="mt-checkbox mt-checkbox-outline control control-checkbox">+ <admin-input asp-for="LimitMethodsToCreated"/>+ <div class="control__indicator"></div>+ </label>+ <span asp-validation-for="LimitMethodsToCreated"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="DisplayOrder" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="DisplayOrder"/>+ <span asp-validation-for="DisplayOrder"></span>+ </div>+ </div>+ </div>+ <div class="form-actions">+ <div class="row">+ <div class="offset-md-3 offset-sm-3 col-md-9 col-sm-9">+ <input type="button" id="savegeneralsettings" class="btn green" value="@Loc["Admin.Common.Save"]"/>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>++ <script>+ $(function () {+ $('#savegeneralsettings').click(function () {++ var postData = $(this.form).serialize();+ addAntiForgeryToken(postData);++ $.ajax({+ cache: false,+ type: 'POST',+ url: "@Html.Raw(Url.Action("SaveGeneralSettings", "ShippingByWeight", new { area = "Store" }))",+ data: postData,+ dataType: 'json',+ success: function (data) {+ alert('Saved');+ },+ error: function (xhr, ajaxOptions, thrownError) {+ alert('Failed to save settings.');+ }+ });+ return false;+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/EditPopup.cshtml b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/EditPopup.cshtmlnew file mode 100644index 000000000..3d2caf8de--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/EditPopup.cshtml@@ -0,0 +1,41 @@+@{+ Layout = "";+}+@model Shipping.ByWeight.Models.ShippingByWeightModel+<form id="EditPopup" asp-controller="ShippingByWeight" asp-action="EditPopup" asp-route-area="Store" method="post"+ asp-route-btnId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["btnId"])"+ asp-route-formId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["formId"])">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-list-alt"></i>+ @Loc["Admin.Common.Edit"]+ </div>+ </div>+ <div class="x_content form">+ <partial name="_CreateOrUpdate" model="Model"/>+ </div>+ </div>+ </div>+ </div>+ <script>+ var mfp = $.magnificPopup.instance;+ $("#EditPopup").submit(function (e) {+ e.preventDefault();+ var form = $(this);+ var url = form.attr('action');+ $.ajax({+ type: "POST",+ url: url,+ data: form.serialize(),+ success: function (data) {+ mfp.close();+ $('#btnRefresh').click();+ }+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/_CreateOrUpdate.cshtml b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/_CreateOrUpdate.cshtmlnew file mode 100644index 000000000..afd540a08--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/ShippingByWeight/_CreateOrUpdate.cshtml@@ -0,0 +1,148 @@+@using Microsoft.AspNetCore.Routing+@model Shipping.ByWeight.Models.ShippingByWeightModel+<div asp-validation-summary="All"></div>+<input asp-for="Id" type="hidden"/>++@if (ViewBag.RefreshPage == true)+{+ <script>+ try {window.opener.document.forms['@(Context.Request.Query["formId"])'].@(Context.Request.Query["btnId"]).click();}+ catch (e){}+ window.close();+ </script>+}+<script>+ $(function () {+ $("#@Html.IdFor(model => model.CountryId)").change(function () {+ var selectedItem = $(this).val();+ var ddlStates = $("#@Html.IdFor(model => model.StateProvinceId)");+ $.ajax({+ cache: false,+ type: "GET",+ url: "@(Url.Action("GetStatesByCountryId", "Home", new RouteValueDictionary { { "area", "Store" } }))",+ data: { "countryId": selectedItem, "addAsterisk": "true" },+ success: function (data) {+ ddlStates.html('');+ $.each(data, function (id, option) {+ ddlStates.append($('<option></option>').val(option.id).html(option.name));+ });+ },+ error: function (xhr, ajaxOptions, thrownError) {+ alert('Failed to retrieve states.');+ }+ });+ });+ });+</script>++@*the record always belongs to the owner's own store, so no store selector is offered*@+<div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="WarehouseId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="WarehouseId" asp-items="Model.AvailableWarehouses"/>+ <span asp-validation-for="WarehouseId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="CountryId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="CountryId" asp-items="Model.AvailableCountries"/>+ <span asp-validation-for="CountryId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="StateProvinceId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="StateProvinceId" asp-items="Model.AvailableStates"/>+ <span asp-validation-for="StateProvinceId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="Zip" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="Zip"/>+ <span asp-validation-for="Zip"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="ShippingMethodId" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="ShippingMethodId" asp-items="Model.AvailableShippingMethods"/>+ <span asp-validation-for="ShippingMethodId"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="From" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="From"/> [@Model.BaseWeightIn]+ <span asp-validation-for="From"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="To" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="To"/> [@Model.BaseWeightIn]+ <span asp-validation-for="To"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="AdditionalFixedCost" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="AdditionalFixedCost"/> [@Model.PrimaryStoreCurrencyCode]+ <span asp-validation-for="AdditionalFixedCost"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="LowerWeightLimit" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="LowerWeightLimit"/>+ <span asp-validation-for="LowerWeightLimit"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="RatePerWeightUnit" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="RatePerWeightUnit"/> [@Model.PrimaryStoreCurrencyCode]+ <span asp-validation-for="RatePerWeightUnit"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="PercentageRateOfSubtotal" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="PercentageRateOfSubtotal"/>+ <span asp-validation-for="PercentageRateOfSubtotal"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="offset-sm-3 offset-md-3 col-md-9 col-sm-9">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i>@Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ </div>+</div>diff --git a/src/Plugins/Shipping.ByWeight/Areas/Store/Views/_ViewImports.cshtml b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/_ViewImports.cshtmlnew file mode 100644index 000000000..254d01f31--- /dev/null+++ b/src/Plugins/Shipping.ByWeight/Areas/Store/Views/_ViewImports.cshtml@@ -0,0 +1,9 @@+@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers+@addTagHelper *, Grand.Web.Common++@using Microsoft.AspNetCore.Mvc.ViewFeatures+@using Grand.Infrastructure.Extensions+@using Grand.Web.Common.Extensions+@using Grand.Web.Common.Localization++@inject LocService Locdiff --git a/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.csindex 38b269f5b..28048e90a 100644--- a/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs+++ b/src/Plugins/Shipping.ByWeight/Services/IShippingByWeightService.cs@@ -7,7 +7,14 @@ public interface IShippingByWeightService{Task DeleteShippingByWeightRecord(ShippingByWeightRecord shippingByWeightRecord);- Task<IPagedList<ShippingByWeightRecord>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue);+ /// <summary>+ /// Gets shipping by weight records+ /// </summary>+ /// <param name="storeId">The store identifier; pass "" to load records of all stores</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ Task<IPagedList<ShippingByWeightRecord>> GetAll(string storeId = "", int pageIndex = 0,+ int pageSize = int.MaxValue);Task<ShippingByWeightRecord> FindRecord(string shippingMethodId,string storeId, string warehouseId,diff --git a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.csindex 737616e99..88a7c2138 100644--- a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs+++ b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs@@ -20,7 +20,7 @@ public class ShippingByWeightService : IShippingByWeightService#region Constants- private const string SHIPPINGBYWEIGHT_ALL_KEY = "Grand.shippingbyweight.all-{0}-{1}";+ private const string SHIPPINGBYWEIGHT_ALL_KEY = "Grand.shippingbyweight.all-{0}-{1}-{2}";private const string SHIPPINGBYWEIGHT_PATTERN_KEY = "Grand.shippingbyweight.";#endregion@@ -43,13 +43,16 @@ public class ShippingByWeightService : IShippingByWeightServiceawait _cacheBase.RemoveByPrefix(SHIPPINGBYWEIGHT_PATTERN_KEY);}- public virtual async Task<IPagedList<ShippingByWeightRecord>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue)+ public virtual async Task<IPagedList<ShippingByWeightRecord>> GetAll(string storeId = "", int pageIndex = 0,+ int pageSize = int.MaxValue){- var key = string.Format(SHIPPINGBYWEIGHT_ALL_KEY, pageIndex, pageSize);+ var key = string.Format(SHIPPINGBYWEIGHT_ALL_KEY, storeId, pageIndex, pageSize);return await _cacheBase.GetAsync(key, async () =>{- var query = from sbw in _sbwRepository.Table- select sbw;+ var query = _sbwRepository.Table.AsQueryable();+ //filter by store when requested; an empty storeId returns records of all stores+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(sbw => sbw.StoreId == storeId);return await _sbwRepository.PagedAsync(query, pageIndex, pageSize);});diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Controllers/ShippingPointController.cs b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Controllers/ShippingPointController.csnew file mode 100644index 000000000..fe39d1115--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Controllers/ShippingPointController.cs@@ -0,0 +1,178 @@+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Rendering;+using Shipping.ShippingPoint.Models;+using Shipping.ShippingPoint.Services;++namespace Shipping.ShippingPoint.Areas.Store.Controllers;++/// <summary>+/// Store-manager configuration of the shipping point (pickup point) provider.+/// A store owner can add, edit and delete pickup points, but only the ones that belong+/// to his own store (<see cref="CurrentStoreId" />). Points owned by other stores or+/// global (store = *) points are never returned nor mutated.+/// </summary>+[Area("Store")]+[AuthorizeStore]+[AuthorizeMenu]+[PermissionAuthorize(PermissionSystemName.ShippingSettings)]+public class ShippingPointController : BaseController+{+ private readonly IContextAccessor _contextAccessor;+ private readonly ICountryService _countryService;+ private readonly IShippingPointService _shippingPointService;+ private readonly ITranslationService _translationService;++ public ShippingPointController(+ ITranslationService translationService,+ IShippingPointService shippingPointService,+ ICountryService countryService,+ IContextAccessor contextAccessor+ )+ {+ _translationService = translationService;+ _shippingPointService = shippingPointService;+ _countryService = countryService;+ _contextAccessor = contextAccessor;+ }++ /// <summary>+ /// The store the current staff/store-manager is bound to.+ /// </summary>+ private string CurrentStoreId => _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;++ public IActionResult Configure()+ {+ return View();+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> List(DataSourceRequest command)+ {+ //only the current store points - filtered and paged in the service layer+ var shippingPoints = await _shippingPointService.GetAllStoreShippingPoint(CurrentStoreId,+ command.Page - 1, command.PageSize);++ var viewModel = shippingPoints.Select(shippingPoint => new ShippingPointModel {+ ShippingPointName = shippingPoint.ShippingPointName,+ Description = shippingPoint.Description,+ Id = shippingPoint.Id,+ OpeningHours = shippingPoint.OpeningHours,+ PickupFee = shippingPoint.PickupFee+ }).ToList();++ return Json(new DataSourceResult {+ Data = viewModel,+ Total = shippingPoints.TotalCount+ });+ }++ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> Create()+ {+ var model = new ShippingPointModel {+ //the owner cannot create points for another store+ StoreId = CurrentStoreId+ };+ await PrepareShippingPointModel(model);+ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> Create(ShippingPointModel model)+ {+ if (ModelState.IsValid)+ {+ var shippingPoint = model.ToEntity();+ //force the current store - the owner cannot create points for another store+ shippingPoint.StoreId = CurrentStoreId;+ await _shippingPointService.InsertStoreShippingPoint(shippingPoint);++ ViewBag.RefreshPage = true;+ return Content("");+ }++ await PrepareShippingPointModel(model);++ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ public async Task<IActionResult> Edit(string id)+ {+ var shippingPoint = await _shippingPointService.GetStoreShippingPointById(id);+ //guard: a store owner can only open his own store points+ if (shippingPoint == null || shippingPoint.StoreId != CurrentStoreId)+ return RedirectToAction("Configure");++ var model = shippingPoint.ToModel();+ await PrepareShippingPointModel(model);+ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> Edit(ShippingPointModel model)+ {+ var existing = await _shippingPointService.GetStoreShippingPointById(model.Id);+ //guard: a store owner can only edit his own store points+ if (existing == null || existing.StoreId != CurrentStoreId)+ return RedirectToAction("Configure");++ if (ModelState.IsValid)+ {+ var shippingPoint = model.ToEntity();+ //StoreId is deliberately not taken from the model - the point stays in the owner's store+ shippingPoint.StoreId = existing.StoreId;+ await _shippingPointService.UpdateStoreShippingPoint(shippingPoint);++ return Content("");+ }++ ViewBag.RefreshPage = true;++ await PrepareShippingPointModel(model);++ return View(model);+ }++ [HttpPost]+ [AutoValidateAntiforgeryToken]+ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ public async Task<IActionResult> Delete(string id)+ {+ var shippingPoint = await _shippingPointService.GetStoreShippingPointById(id);+ //guard: a store owner can only delete his own store points+ if (shippingPoint == null || shippingPoint.StoreId != CurrentStoreId)+ return new JsonResult("");++ await _shippingPointService.DeleteStoreShippingPoint(shippingPoint);++ return new JsonResult("");+ }++ /// <summary>+ /// Fills the drop-downs of the add/edit form. No store selector is offered - the point+ /// always belongs to the owner's own store.+ /// </summary>+ [NonAction]+ private async Task PrepareShippingPointModel(ShippingPointModel model)+ {+ 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 });+ }+}diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Configure.cshtml b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Configure.cshtmlnew file mode 100644index 000000000..ad6d55b09--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Configure.cshtml@@ -0,0 +1,144 @@+@{+ Layout = "~/Areas/Store/Views/Shared/_StoreLayout.cshtml";+ ViewBag.Title = Loc["Admin.Configuration.Shipping.Providers"];+}+<input id="active-menu-item" type="hidden" value="/Store/Shipping/Providers"/>++<form asp-controller="ShippingPoint" asp-action="Configure" asp-route-area="Store" method="post" id="shipping-instore-form">+ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption level-caption">+ <i class="fa fa-map-marker"></i>+ @Loc["Shipping.ShippingPoint.FriendlyName"]+ </div>+ </div>+ <div class="x_content form">+ <div id="shipping-points-grid"></div>+ </div>+ <div class="panel-footer">+ <a id="btnAddNewOption" class="btn btn-primary" href="@(Url.Action("Create", "ShippingPoint", new { area = "Store" }) + "?btnId=btnRefresh&formId=shipping-instore-form")">+ @Loc["Admin.Common.AddNew"]+ </a>+ <input type="submit" id="btnRefresh" class="btn btn-default" style="display: none"/>+ </div>+ </div>+ </div>+ </div>++ <script>+ $(document).ready(function () {+ $('#btnAddNewOption').magnificPopup({+ type: 'ajax',+ settings: { cache: false, async: false },+ midClick: true,+ callbacks: {+ parseAjax: function (mfpResponse) {+ mfpResponse.data = $('<div></div>').html(mfpResponse.data);+ },+ ajaxContentAdded: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ $("#shipping-points-grid").kendoGrid({+ dataBound: function () {+ $('.editpopup').magnificPopup({+ type: 'ajax',+ settings: { cache: false, async: false },+ midClick: true,+ callbacks: {+ parseAjax: function (mfpResponse) {+ mfpResponse.data = $('<div></div>').html(mfpResponse.data);+ },+ ajaxContentAdded: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ },+ dataSource: {+ type: "json",+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("List", "ShippingPoint", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ destroy: {+ url: "@Html.Raw(Url.Action("Delete", "ShippingPoint", new { area = "Store" }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id"+ }+ },+ requestEnd: function (e) {+ if (e.type == "update") {+ this.read();+ }+ },+ error: function (e) {+ display_kendoui_grid_error(e);+ this.cancelChanges();+ },+ serverPaging: true,+ serverFiltering: true,+ serverSorting: true+ },+ pageable: {+ refresh: true,+ numeric: false,+ previousNext: false,+ info: false+ },+ editable: {+ confirmation: "@Loc["Admin.Common.DeleteConfirmation"]",+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "ShippingPointName",+ width: 200,+ title: "@Loc["Shipping.ShippingPoint.Fields.ShippingPointName"]"+ }, {+ field: "OpeningHours",+ width: 200,+ title: "@Loc["Shipping.ShippingPoint.Fields.OpeningHours"]"+ }, {+ field: "PickupFee",+ width: 150,+ title: "@Loc["Shipping.ShippingPoint.Fields.PickupFee"]"+ }, {+ field: "Id",+ title: "@Loc["Admin.Common.Edit"]",+ width: 100,+ template: "<a href=\"@Url.Action("Edit", "ShippingPoint", new { area = "Store" })?id=#=Id#&btnId=btnRefresh&formId=shipping-instore-form\" class='k-button editpopup k-button-icontext'>@Loc["Admin.Common.Edit"]</a>"+ }, {+ command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },+ title: "@Loc["Admin.Common.Delete"]",+ width: 100+ }]+ });+ });+ </script>++ <script>+ $(document).ready(function () {+ $('#btnRefresh').click(function () {+ var grid = $("#shipping-points-grid").data('kendoGrid');+ grid.dataSource.read();+ return false;+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Create.cshtml b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Create.cshtmlnew file mode 100644index 000000000..e9a346bef--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Create.cshtml@@ -0,0 +1,64 @@+@{+ Layout = "";+}+@model Shipping.ShippingPoint.Models.ShippingPointModel++<form id="CreatePopup" asp-controller="ShippingPoint" asp-action="Create" asp-route-area="Store" method="post"+ asp-route-btnId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["btnId"])"+ asp-route-formId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["formId"])">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ @Loc["Admin.Common.AddNew"]+ </div>+ <div class="actions">+ <div class="btn-group btn-group-devided">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ <div class="content">+ <div class="form-horizontal">+ <partial name="_CreateOrUpdate" model="Model"/>+ </div>+ </div>+ <script>+ var mfp = $.magnificPopup.instance;+ $("#CreatePopup").submit(function (e) {+ e.preventDefault();+ var form = $(this);+ var url = form.attr('action');+ $.ajax({+ type: "POST",+ url: url,+ data: form.serialize(),+ success: function (data) {+ if (data == "") {+ mfp.close();+ $('#btnRefresh').click();+ } else {+ $.magnificPopup.open({+ items: {+ src: data,+ type: 'inline'+ },+ callbacks: {+ open: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ }+ }+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Edit.cshtml b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Edit.cshtmlnew file mode 100644index 000000000..1f3d9e471--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/Edit.cshtml@@ -0,0 +1,64 @@+@{+ Layout = "";+}+@model Shipping.ShippingPoint.Models.ShippingPointModel++<form id="EditPopup" asp-controller="ShippingPoint" asp-action="Edit" asp-route-area="Store" method="post"+ asp-route-btnId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["btnId"])"+ asp-route-formId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["formId"])">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ @Loc["Admin.Common.Edit"]+ </div>+ <div class="actions">+ <div class="btn-group btn-group-devided">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ <div class="content">+ <div class="form-horizontal">+ <partial name="_CreateOrUpdate" model="Model"/>+ </div>+ </div>+ <script>+ var mfp = $.magnificPopup.instance;+ $("#EditPopup").submit(function (e) {+ e.preventDefault();+ var form = $(this);+ var url = form.attr('action');+ $.ajax({+ type: "POST",+ url: url,+ data: form.serialize(),+ success: function (data) {+ if (data == "") {+ mfp.close();+ $('#btnRefresh').click();+ } else {+ $.magnificPopup.open({+ items: {+ src: data,+ type: 'inline'+ },+ callbacks: {+ open: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ }+ }+ });+ });+ </script>+</form>diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/_CreateOrUpdate.cshtml b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/_CreateOrUpdate.cshtmlnew file mode 100644index 000000000..bcbf042fe--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/ShippingPoint/_CreateOrUpdate.cshtml@@ -0,0 +1,75 @@+@model Shipping.ShippingPoint.Models.ShippingPointModel++<div asp-validation-summary="All"></div>+<input asp-for="Id" type="hidden"/>++@if (ViewBag.RefreshPage == true)+{+ <script>+ try {window.opener.document.forms['@(Context.Request.Query["formId"])'].@(Context.Request.Query["btnId"]).click();}+ catch (e){}+ window.close();+ </script>+}++@*the point always belongs to the owner's own store, so no store selector is offered*@+<div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <admin-label asp-for="ShippingPointName"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="ShippingPointName"/>+ <span asp-validation-for="ShippingPointName"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="Description"/>+ <div class="col-md-9 col-sm-9">+ <admin-textarea asp-for="Description"></admin-textarea>+ <span asp-validation-for="Description"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="CountryId"/>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="CountryId" asp-items="Model.AvailableCountries"/>+ <span asp-validation-for="CountryId"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="City"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="City"/>+ <span asp-validation-for="City"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="Address1"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="Address1"/>+ <span asp-validation-for="Address1"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="ZipPostalCode"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="ZipPostalCode"/>+ <span asp-validation-for="ZipPostalCode"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="OpeningHours"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="OpeningHours"/>+ <span asp-validation-for="OpeningHours"></span>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="PickupFee"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="PickupFee"/>+ <span asp-validation-for="PickupFee"></span>+ </div>+ </div>+ </div>+</div>diff --git a/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/_ViewImports.cshtml b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/_ViewImports.cshtmlnew file mode 100644index 000000000..254d01f31--- /dev/null+++ b/src/Plugins/Shipping.ShippingPoint/Areas/Store/Views/_ViewImports.cshtml@@ -0,0 +1,9 @@+@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers+@addTagHelper *, Grand.Web.Common++@using Microsoft.AspNetCore.Mvc.ViewFeatures+@using Grand.Infrastructure.Extensions+@using Grand.Web.Common.Extensions+@using Grand.Web.Common.Localization++@inject LocService Locdiff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Providers.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Providers.cshtmlindex bb28545a2..535b94297 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Providers.cshtml+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Providers.cshtml@@ -85,12 +85,12 @@ $(document).ready(function () {field: "FriendlyName",title: "@Loc["Admin.Configuration.Shipping.Providers.Fields.FriendlyName"]",width: 250,- template: '<a class="k-link" href="#=ConfigurationUrl#">#=FriendlyName#</a>',+ template: '# if (ConfigurationUrl) { # <a class="k-link" href="#=ConfigurationUrl#">#:FriendlyName#</a> # } else { # #:FriendlyName# # } #',}, {field: "SystemName",title: "@Loc["Admin.Configuration.Shipping.Providers.Fields.SystemName"]",width: 250,- template: '<a class="k-link" href="#=ConfigurationUrl#">#=SystemName#</a>',+ template: '# if (ConfigurationUrl) { # <a class="k-link" href="#=ConfigurationUrl#">#:SystemName#</a> # } else { # #:SystemName# # } #',}, {field: "DisplayOrder",title: "@Loc["Admin.Configuration.Shipping.Providers.Fields.DisplayOrder"]",diff --git a/src/Web/Grand.Web.Store/Controllers/ShippingController.cs b/src/Web/Grand.Web.Store/Controllers/ShippingController.csindex 017c2e5a6..65491b5dc 100644--- a/src/Web/Grand.Web.Store/Controllers/ShippingController.cs+++ b/src/Web/Grand.Web.Store/Controllers/ShippingController.cs@@ -17,6 +17,7 @@ using Grand.Web.AdminShared.Models.Shipping;using Grand.Web.Common.DataSource;using Grand.Web.Common.Models;using Grand.Web.Common.Security.Authorization;+using Grand.Web.Store.Extensions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Rendering;@@ -50,6 +51,10 @@ public class ShippingController(.Select(p => {var m = p.ToModel();m.IsActive = p.IsShippingRateMethodActive(shippingProviderSettings);+ //a provider whose plugin is not multi-store has no Store-area configuration screen -+ //its relative url would resolve under /Store/ and 404, so offer no link at all+ if (!StoreAreaConfiguration.Exists(p))+ m.ConfigurationUrl = null;return m;}).ToList();diff --git a/src/Web/Grand.Web.Store/Extensions/StoreAreaConfiguration.cs b/src/Web/Grand.Web.Store/Extensions/StoreAreaConfiguration.csnew file mode 100644index 000000000..01e564e93--- /dev/null+++ b/src/Web/Grand.Web.Store/Extensions/StoreAreaConfiguration.cs@@ -0,0 +1,53 @@+using Microsoft.AspNetCore.Mvc;+using System.Collections.Concurrent;+using System.Reflection;++namespace Grand.Web.Store.Extensions;++/// <summary>+/// Tells whether the plugin a provider comes from ships a configuration screen for the Store area.+/// <para>+/// Provider configuration urls are relative (e.g. "../ShippingByWeight/Configure"), so the very+/// same value resolves to /Admin/... under the Admin area and to /Store/... under this one. A+/// plugin whose data is not store-scoped only has an [Area("Admin")] controller - linking a store+/// owner there produces a 404. The Store grids therefore ask this first and render plain text+/// instead of a dead link when the answer is no.+/// </para>+/// </summary>+public static class StoreAreaConfiguration+{+ //plugin assemblies never change within a process lifetime, so the reflection cost is paid once+ private static readonly ConcurrentDictionary<Assembly, bool> Cache = new();++ /// <summary>+ /// Whether the provider's plugin exposes at least one controller in the Store area.+ /// </summary>+ public static bool Exists(object provider)+ {+ return provider != null && Cache.GetOrAdd(provider.GetType().Assembly, HasStoreAreaController);+ }++ private static bool HasStoreAreaController(Assembly assembly)+ {+ return GetLoadableTypes(assembly).Any(type =>+ typeof(ControllerBase).IsAssignableFrom(type) &&+ string.Equals(type.GetCustomAttribute<AreaAttribute>()?.RouteValue, Constants.AreaStore,+ StringComparison.OrdinalIgnoreCase));+ }++ /// <summary>+ /// A plugin assembly can reference types that fail to load; those types are simply not controllers+ /// we could route to, so they are skipped rather than failing the whole provider list.+ /// </summary>+ private static IEnumerable<Type> GetLoadableTypes(Assembly assembly)+ {+ try+ {+ return assembly.GetTypes();+ }+ catch (ReflectionTypeLoadException ex)+ {+ return ex.Types.Where(type => type != null);+ }+ }+}