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.

Publish rating, shipping and return policy in the storefront JSON-LD (#863)

Krzysztof Pajaka2527c39bd58
diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnFees.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnFees.cs
new file mode 100644
index 000000000..03b5be29b
--- /dev/null
+++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnFees.cs
@@ -0,0 +1,22 @@
+namespace Grand.Domain.Orders;
+
+/// <summary>
+/// Represents who pays for a merchandise return, as the store declares it
+/// </summary>
+public enum MerchandiseReturnFees
+{
+ /// <summary>
+ /// Not declared - nothing is published about return fees
+ /// </summary>
+ NotSpecified = 0,
+
+ /// <summary>
+ /// Returns cost the customer nothing
+ /// </summary>
+ Free = 10,
+
+ /// <summary>
+ /// The customer pays for the return
+ /// </summary>
+ CustomerPays = 20
+}
diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnMethod.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnMethod.cs
new file mode 100644
index 000000000..4add3ba9f
--- /dev/null
+++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnMethod.cs
@@ -0,0 +1,22 @@
+namespace Grand.Domain.Orders;
+
+/// <summary>
+/// Represents how the customer sends a merchandise return back, as the store declares it
+/// </summary>
+public enum MerchandiseReturnMethod
+{
+ /// <summary>
+ /// Not declared - nothing is published about the return method
+ /// </summary>
+ NotSpecified = 0,
+
+ /// <summary>
+ /// Returned by mail or courier
+ /// </summary>
+ ByMail = 10,
+
+ /// <summary>
+ /// Returned in a physical store
+ /// </summary>
+ InStore = 20
+}
diff --git a/src/Core/Grand.Domain/Orders/OrderSettings.cs b/src/Core/Grand.Domain/Orders/OrderSettings.cs
index d00058071..0dcc6e31e 100644
--- a/src/Core/Grand.Domain/Orders/OrderSettings.cs
+++ b/src/Core/Grand.Domain/Orders/OrderSettings.cs
@@ -90,6 +90,18 @@ public class OrderSettings : ISettings
/// </summary>
public int NumberOfDaysMerchandiseReturnAvailable { get; set; }
+ /// <summary>
+ /// Gets or sets who pays for a merchandise return. Optional - informational only, published in the
+ /// store's structured data (MerchantReturnPolicy.returnFees); nothing in checkout enforces it
+ /// </summary>
+ public MerchandiseReturnFees MerchandiseReturnFees { get; set; }
+
+ /// <summary>
+ /// Gets or sets how merchandise returns are sent back. Optional - informational only, published in the
+ /// store's structured data (MerchantReturnPolicy.returnMethod)
+ /// </summary>
+ public MerchandiseReturnMethod MerchandiseReturnMethod { get; set; }
+
/// <summary>
/// Gift vouchers are activated when the order status is
/// </summary>
diff --git a/src/Core/Grand.Domain/Shipping/ShippingSettings.cs b/src/Core/Grand.Domain/Shipping/ShippingSettings.cs
index e1c115f66..31b913765 100644
--- a/src/Core/Grand.Domain/Shipping/ShippingSettings.cs
+++ b/src/Core/Grand.Domain/Shipping/ShippingSettings.cs
@@ -57,4 +57,34 @@ public class ShippingSettings : ISettings
/// quantity
/// </summary>
public bool AdditionalShippingChargeByQty { get; set; }
+
+ /// <summary>
+ /// Gets or sets the standard cost of shipping one item, in the primary store currency, entered like a
+ /// shipping method's rate. Optional - informational only, published in structured data
+ /// (OfferShippingDetails.shippingRate) for products without free shipping; checkout never uses it,
+ /// the rate there always comes from the shipping provider
+ /// </summary>
+ public double? DefaultShippingRate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum number of business days between the order and handing it to the carrier.
+ /// Optional - informational only, published in structured data (OfferShippingDetails.deliveryTime)
+ /// </summary>
+ public int? HandlingTimeMinDays { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum number of business days between the order and handing it to the carrier
+ /// </summary>
+ public int? HandlingTimeMaxDays { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum number of business days the carrier needs to deliver.
+ /// Optional - informational only, published in structured data (OfferShippingDetails.deliveryTime)
+ /// </summary>
+ public int? TransitTimeMinDays { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum number of business days the carrier needs to deliver
+ /// </summary>
+ public int? TransitTimeMaxDays { get; set; }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Common/GetSiteStructuredDataHandlerTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Common/GetSiteStructuredDataHandlerTests.cs
new file mode 100644
index 000000000..72873be78
--- /dev/null
+++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Common/GetSiteStructuredDataHandlerTests.cs
@@ -0,0 +1,91 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain.Directory;
+using Grand.Domain.Orders;
+using Grand.Domain.Stores;
+using Grand.Web.Features.Handlers.Common;
+using Grand.Web.Features.Models.Common;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Tests.Features.Handlers.Common;
+
+[TestClass]
+public class GetSiteStructuredDataHandlerTests
+{
+ private readonly Domain.Stores.Store _store = new() { Id = "store-1", Name = "Shop" };
+ private Mock<ICountryService> _countryServiceMock;
+ private OrderSettings _orderSettings;
+ private StoreInformationSettings _storeInformationSettings;
+ private GetSiteStructuredDataHandler _handler;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _countryServiceMock = new Mock<ICountryService>();
+ _countryServiceMock.Setup(x => x.GetAllCountriesForShipping(It.IsAny<string>(), "store-1", false))
+ .ReturnsAsync(new List<Country> { new() { TwoLetterIsoCode = "PL" } });
+ _orderSettings = new OrderSettings();
+ _storeInformationSettings = new StoreInformationSettings { FacebookLink = "https://facebook.com/shop" };
+ _handler = new GetSiteStructuredDataHandler(_countryServiceMock.Object, new Mock<IPictureService>().Object,
+ _orderSettings, _storeInformationSettings);
+ }
+
+ [TestMethod]
+ public async Task Handle_ReturnsDisabled_NoReturnPolicy()
+ {
+ var result = await _handler.Handle(new GetSiteStructuredData { Store = _store }, default);
+
+ Assert.IsNull(result.ReturnPolicy);
+ Assert.AreEqual("Shop", result.StoreName);
+ CollectionAssert.AreEqual(new[] { "https://facebook.com/shop" }, result.SameAs.ToArray());
+ }
+
+ [TestMethod]
+ public async Task Handle_ReturnsEnabledWithDayLimit_FiniteWindow()
+ {
+ _orderSettings.MerchandiseReturnsEnabled = true;
+ _orderSettings.NumberOfDaysMerchandiseReturnAvailable = 14;
+
+ var result = await _handler.Handle(new GetSiteStructuredData { Store = _store }, default);
+
+ Assert.IsNotNull(result.ReturnPolicy);
+ Assert.IsFalse(result.ReturnPolicy.UnlimitedWindow);
+ CollectionAssert.AreEqual(new[] { "PL" }, result.ReturnPolicy.CountryCodes.ToArray());
+ }
+
+ [TestMethod]
+ public async Task Handle_ReturnsEnabledWithoutDayLimit_UnlimitedWindow()
+ {
+ _orderSettings.MerchandiseReturnsEnabled = true;
+ _orderSettings.NumberOfDaysMerchandiseReturnAvailable = 0;
+
+ var result = await _handler.Handle(new GetSiteStructuredData { Store = _store }, default);
+
+ Assert.IsTrue(result.ReturnPolicy.UnlimitedWindow);
+ }
+
+ [TestMethod]
+ public async Task Handle_ReturnFeesAndMethodDeclared_MappedToSchemaOrg()
+ {
+ _orderSettings.MerchandiseReturnsEnabled = true;
+ _orderSettings.MerchandiseReturnFees = MerchandiseReturnFees.Free;
+ _orderSettings.MerchandiseReturnMethod = MerchandiseReturnMethod.ByMail;
+
+ var result = await _handler.Handle(new GetSiteStructuredData { Store = _store }, default);
+
+ Assert.AreEqual("https://schema.org/FreeReturn", result.ReturnPolicy.ReturnFees);
+ Assert.AreEqual("https://schema.org/ReturnByMail", result.ReturnPolicy.ReturnMethod);
+ }
+
+ [TestMethod]
+ public async Task Handle_ReturnFeesAndMethodNotSpecified_Null()
+ {
+ _orderSettings.MerchandiseReturnsEnabled = true;
+
+ var result = await _handler.Handle(new GetSiteStructuredData { Store = _store }, default);
+
+ Assert.IsNull(result.ReturnPolicy.ReturnFees);
+ Assert.IsNull(result.ReturnPolicy.ReturnMethod);
+ }
+}
diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Products/GetProductStructuredDataHandlerTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Products/GetProductStructuredDataHandlerTests.cs
new file mode 100644
index 000000000..f743d1039
--- /dev/null
+++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Products/GetProductStructuredDataHandlerTests.cs
@@ -0,0 +1,244 @@
+using Grand.Business.Core.Interfaces.Catalog.Prices;
+using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Directory;
+using Grand.Domain.Orders;
+using Grand.Domain.Shipping;
+using Grand.Web.Features.Handlers.Products;
+using Grand.Web.Features.Models.Products;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Tests.Features.Handlers.Products;
+
+[TestClass]
+public class GetProductStructuredDataHandlerTests
+{
+ private readonly Domain.Stores.Store _store = new() { Id = "store-1" };
+ private readonly Customer _customer = new() { Id = "c1" };
+ //working currency at twice the primary one, so a missed conversion shows
+ private readonly Currency _currency = new() { CurrencyCode = "EUR", Rate = 2, NumberDecimal = 2 };
+ private Mock<ICountryService> _countryServiceMock;
+ private Mock<ICurrencyService> _currencyServiceMock;
+ private Mock<IPricingService> _pricingServiceMock;
+ private Mock<ITaxService> _taxServiceMock;
+ private OrderSettings _orderSettings;
+ private ShippingSettings _shippingSettings;
+ private GetProductStructuredDataHandler _handler;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _countryServiceMock = new Mock<ICountryService>();
+ _countryServiceMock.Setup(x => x.GetAllCountriesForShipping(It.IsAny<string>(), "store-1", false))
+ .ReturnsAsync(new List<Country> {
+ new() { TwoLetterIsoCode = "PL" }, new() { TwoLetterIsoCode = "DE" }, new() { TwoLetterIsoCode = "" }
+ });
+ _orderSettings = new OrderSettings { MerchandiseReturnsEnabled = true };
+ _shippingSettings = new ShippingSettings();
+ _currencyServiceMock = new Mock<ICurrencyService>();
+ _currencyServiceMock.Setup(x => x.ConvertFromPrimaryStoreCurrency(It.IsAny<double>(), _currency))
+ .ReturnsAsync((double amount, Currency _) => amount * 2);
+ _pricingServiceMock = new Mock<IPricingService>();
+ _taxServiceMock = new Mock<ITaxService>();
+ //shipping taxed at 10%, product prices passed through
+ _taxServiceMock.Setup(x => x.GetShippingPrice(It.IsAny<double>(), _customer, _store))
+ .ReturnsAsync((double price, Customer _, Domain.Stores.Store _) => (price * 1.1, 10));
+ _taxServiceMock.Setup(x => x.GetProductPrice(It.IsAny<Product>(), It.IsAny<double>(), It.IsAny<bool>(),
+ _customer, _store))
+ .ReturnsAsync((Product _, double price, bool _, Customer _, Domain.Stores.Store _) => (price, 0));
+ _handler = new GetProductStructuredDataHandler(_countryServiceMock.Object, _currencyServiceMock.Object,
+ _pricingServiceMock.Object, _taxServiceMock.Object, _orderSettings, _shippingSettings);
+ }
+
+ private Task<Grand.Web.Models.Catalog.ProductStructuredDataModel> Handle(Product product) =>
+ _handler.Handle(new GetProductStructuredData {
+ Product = product, Store = _store, Customer = _customer, Currency = _currency
+ }, default);
+
+ private void SetupFinalPrice(double price) =>
+ _pricingServiceMock.Setup(x => x.GetFinalPrice(It.IsAny<Product>(), _customer, _store, _currency, 0, true, 1))
+ .ReturnsAsync((price, 0, new List<Grand.Business.Core.Utilities.Catalog.ApplyDiscount>(), null));
+
+ [TestMethod]
+ public async Task Handle_ApprovedReviews_ReturnsRatingOfApprovedOnly()
+ {
+ var result = await Handle(new Product {
+ AllowCustomerReviews = true, ApprovedTotalReviews = 3, ApprovedRatingSum = 13,
+ NotApprovedTotalReviews = 5, NotApprovedRatingSum = 5
+ });
+
+ Assert.AreEqual(4.33, result.RatingValue);
+ Assert.AreEqual(3, result.ReviewCount);
+ }
+
+ [TestMethod]
+ public async Task Handle_NoApprovedReviews_NoRating()
+ {
+ var result = await Handle(new Product { AllowCustomerReviews = true, NotApprovedTotalReviews = 2 });
+
+ Assert.IsNull(result.RatingValue);
+ }
+
+ [TestMethod]
+ public async Task Handle_ReviewsDisabled_NoRating()
+ {
+ var result = await Handle(new Product {
+ AllowCustomerReviews = false, ApprovedTotalReviews = 3, ApprovedRatingSum = 15
+ });
+
+ Assert.IsNull(result.RatingValue);
+ }
+
+ [TestMethod]
+ public async Task Handle_FreeShippingProduct_ReturnsShippingCountries()
+ {
+ var result = await Handle(new Product { IsShipEnabled = true, IsFreeShipping = true });
+
+ Assert.AreEqual(0, result.ShippingRate);
+ CollectionAssert.AreEqual(new[] { "PL", "DE" }, result.CountryCodes.ToArray());
+ }
+
+ [TestMethod]
+ public async Task Handle_FreeShippingFlagOnNonShippableProduct_NoShippingClaim()
+ {
+ var result = await Handle(new Product { IsShipEnabled = false, IsFreeShipping = true });
+
+ Assert.IsNull(result.ShippingRate);
+ }
+
+ [TestMethod]
+ public async Task Handle_PaidShippingWithoutDefaultRate_NoShippingClaimAndNoCountryLookup()
+ {
+ var result = await Handle(new Product { IsShipEnabled = true, AdditionalShippingCharge = 5 });
+
+ Assert.IsNull(result.ShippingRate);
+ Assert.AreEqual(0, result.CountryCodes.Count);
+ _countryServiceMock.Verify(x => x.GetAllCountriesForShipping(It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<bool>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task Handle_NotReturnableProduct_OverridesStorePolicy()
+ {
+ var result = await Handle(new Product { NotReturnable = true });
+
+ Assert.IsTrue(result.ReturnsNotPermitted);
+ Assert.AreEqual(2, result.CountryCodes.Count);
+ }
+
+ [TestMethod]
+ public async Task Handle_NotReturnableProduct_ReturnsDisabled_NoOverride()
+ {
+ _orderSettings.MerchandiseReturnsEnabled = false;
+
+ var result = await Handle(new Product { NotReturnable = true });
+
+ Assert.IsFalse(result.ReturnsNotPermitted);
+ }
+
+ [TestMethod]
+ public async Task Handle_DeliveryTimeDeclared_ReturnedForShippableProduct()
+ {
+ _shippingSettings.HandlingTimeMinDays = 0;
+ _shippingSettings.HandlingTimeMaxDays = 1;
+ _shippingSettings.TransitTimeMaxDays = 3;
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.IsNull(result.ShippingRate);
+ Assert.IsTrue(result.HasShippingDetails);
+ Assert.AreEqual(0, result.HandlingTime.Min);
+ Assert.AreEqual(1, result.HandlingTime.Max);
+ Assert.IsNull(result.TransitTime.Min);
+ Assert.AreEqual(3, result.TransitTime.Max);
+ Assert.AreEqual(2, result.CountryCodes.Count);
+ }
+
+ [TestMethod]
+ public async Task Handle_DeliveryTimeDeclared_NotForNonShippableProduct()
+ {
+ _shippingSettings.TransitTimeMinDays = 1;
+
+ var result = await Handle(new Product { IsShipEnabled = false });
+
+ Assert.IsFalse(result.HasShippingDetails);
+ }
+
+ [TestMethod]
+ public async Task Handle_InconsistentDayRange_Dropped()
+ {
+ _shippingSettings.HandlingTimeMinDays = 5;
+ _shippingSettings.HandlingTimeMaxDays = 2;
+ _shippingSettings.TransitTimeMinDays = -1;
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.IsNull(result.HandlingTime);
+ Assert.IsNull(result.TransitTime);
+ Assert.IsFalse(result.HasShippingDetails);
+ }
+
+ [TestMethod]
+ public async Task Handle_DefaultShippingRate_AddsSurchargeConvertsAndTaxes()
+ {
+ _shippingSettings.DefaultShippingRate = 10;
+
+ var result = await Handle(new Product { IsShipEnabled = true, AdditionalShippingCharge = 5 });
+
+ //(10 + 5) primary -> 30 working -> 33 with shipping tax
+ Assert.AreEqual(33, result.ShippingRate);
+ Assert.IsTrue(result.HasShippingDetails);
+ }
+
+ [TestMethod]
+ public async Task Handle_PriceOverFreeShippingThreshold_Free()
+ {
+ _shippingSettings.DefaultShippingRate = 10;
+ _shippingSettings.FreeShippingOverXEnabled = true;
+ _shippingSettings.FreeShippingOverXValue = 200;
+ SetupFinalPrice(250);
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.AreEqual(0, result.ShippingRate);
+ }
+
+ [TestMethod]
+ public async Task Handle_PriceAtFreeShippingThreshold_DefaultRate()
+ {
+ //checkout requires the subtotal to be strictly over X
+ _shippingSettings.DefaultShippingRate = 10;
+ _shippingSettings.FreeShippingOverXEnabled = true;
+ _shippingSettings.FreeShippingOverXValue = 200;
+ SetupFinalPrice(200);
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.AreEqual(22, result.ShippingRate);
+ }
+
+ [TestMethod]
+ public async Task Handle_PriceOverThresholdWithoutDefaultRate_StillFree()
+ {
+ _shippingSettings.FreeShippingOverXEnabled = true;
+ _shippingSettings.FreeShippingOverXValue = 100;
+ SetupFinalPrice(150);
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.AreEqual(0, result.ShippingRate);
+ }
+
+ [TestMethod]
+ public async Task Handle_NegativeDefaultRate_Ignored()
+ {
+ _shippingSettings.DefaultShippingRate = -1;
+
+ var result = await Handle(new Product { IsShipEnabled = true });
+
+ Assert.IsNull(result.ShippingRate);
+ }
+}
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
index d8df62740..d0af714d1 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
@@ -11,6 +11,8 @@
<div class="grand-fields grand-fields--2col">
<admin-field asp-for="OrderSettings.MerchandiseReturnsEnabled"/>
<admin-field asp-for="OrderSettings.NumberOfDaysMerchandiseReturnAvailable" size="sm"/>
+ <admin-field asp-for="OrderSettings.MerchandiseReturnFees" asp-items="EnumTranslationService.ToSelectList(Model.OrderSettings.MerchandiseReturnFees)" size="md"/>
+ <admin-field asp-for="OrderSettings.MerchandiseReturnMethod" asp-items="EnumTranslationService.ToSelectList(Model.OrderSettings.MerchandiseReturnMethod)" size="md"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_AllowToSpecifyPickupAddress"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_AllowToSpecifyPickupDate"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_PickupDateRequired"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shipping/Settings.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shipping/Settings.cshtml
index 2045390e7..4e396c3da 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shipping/Settings.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shipping/Settings.cshtml
@@ -52,6 +52,19 @@
</div>
</div>
</admin-card>
+ @* optional; published only in the product structured data (JSON-LD), never used by checkout *@
+ <admin-card title="@Loc["Admin.Configuration.Shipping.Settings.StructuredData"]">
+ <div class="note note-info">@Loc["Admin.Configuration.Shipping.Settings.StructuredData.Description"]</div>
+ <div class="grand-fields">
+ <admin-field asp-for="DefaultShippingRate" size="md"/>
+ </div>
+ <div class="grand-fields grand-fields--2col">
+ <admin-field asp-for="HandlingTimeMinDays" size="sm"/>
+ <admin-field asp-for="HandlingTimeMaxDays" size="sm"/>
+ <admin-field asp-for="TransitTimeMinDays" size="sm"/>
+ <admin-field asp-for="TransitTimeMaxDays" size="sm"/>
+ </div>
+ </admin-card>
<admin-card title="@Loc["Admin.Configuration.Shipping.Settings.shippingoriginaddress"]">
<div id="pnlShippingOriginAddress">
<admin-input asp-for="ShippingOriginAddress" asp-template="Address"/>
diff --git a/src/Web/Grand.Web.AdminShared/Models/Settings/SalesSettingsModel.cs b/src/Web/Grand.Web.AdminShared/Models/Settings/SalesSettingsModel.cs
index dcb1a6ecb..03f9305cc 100644
--- a/src/Web/Grand.Web.AdminShared/Models/Settings/SalesSettingsModel.cs
+++ b/src/Web/Grand.Web.AdminShared/Models/Settings/SalesSettingsModel.cs
@@ -1,4 +1,5 @@
-using Grand.Infrastructure.ModelBinding;
+using Grand.Domain.Orders;
+using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
@@ -55,6 +56,12 @@ public class SalesSettingsModel : BaseModel
[GrandResourceDisplayName("Admin.Settings.Order.NumberOfDaysMerchandiseReturnAvailable")]
public int NumberOfDaysMerchandiseReturnAvailable { get; set; }
+ [GrandResourceDisplayName("Admin.Settings.Order.MerchandiseReturnFees")]
+ public MerchandiseReturnFees MerchandiseReturnFees { get; set; }
+
+ [GrandResourceDisplayName("Admin.Settings.Order.MerchandiseReturnMethod")]
+ public MerchandiseReturnMethod MerchandiseReturnMethod { get; set; }
+
[GrandResourceDisplayName("Admin.Settings.Order.GiftVouchers_Activated")]
public int GiftVouchers_Activated_OrderStatusId { get; set; }
diff --git a/src/Web/Grand.Web.AdminShared/Models/Shipping/ShippingSettingsModel.cs b/src/Web/Grand.Web.AdminShared/Models/Shipping/ShippingSettingsModel.cs
index 18bf49dbe..572788506 100644
--- a/src/Web/Grand.Web.AdminShared/Models/Shipping/ShippingSettingsModel.cs
+++ b/src/Web/Grand.Web.AdminShared/Models/Shipping/ShippingSettingsModel.cs
@@ -35,6 +35,21 @@ public class ShippingSettingsModel : BaseModel
[GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.AdditionalShippingChargeByQty")]
public bool AdditionalShippingChargeByQty { get; set; }
+ [GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.DefaultShippingRate")]
+ public double? DefaultShippingRate { get; set; }
+
+ [GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.HandlingTimeMinDays")]
+ public int? HandlingTimeMinDays { get; set; }
+
+ [GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.HandlingTimeMaxDays")]
+ public int? HandlingTimeMaxDays { get; set; }
+
+ [GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.TransitTimeMinDays")]
+ public int? TransitTimeMinDays { get; set; }
+
+ [GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.TransitTimeMaxDays")]
+ public int? TransitTimeMaxDays { get; set; }
+
[GrandResourceDisplayName("Admin.Configuration.Shipping.Settings.ShippingOriginAddress")]
public AddressModel ShippingOriginAddress { get; set; }
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
index b6fbfdb46..ec519fd5f 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Sales.TabMerchandiseReturn.cshtml
@@ -11,6 +11,8 @@
<div class="grand-fields grand-fields--2col">
<admin-field asp-for="OrderSettings.MerchandiseReturnsEnabled"/>
<admin-field asp-for="OrderSettings.NumberOfDaysMerchandiseReturnAvailable" size="sm"/>
+ <admin-field asp-for="OrderSettings.MerchandiseReturnFees" asp-items="EnumTranslationService.ToSelectList(Model.OrderSettings.MerchandiseReturnFees)" size="md"/>
+ <admin-field asp-for="OrderSettings.MerchandiseReturnMethod" asp-items="EnumTranslationService.ToSelectList(Model.OrderSettings.MerchandiseReturnMethod)" size="md"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_AllowToSpecifyPickupAddress"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_AllowToSpecifyPickupDate"/>
<admin-field asp-for="OrderSettings.MerchandiseReturns_PickupDateRequired"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Settings.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Settings.cshtml
index 85f4b0e18..2081aea20 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Settings.cshtml
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Shipping/Settings.cshtml
@@ -48,6 +48,19 @@
</div>
</div>
</admin-card>
+ @* optional; published only in the product structured data (JSON-LD), never used by checkout *@
+ <admin-card title="@Loc["Admin.Configuration.Shipping.Settings.StructuredData"]">
+ <div class="note note-info">@Loc["Admin.Configuration.Shipping.Settings.StructuredData.Description"]</div>
+ <div class="grand-fields">
+ <admin-field asp-for="DefaultShippingRate" size="md"/>
+ </div>
+ <div class="grand-fields grand-fields--2col">
+ <admin-field asp-for="HandlingTimeMinDays" size="sm"/>
+ <admin-field asp-for="HandlingTimeMaxDays" size="sm"/>
+ <admin-field asp-for="TransitTimeMinDays" size="sm"/>
+ <admin-field asp-for="TransitTimeMaxDays" size="sm"/>
+ </div>
+ </admin-card>
<admin-card title="@Loc["Admin.Configuration.Shipping.Settings.shippingoriginaddress"]">
<div id="pnlShippingOriginAddress">
<admin-input asp-for="ShippingOriginAddress" asp-template="Address"/>
diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
index c4561ff2a..bdc7a0ac1 100644
Binary files a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml and b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml differ
diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_240.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_240.xml
index fb39219e2..3c164986d 100644
--- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_240.xml
+++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_240.xml
@@ -408,4 +408,70 @@
<Resource Name="admin.catalog.products.fields.published.unpublished" Area="Admin">
<Value>Unpublished</Value>
</Resource>
+ <Resource Name="admin.settings.order.merchandisereturnfees" Area="Admin">
+ <Value>Return fees</Value>
+ </Resource>
+ <Resource Name="admin.settings.order.merchandisereturnfees.hint" Area="Admin">
+ <Value>Who pays for a return. Optional - published in the store's structured data for search engines and AI assistants; nothing in checkout enforces it.</Value>
+ </Resource>
+ <Resource Name="admin.settings.order.merchandisereturnmethod" Area="Admin">
+ <Value>Return method</Value>
+ </Resource>
+ <Resource Name="admin.settings.order.merchandisereturnmethod.hint" Area="Admin">
+ <Value>How customers send a return back. Optional - published in the store's structured data for search engines and AI assistants.</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.handlingtimemindays" Area="Admin">
+ <Value>Handling time - minimum days</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.handlingtimemindays.hint" Area="Admin">
+ <Value>Minimum business days between the order and handing the parcel to the carrier.</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.handlingtimemaxdays" Area="Admin">
+ <Value>Handling time - maximum days</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.handlingtimemaxdays.hint" Area="Admin">
+ <Value>Maximum business days between the order and handing the parcel to the carrier.</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.transittimemindays" Area="Admin">
+ <Value>Transit time - minimum days</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.transittimemindays.hint" Area="Admin">
+ <Value>Minimum business days the carrier needs to deliver.</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.transittimemaxdays" Area="Admin">
+ <Value>Transit time - maximum days</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.transittimemaxdays.hint" Area="Admin">
+ <Value>Maximum business days the carrier needs to deliver.</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnfees.notspecified" Area="Common">
+ <Value>Not specified</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnfees.free" Area="Common">
+ <Value>Free return</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnfees.customerpays" Area="Common">
+ <Value>Paid by the customer</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnmethod.notspecified" Area="Common">
+ <Value>Not specified</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnmethod.bymail" Area="Common">
+ <Value>By mail</Value>
+ </Resource>
+ <Resource Name="enums.grand.domain.orders.merchandisereturnmethod.instore" Area="Common">
+ <Value>In store</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.structureddata" Area="Admin">
+ <Value>Shipping details for search engines</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.structureddata.description" Area="Admin">
+ <Value>Optional. Published in the product structured data (JSON-LD) read by search engines, Google Merchant listings and AI assistants - checkout never uses these values. Leave a field empty to publish nothing for it.</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.defaultshippingrate" Area="Admin">
+ <Value>Default shipping rate</Value>
+ </Resource>
+ <Resource Name="admin.configuration.shipping.settings.defaultshippingrate.hint" Area="Admin">
+ <Value>Standard cost of shipping one item, in the primary store currency, entered like a shipping method's rate. Published for products without free shipping, plus the product's additional shipping charge; products that qualify for free shipping over X are published as free.</Value>
+ </Resource>
</Language>
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Components/SiteStructuredData.cs b/src/Web/Grand.Web/Components/SiteStructuredData.cs
new file mode 100644
index 000000000..2e159af73
--- /dev/null
+++ b/src/Web/Grand.Web/Components/SiteStructuredData.cs
@@ -0,0 +1,28 @@
+using Grand.Infrastructure;
+using Grand.Web.Common.Components;
+using Grand.Web.Features.Models.Common;
+using Grand.Mediator;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.Components;
+
+public class SiteStructuredDataViewComponent : BaseViewComponent
+{
+ private readonly IMediator _mediator;
+ private readonly IContextAccessor _contextAccessor;
+
+ public SiteStructuredDataViewComponent(IMediator mediator,
+ IContextAccessor contextAccessor)
+ {
+ _mediator = mediator;
+ _contextAccessor = contextAccessor;
+ }
+
+ public async Task<IViewComponentResult> InvokeAsync()
+ {
+ var model = await _mediator.Send(new GetSiteStructuredData {
+ Store = _contextAccessor.StoreContext.CurrentStore
+ });
+ return View(model);
+ }
+}
diff --git a/src/Web/Grand.Web/Features/Handlers/Common/GetSiteStructuredDataHandler.cs b/src/Web/Grand.Web/Features/Handlers/Common/GetSiteStructuredDataHandler.cs
new file mode 100644
index 000000000..ac1d45e5c
--- /dev/null
+++ b/src/Web/Grand.Web/Features/Handlers/Common/GetSiteStructuredDataHandler.cs
@@ -0,0 +1,78 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain.Orders;
+using Grand.Domain.Stores;
+using Grand.Web.Features.Models.Common;
+using Grand.Web.Models.Common;
+using Grand.Mediator;
+
+namespace Grand.Web.Features.Handlers.Common;
+
+public class GetSiteStructuredDataHandler : IRequestHandler<GetSiteStructuredData, SiteStructuredDataModel>
+{
+ private readonly ICountryService _countryService;
+ private readonly OrderSettings _orderSettings;
+ private readonly IPictureService _pictureService;
+ private readonly StoreInformationSettings _storeInformationSettings;
+
+ public GetSiteStructuredDataHandler(
+ ICountryService countryService,
+ IPictureService pictureService,
+ OrderSettings orderSettings,
+ StoreInformationSettings storeInformationSettings)
+ {
+ _countryService = countryService;
+ _pictureService = pictureService;
+ _orderSettings = orderSettings;
+ _storeInformationSettings = storeInformationSettings;
+ }
+
+ public async Task<SiteStructuredDataModel> Handle(GetSiteStructuredData request,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(request.Store);
+
+ var model = new SiteStructuredDataModel {
+ StoreName = request.Store.Name,
+ //social profiles the store has actually filled in - sameAs is what links the
+ //site to an existing knowledge-graph entity
+ SameAs = new[] {
+ _storeInformationSettings.FacebookLink,
+ _storeInformationSettings.TwitterLink,
+ _storeInformationSettings.YoutubeLink,
+ _storeInformationSettings.InstagramLink,
+ _storeInformationSettings.LinkedInLink,
+ _storeInformationSettings.PinterestLink
+ }
+ .Where(x => !string.IsNullOrWhiteSpace(x))
+ .ToList()
+ };
+
+ if (!string.IsNullOrEmpty(_storeInformationSettings.LogoPictureId))
+ model.LogoUrl = await _pictureService.GetPictureUrl(_storeInformationSettings.LogoPictureId);
+
+ if (_orderSettings.MerchandiseReturnsEnabled)
+ model.ReturnPolicy = new SiteStructuredDataModel.ReturnPolicyModel {
+ //IsMerchandiseReturnAllowedQueryHandler applies no age limit when this is 0
+ UnlimitedWindow = _orderSettings.NumberOfDaysMerchandiseReturnAvailable <= 0,
+ //optional declarations from the settings screen; NotSpecified publishes nothing
+ ReturnFees = _orderSettings.MerchandiseReturnFees switch {
+ MerchandiseReturnFees.Free => "https://schema.org/FreeReturn",
+ MerchandiseReturnFees.CustomerPays => "https://schema.org/ReturnFeesCustomerResponsibility",
+ _ => null
+ },
+ ReturnMethod = _orderSettings.MerchandiseReturnMethod switch {
+ MerchandiseReturnMethod.ByMail => "https://schema.org/ReturnByMail",
+ MerchandiseReturnMethod.InStore => "https://schema.org/ReturnInStore",
+ _ => null
+ },
+ CountryCodes = (await _countryService.GetAllCountriesForShipping(storeId: request.Store.Id))
+ .Select(x => x.TwoLetterIsoCode)
+ .Where(x => !string.IsNullOrWhiteSpace(x))
+ .Distinct()
+ .ToList()
+ };
+
+ return model;
+ }
+}
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
index f08c90755..6c52c308a 100644
--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
@@ -263,6 +263,19 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
#endregion
+ #region Structured data
+
+ //only the page's own product emits JSON-LD (Partials/ProductStructuredData)
+ if (!isAssociatedProduct)
+ model.StructuredData = await _mediator.Send(new GetProductStructuredData {
+ Product = product,
+ Store = _contextAccessor.StoreContext.CurrentStore,
+ Customer = _contextAccessor.WorkContext.CurrentCustomer,
+ Currency = _contextAccessor.WorkContext.WorkingCurrency
+ });
+
+ #endregion
+
#region Tier prices
if (product.TierPrices.Any() && await _permissionService.Authorize(StandardPermission.DisplayPrices))
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductStructuredDataHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductStructuredDataHandler.cs
new file mode 100644
index 000000000..bec3cb3d6
--- /dev/null
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductStructuredDataHandler.cs
@@ -0,0 +1,122 @@
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Prices;
+using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Domain.Orders;
+using Grand.Domain.Shipping;
+using Grand.Web.Features.Models.Products;
+using Grand.Web.Models.Catalog;
+using Grand.Mediator;
+
+namespace Grand.Web.Features.Handlers.Products;
+
+public class GetProductStructuredDataHandler : IRequestHandler<GetProductStructuredData, ProductStructuredDataModel>
+{
+ private readonly ICountryService _countryService;
+ private readonly ICurrencyService _currencyService;
+ private readonly OrderSettings _orderSettings;
+ private readonly IPricingService _pricingService;
+ private readonly ShippingSettings _shippingSettings;
+ private readonly ITaxService _taxService;
+
+ public GetProductStructuredDataHandler(
+ ICountryService countryService,
+ ICurrencyService currencyService,
+ IPricingService pricingService,
+ ITaxService taxService,
+ OrderSettings orderSettings,
+ ShippingSettings shippingSettings)
+ {
+ _countryService = countryService;
+ _currencyService = currencyService;
+ _pricingService = pricingService;
+ _taxService = taxService;
+ _orderSettings = orderSettings;
+ _shippingSettings = shippingSettings;
+ }
+
+ public async Task<ProductStructuredDataModel> Handle(GetProductStructuredData request,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(request.Product);
+
+ var product = request.Product;
+ var model = new ProductStructuredDataModel();
+
+ //the Approved* totals count approved reviews only (UpdateProductReviewTotalsCommandHandler),
+ //and they are exactly what the reviews tab lists - so the rating describes reviews on the page
+ if (product.AllowCustomerReviews && product.ApprovedTotalReviews > 0)
+ {
+ model.RatingValue = Math.Round((double)product.ApprovedRatingSum / product.ApprovedTotalReviews, 2);
+ model.ReviewCount = product.ApprovedTotalReviews;
+ }
+
+ if (product.IsShipEnabled)
+ {
+ model.ShippingRate = await ShippingRate(request);
+ model.HandlingTime = DayRange(_shippingSettings.HandlingTimeMinDays, _shippingSettings.HandlingTimeMaxDays);
+ model.TransitTime = DayRange(_shippingSettings.TransitTimeMinDays, _shippingSettings.TransitTimeMaxDays);
+ }
+
+ //the Organization declares the store's return policy; a product excluded from returns must say so
+ model.ReturnsNotPermitted = _orderSettings.MerchandiseReturnsEnabled && product.NotReturnable;
+
+ if (model.HasShippingDetails || model.ReturnsNotPermitted)
+ model.CountryCodes = (await _countryService.GetAllCountriesForShipping(storeId: request.Store?.Id ?? ""))
+ .Select(x => x.TwoLetterIsoCode)
+ .Where(x => !string.IsNullOrWhiteSpace(x))
+ .Distinct()
+ .ToList();
+
+ return model;
+ }
+
+ /// <summary>
+ /// What shipping this product on its own costs, in the request currency, or null when the store's
+ /// data does not say. Mirrors OrderCalculationService.IsFreeShipping / AdjustShippingRate for a cart
+ /// holding just this product; the shipping providers are never asked - their rates depend on the
+ /// address and the cart, so the fallback is the rate the store declares in ShippingSettings.
+ /// Visitor-specific free shipping (customer, customer group) and shipping discounts are left out:
+ /// they are not a property of the product.
+ /// </summary>
+ private async Task<double?> ShippingRate(GetProductStructuredData request)
+ {
+ var product = request.Product;
+ if (product.IsFreeShipping)
+ return 0;
+
+ if (request.Customer == null || request.Currency == null)
+ return null;
+
+ //free over X compares the cart subtotal, in the working currency, with the threshold as entered
+ if (_shippingSettings.FreeShippingOverXEnabled && await UnitPrice(request) > _shippingSettings.FreeShippingOverXValue)
+ return 0;
+
+ if (_shippingSettings.DefaultShippingRate is not >= 0)
+ return null;
+
+ //entered like a shipping method's rate: primary store currency, converted the way the rate providers
+ //convert theirs, plus the product's own surcharge, taxed as shipping
+ var rate = await _currencyService.ConvertFromPrimaryStoreCurrency(
+ _shippingSettings.DefaultShippingRate.Value + product.AdditionalShippingCharge, request.Currency);
+ rate = (await _taxService.GetShippingPrice(rate, request.Customer, request.Store)).shippingPrice;
+ return RoundingHelper.RoundPrice(rate, request.Currency);
+ }
+
+ private async Task<double> UnitPrice(GetProductStructuredData request)
+ {
+ var finalPrice = (await _pricingService.GetFinalPrice(request.Product, request.Customer, request.Store,
+ request.Currency, includeDiscounts: true)).finalPrice;
+ return (await _taxService.GetProductPrice(request.Product, finalPrice,
+ _shippingSettings.FreeShippingOverXIncludingTax, request.Customer, request.Store)).productprice;
+ }
+
+ //the settings screen does not validate these optional fields, so a pair that cannot be
+ //true (a negative day count, min above max) is dropped rather than published
+ private static ProductStructuredDataModel.DayRangeModel DayRange(int? min, int? max)
+ {
+ if (min < 0 || max < 0 || min > max) return null;
+ if (min == null && max == null) return null;
+ return new ProductStructuredDataModel.DayRangeModel { Min = min, Max = max };
+ }
+}
diff --git a/src/Web/Grand.Web/Features/Models/Common/GetSiteStructuredData.cs b/src/Web/Grand.Web/Features/Models/Common/GetSiteStructuredData.cs
new file mode 100644
index 000000000..bba3e2ecd
--- /dev/null
+++ b/src/Web/Grand.Web/Features/Models/Common/GetSiteStructuredData.cs
@@ -0,0 +1,9 @@
+using Grand.Web.Models.Common;
+using Grand.Mediator;
+
+namespace Grand.Web.Features.Models.Common;
+
+public class GetSiteStructuredData : IRequest<SiteStructuredDataModel>
+{
+ public Domain.Stores.Store Store { get; set; }
+}
diff --git a/src/Web/Grand.Web/Features/Models/Products/GetProductStructuredData.cs b/src/Web/Grand.Web/Features/Models/Products/GetProductStructuredData.cs
new file mode 100644
index 000000000..0e33095a0
--- /dev/null
+++ b/src/Web/Grand.Web/Features/Models/Products/GetProductStructuredData.cs
@@ -0,0 +1,19 @@
+using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Directory;
+using Grand.Web.Models.Catalog;
+using Grand.Mediator;
+
+namespace Grand.Web.Features.Models.Products;
+
+public class GetProductStructuredData : IRequest<ProductStructuredDataModel>
+{
+ public Product Product { get; set; }
+ public Domain.Stores.Store Store { get; set; }
+ public Customer Customer { get; set; }
+
+ /// <summary>
+ /// The currency the offer's price is published in
+ /// </summary>
+ public Currency Currency { get; set; }
+}
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductDetailsModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductDetailsModel.cs
index 7debe2c55..c7de9e21b 100644
--- a/src/Web/Grand.Web/Models/Catalog/ProductDetailsModel.cs
+++ b/src/Web/Grand.Web/Models/Catalog/ProductDetailsModel.cs
@@ -73,6 +73,7 @@ public class ProductDetailsModel : BaseEntityModel
public IList<ProductSpecificationModel> ProductSpecifications { get; set; } = new List<ProductSpecificationModel>();
public IList<CollectionModel> ProductCollections { get; set; } = new List<CollectionModel>();
public ProductReviewOverviewModel ProductReviewOverview { get; set; } = new();
+ public ProductStructuredDataModel StructuredData { get; set; } = new();
public IList<TierPriceModel> TierPrices { get; set; } = new List<TierPriceModel>();
diff --git a/src/Web/Grand.Web/Models/Catalog/ProductStructuredDataModel.cs b/src/Web/Grand.Web/Models/Catalog/ProductStructuredDataModel.cs
new file mode 100644
index 000000000..500695309
--- /dev/null
+++ b/src/Web/Grand.Web/Models/Catalog/ProductStructuredDataModel.cs
@@ -0,0 +1,53 @@
+namespace Grand.Web.Models.Catalog;
+
+/// <summary>
+/// Facts for the product JSON-LD that the rest of ProductDetailsModel does not carry.
+/// Each one is set only when the store's own data makes it true - an unset value means
+/// "say nothing", never "false".
+/// </summary>
+public class ProductStructuredDataModel
+{
+ /// <summary>
+ /// Average of the approved reviews; null when reviews are off or none is approved
+ /// </summary>
+ public double? RatingValue { get; set; }
+
+ public int ReviewCount { get; set; }
+
+ /// <summary>
+ /// Cost of shipping this product on its own, in the offer's currency: 0 for free shipping,
+ /// otherwise the store's declared default rate; null when neither applies
+ /// </summary>
+ public double? ShippingRate { get; set; }
+
+ /// <summary>
+ /// Business days from order to handover to the carrier, as the store declares them
+ /// (ShippingSettings); null when the product does not ship or nothing usable is declared
+ /// </summary>
+ public DayRangeModel HandlingTime { get; set; }
+
+ /// <summary>
+ /// Business days the carrier needs, as the store declares them (ShippingSettings)
+ /// </summary>
+ public DayRangeModel TransitTime { get; set; }
+
+ /// <summary>
+ /// Merchandise returns are on for the store, but this product is excluded from them -
+ /// the offer has to override the Organization-level return policy
+ /// </summary>
+ public bool ReturnsNotPermitted { get; set; }
+
+ /// <summary>
+ /// ISO 3166-1 alpha-2 codes of the countries the store ships to; filled only when
+ /// shipping details or ReturnsNotPermitted need them
+ /// </summary>
+ public IList<string> CountryCodes { get; set; } = new List<string>();
+
+ public bool HasShippingDetails => ShippingRate != null || HandlingTime != null || TransitTime != null;
+
+ public class DayRangeModel
+ {
+ public int? Min { get; set; }
+ public int? Max { get; set; }
+ }
+}
diff --git a/src/Web/Grand.Web/Models/Common/SiteStructuredDataModel.cs b/src/Web/Grand.Web/Models/Common/SiteStructuredDataModel.cs
new file mode 100644
index 000000000..6fe8e8df1
--- /dev/null
+++ b/src/Web/Grand.Web/Models/Common/SiteStructuredDataModel.cs
@@ -0,0 +1,47 @@
+namespace Grand.Web.Models.Common;
+
+/// <summary>
+/// Facts for the site-wide JSON-LD (Organization and WebSite). Urls that depend on the
+/// request are built in the view; everything here is store data.
+/// </summary>
+public class SiteStructuredDataModel
+{
+ public string StoreName { get; set; }
+
+ /// <summary>
+ /// Logo url as the picture service returns it (may be relative)
+ /// </summary>
+ public string LogoUrl { get; set; }
+
+ public IList<string> SameAs { get; set; } = new List<string>();
+
+ /// <summary>
+ /// Null when merchandise returns are off - then no return policy is declared at all
+ /// </summary>
+ public ReturnPolicyModel ReturnPolicy { get; set; }
+
+ public class ReturnPolicyModel
+ {
+ /// <summary>
+ /// No day limit is configured. A configured limit is not published as merchantReturnDays:
+ /// the store counts it from the order date, schema.org from delivery, so the number
+ /// would promise a longer window than the store gives.
+ /// </summary>
+ public bool UnlimitedWindow { get; set; }
+
+ /// <summary>
+ /// schema.org ReturnFeesEnumeration member, or null when the store has not declared it
+ /// </summary>
+ public string ReturnFees { get; set; }
+
+ /// <summary>
+ /// schema.org ReturnMethodEnumeration member, or null when the store has not declared it
+ /// </summary>
+ public string ReturnMethod { get; set; }
+
+ /// <summary>
+ /// ISO 3166-1 alpha-2 codes of the countries the store ships to
+ /// </summary>
+ public IList<string> CountryCodes { get; set; } = new List<string>();
+ }
+}
diff --git a/src/Web/Grand.Web/Views/Product/Partials/ProductStructuredData.cshtml b/src/Web/Grand.Web/Views/Product/Partials/ProductStructuredData.cshtml
index 14484b394..1edd31b31 100644
--- a/src/Web/Grand.Web/Views/Product/Partials/ProductStructuredData.cshtml
+++ b/src/Web/Grand.Web/Views/Product/Partials/ProductStructuredData.cshtml
@@ -49,6 +49,10 @@
["@type"] = "Brand", ["name"] = Model.BrandModel.Name
};
+ //rating, shipping and return facts come from Model.StructuredData, worked out in
+ //GetProductStructuredDataHandler - this view only shapes them into schema.org
+ var facts = Model.StructuredData;
+
//no offer at all rather than a misleading one: a hidden or on-request price is
//not a price, and an auction's current bid is not an offer either
var price = Model.ProductPrice;
@@ -62,17 +66,61 @@
["url"] = productUrl
};
if (Model.Availability.HasValue) offer["availability"] = Model.Availability.ToSchemaOrgUrl();
+
+ if (facts.HasShippingDetails)
+ {
+ var shipping = new Dictionary<string, object> {
+ ["@type"] = "OfferShippingDetails"
+ };
+ //a rate only when it is known - see GetProductStructuredDataHandler.ShippingRate
+ if (facts.ShippingRate is { } shippingRate)
+ shipping["shippingRate"] = new Dictionary<string, object> {
+ ["@type"] = "MonetaryAmount",
+ ["value"] = shippingRate.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ ["currency"] = price.CurrencyCode
+ };
+ if (facts.HandlingTime != null || facts.TransitTime != null)
+ {
+ Dictionary<string, object> Days(ProductStructuredDataModel.DayRangeModel range)
+ {
+ var value = new Dictionary<string, object> { ["@type"] = "QuantitativeValue", ["unitCode"] = "DAY" };
+ if (range.Min is { } min) value["minValue"] = min;
+ if (range.Max is { } max) value["maxValue"] = max;
+ return value;
+ }
+
+ var deliveryTime = new Dictionary<string, object> { ["@type"] = "ShippingDeliveryTime" };
+ if (facts.HandlingTime != null) deliveryTime["handlingTime"] = Days(facts.HandlingTime);
+ if (facts.TransitTime != null) deliveryTime["transitTime"] = Days(facts.TransitTime);
+ shipping["deliveryTime"] = deliveryTime;
+ }
+ if (facts.CountryCodes.Count > 0)
+ shipping["shippingDestination"] = facts.CountryCodes
+ .Select(x => new Dictionary<string, object> { ["@type"] = "DefinedRegion", ["addressCountry"] = x })
+ .ToArray();
+ offer["shippingDetails"] = shipping;
+ }
+
+ //overrides the store-wide policy declared on the Organization (Components/SiteStructuredData)
+ if (facts.ReturnsNotPermitted)
+ {
+ var policy = new Dictionary<string, object> {
+ ["@type"] = "MerchantReturnPolicy",
+ ["returnPolicyCategory"] = "https://schema.org/MerchantReturnNotPermitted"
+ };
+ if (facts.CountryCodes.Count > 0) policy["applicableCountry"] = facts.CountryCodes;
+ offer["hasMerchantReturnPolicy"] = policy;
+ }
+
product["offers"] = offer;
}
- var reviews = Model.ProductReviewOverview;
- if (reviews is { AllowCustomerReviews: true, TotalReviews: > 0 })
+ if (facts.RatingValue is { } ratingValue)
{
product["aggregateRating"] = new Dictionary<string, object> {
["@type"] = "AggregateRating",
- ["ratingValue"] = Math.Round(reviews.AvgRating, 2)
- .ToString(System.Globalization.CultureInfo.InvariantCulture),
- ["reviewCount"] = reviews.TotalReviews
+ ["ratingValue"] = ratingValue.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ ["reviewCount"] = facts.ReviewCount
};
}
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/SiteStructuredData.cshtml b/src/Web/Grand.Web/Views/Shared/Components/SiteStructuredData/Default.cshtml
similarity index 51%
rename from src/Web/Grand.Web/Views/Shared/Partials/SiteStructuredData.cshtml
rename to src/Web/Grand.Web/Views/Shared/Components/SiteStructuredData/Default.cshtml
index cded63c58..7fa2cf416 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/SiteStructuredData.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Components/SiteStructuredData/Default.cshtml
@@ -1,8 +1,5 @@
-@using Grand.Business.Core.Interfaces.Storage
@using System.Text.Json
-@inject IContextAccessor contextAccessor
-@inject StoreInformationSettings storeInformationSettings
-@inject IPictureService pictureService
+@model SiteStructuredDataModel
@*
Site-wide structured data: Organization and WebSite.
@@ -11,47 +8,42 @@
engine the store's name, logo or social profiles, and nothing declared a search
endpoint for the sitelinks searchbox.
- Kept to facts the store already publishes. Emitted once per page from _Layout;
- search engines de-duplicate Organization across a site.
+ Kept to facts the store already publishes; they are gathered in
+ GetSiteStructuredDataHandler, this view only shapes them. Emitted once per page
+ from _Layout; search engines de-duplicate Organization across a site.
*@
@{
var request = Url.ActionContext.HttpContext.Request;
var homeUrl = Url.RouteUrl("HomePage", null, request.Scheme);
var searchUrl = Url.RouteUrl("ProductSearch", null, request.Scheme);
- var storeName = contextAccessor.StoreContext.CurrentStore.Name;
-
- var logoUrl = string.Empty;
- if (!string.IsNullOrEmpty(storeInformationSettings.LogoPictureId))
- {
- var logo = await pictureService.GetPictureUrl(storeInformationSettings.LogoPictureId);
- if (!string.IsNullOrEmpty(logo))
- logoUrl = new Uri(new Uri($"{request.Scheme}://{request.Host}"), logo).ToString();
- }
-
- //social profiles the store has actually filled in - sameAs is what links the
- //site to an existing knowledge-graph entity
- var sameAs = new[] {
- storeInformationSettings.FacebookLink,
- storeInformationSettings.TwitterLink,
- storeInformationSettings.YoutubeLink,
- storeInformationSettings.InstagramLink,
- storeInformationSettings.LinkedInLink,
- storeInformationSettings.PinterestLink
- }
- .Where(x => !string.IsNullOrWhiteSpace(x))
- .ToArray();
var organization = new Dictionary<string, object> {
["@type"] = "Organization",
- ["name"] = storeName,
+ ["name"] = Model.StoreName,
["url"] = homeUrl
};
- if (!string.IsNullOrEmpty(logoUrl)) organization["logo"] = logoUrl;
- if (sameAs.Length > 0) organization["sameAs"] = sameAs;
+ if (!string.IsNullOrEmpty(Model.LogoUrl))
+ organization["logo"] = new Uri(new Uri($"{request.Scheme}://{request.Host}"), Model.LogoUrl).ToString();
+ if (Model.SameAs.Count > 0) organization["sameAs"] = Model.SameAs;
+
+ //store-wide; a product excluded from returns overrides it on its Offer (Partials/ProductStructuredData)
+ if (Model.ReturnPolicy is { } returns)
+ {
+ var policy = new Dictionary<string, object> {
+ ["@type"] = "MerchantReturnPolicy",
+ ["returnPolicyCategory"] = returns.UnlimitedWindow
+ ? "https://schema.org/MerchantReturnUnlimitedWindow"
+ : "https://schema.org/MerchantReturnFiniteReturnWindow"
+ };
+ if (returns.CountryCodes.Count > 0) policy["applicableCountry"] = returns.CountryCodes;
+ if (returns.ReturnFees != null) policy["returnFees"] = returns.ReturnFees;
+ if (returns.ReturnMethod != null) policy["returnMethod"] = returns.ReturnMethod;
+ organization["hasMerchantReturnPolicy"] = policy;
+ }
var website = new Dictionary<string, object> {
["@type"] = "WebSite",
- ["name"] = storeName,
+ ["name"] = Model.StoreName,
["url"] = homeUrl,
["potentialAction"] = new Dictionary<string, object> {
["@type"] = "SearchAction",
@@ -73,4 +65,6 @@
//out of the block; the default encoder escapes it
var json = JsonSerializer.Serialize(graph, new JsonSerializerOptions { WriteIndented = false });
}
-<script type="application/ld+json">@Html.Raw(json)</script>
+@*written out whole, as in Partials/ProductStructuredData: rendered as markup the type
+ attribute reached the page as "application/ld&#x2B;json", which crawlers reading raw HTML miss*@
[email protected]($"<script type=\"application/ld+json\">{json}</script>")
diff --git a/src/Web/Grand.Web/Views/Shared/_Layout.cshtml b/src/Web/Grand.Web/Views/Shared/_Layout.cshtml
index a3398f02c..3e0baf48f 100644
--- a/src/Web/Grand.Web/Views/Shared/_Layout.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/_Layout.cshtml
@@ -16,7 +16,7 @@
<partial name="Partials/Favicons"/>
<resources asp-type="HeadLink"/>
<resources asp-type="HeadScript"/>
- <partial name="Partials/SiteStructuredData"/>
+ @await Component.InvokeAsync("SiteStructuredData")
@await RenderSectionAsync("head", false)
</head>
<body>