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.

Migrate 'Reservation' region into BaseProductController (ARCH-001 Phase 1)

KrzysztofPajake55e5ab06698
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
index e97802293..fb2482a17 100644
--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
@@ -25,6 +25,7 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
+using System.Linq.Expressions;
namespace Grand.Web.Admin.Tests.Controllers;
@@ -60,6 +61,7 @@ public class BaseProductControllerTests
private Mock<ITranslationService> _translationServiceMock;
private Mock<IAdminDataScope<Product>> _scopeMock;
private Mock<IPermissionService> _permissionServiceMock;
+ private Mock<IProductReservationService> _productReservationServiceMock;
[TestInitialize]
public void Setup()
@@ -86,13 +88,15 @@ public class BaseProductControllerTests
var languageServiceMock = new Mock<ILanguageService>();
languageServiceMock.Setup(l => l.GetAllLanguages(true, It.IsAny<string>())).ReturnsAsync(new List<Domain.Localization.Language>());
+ _productReservationServiceMock = new Mock<IProductReservationService>();
+
_controller = new TestProductController(
_productViewModelServiceMock.Object,
_productServiceMock.Object,
new Mock<IInventoryManageService>().Object,
languageServiceMock.Object,
_translationServiceMock.Object,
- new Mock<IProductReservationService>().Object,
+ _productReservationServiceMock.Object,
new Mock<IAuctionService>().Object,
new Mock<IDateTimeService>().Object,
_permissionServiceMock.Object,
@@ -5202,4 +5206,324 @@ public class BaseProductControllerTests
_productViewModelServiceMock.Verify(
s => s.DeleteProductAttributeCombinationTierPrices(product, combination, tierPrice), Times.Once);
}
+
+ // --- Reservation -------------------------------------------------------------------------------
+ // ARCH-001 Phase 1 Task 8 row 23. Admin's originals had no ownership check at all on any of these
+ // four actions; Store used CanAccessProduct; Vendor used CheckAccessToProduct (List) or a combined
+ // null-or-HasAccessToProduct throw (the other three) - all normalized to scope.HasAccess.
+
+ private static ProductReservation NewReservation(string id, string productId, string orderId = "") =>
+ new() { Id = id, ProductId = productId, OrderId = orderId, Date = DateTime.UtcNow };
+
+ // --- ListReservations ----------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task ListReservations_ScopeDeniesAccess_ReturnsKendoGridError_DoesNotQuery()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);
+
+ var result = await _controller.ListReservations(
+ new Grand.Web.Common.DataSource.DataSourceRequest(), "p1");
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.GetProductReservationsByProductId(It.IsAny<string>(), It.IsAny<bool?>(), It.IsAny<DateTime?>(),
+ It.IsAny<int>(), It.IsAny<int>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ListReservations_ScopeGrantsAccess_ReturnsGrid()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ var reservations = new PagedList<ProductReservation>(
+ new List<ProductReservation> { NewReservation("r1", "p1") }, 0, 10);
+ _productReservationServiceMock
+ .Setup(s => s.GetProductReservationsByProductId("p1", null, null, 0, 10))
+ .ReturnsAsync(reservations);
+
+ var result = await _controller.ListReservations(
+ new Grand.Web.Common.DataSource.DataSourceRequest { Page = 1, PageSize = 10 }, "p1");
+
+ var json = result as JsonResult;
+ Assert.IsNotNull(json);
+ var gridModel = json.Value as Grand.Web.Common.DataSource.DataSourceResult;
+ Assert.IsNotNull(gridModel);
+ Assert.AreEqual(1, gridModel.Total);
+ }
+
+ // --- GenerateCalendar ------------------------------------------------------------------------------
+
+ private static ProductModel.GenerateCalendarModel ValidCalendarModel(IntervalUnit unit = IntervalUnit.Day) => new() {
+ StartDate = new DateTime(2026, 1, 1),
+ EndDate = new DateTime(2026, 1, 1),
+ StartTime = new DateTime(2026, 1, 1, 8, 0, 0),
+ EndTime = new DateTime(2026, 1, 1, 18, 0, 0),
+ Interval = 1,
+ IntervalUnit = (int)unit,
+ Quantity = 1,
+ Resource = "room1",
+ // 2026-01-01 is a Thursday.
+ Thursday = true
+ };
+
+ [TestMethod]
+ public async Task GenerateCalendar_MissingProduct_Throws()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("missing")).ReturnsAsync((Product)null);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(
+ () => _controller.GenerateCalendar("missing", ValidCalendarModel()));
+ }
+
+ [TestMethod]
+ public async Task GenerateCalendar_ScopeDeniesAccess_ReturnsErrorsJson_DoesNotUpdate()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);
+
+ var result = await _controller.GenerateCalendar("p1", ValidCalendarModel());
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.InsertProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task GenerateCalendar_InvalidModelState_ReturnsErrorsJson_DoesNotInsert()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ _productReservationServiceMock
+ .Setup(s => s.GetProductReservationsByProductId("p1", null, null))
+ .ReturnsAsync(new PagedList<ProductReservation>(new List<ProductReservation>(), 0, int.MaxValue));
+ _controller.ModelState.AddModelError("Resource", "Required");
+
+ var result = await _controller.GenerateCalendar("p1", ValidCalendarModel());
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(
+ s => s.InsertProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task GenerateCalendar_ScopeGrantsAccess_Valid_InsertsReservationAndUpdatesProductFields()
+ {
+ var product = new Product { Id = "p1", IntervalUnitId = IntervalUnit.Day };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ _productReservationServiceMock
+ .Setup(s => s.GetProductReservationsByProductId("p1", null, null))
+ .ReturnsAsync(new PagedList<ProductReservation>(new List<ProductReservation>(), 0, int.MaxValue));
+
+ var result = await _controller.GenerateCalendar("p1", ValidCalendarModel());
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(
+ s => s.InsertProductReservation(It.Is<ProductReservation>(r =>
+ r.ProductId == "p1" && r.Resource == "room1")), Times.Once);
+ _productServiceMock.Verify(
+ s => s.UpdateProductField(product, It.IsAny<Expression<Func<Product, int>>>(), 1), Times.Once);
+ }
+
+ // --- ClearCalendar ----------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task ClearCalendar_MissingProduct_Throws()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("missing")).ReturnsAsync((Product)null);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() => _controller.ClearCalendar("missing"));
+ }
+
+ [TestMethod]
+ public async Task ClearCalendar_ScopeDeniesAccess_Throws_DoesNotDelete()
+ {
+ // Throws rather than returning Json({errors}): CreateOrUpdate.Calendar.cshtml's success
+ // callback for this action never reads the response body (no else branch) on any of the three
+ // hosts, so a 200 response would silently refresh the grid as if the clear succeeded.
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() => _controller.ClearCalendar("p1"));
+
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ClearCalendar_ScopeGrantsAccess_DeletesAllReservations()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ var reservation = NewReservation("r1", "p1");
+ _productReservationServiceMock
+ .Setup(s => s.GetProductReservationsByProductId("p1", true, null))
+ .ReturnsAsync(new PagedList<ProductReservation>(new List<ProductReservation> { reservation }, 0, int.MaxValue));
+
+ var result = await _controller.ClearCalendar("p1");
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(s => s.DeleteProductReservation(reservation), Times.Once);
+ }
+
+ // --- ClearOld ---------------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task ClearOld_MissingProduct_Throws()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("missing")).ReturnsAsync((Product)null);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() => _controller.ClearOld("missing"));
+ }
+
+ [TestMethod]
+ public async Task ClearOld_ScopeDeniesAccess_Throws_DoesNotDelete()
+ {
+ // See the comment on ClearCalendar_ScopeDeniesAccess_Throws_DoesNotDelete above - same view-layer
+ // gap applies to this action's response handling.
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() => _controller.ClearOld("p1"));
+
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ClearOld_ScopeGrantsAccess_DeletesOnlyPastReservations()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ var oldReservation = new ProductReservation { Id = "old", ProductId = "p1", Date = DateTime.UtcNow.AddDays(-1) };
+ var futureReservation = new ProductReservation { Id = "future", ProductId = "p1", Date = DateTime.UtcNow.AddDays(1) };
+ _productReservationServiceMock
+ .Setup(s => s.GetProductReservationsByProductId("p1", true, null))
+ .ReturnsAsync(new PagedList<ProductReservation>(
+ new List<ProductReservation> { oldReservation, futureReservation }, 0, int.MaxValue));
+
+ var result = await _controller.ClearOld("p1");
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(s => s.DeleteProductReservation(oldReservation), Times.Once);
+ _productReservationServiceMock.Verify(s => s.DeleteProductReservation(futureReservation), Times.Never);
+ }
+
+ // --- ProductReservationDelete ------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task ProductReservationDelete_MissingProduct_Throws()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("missing")).ReturnsAsync((Product)null);
+ var model = new ProductModel.ReservationModel { ProductId = "missing", ReservationId = "r1" };
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() => _controller.ProductReservationDelete(model));
+ }
+
+ [TestMethod]
+ public async Task ProductReservationDelete_ScopeDeniesAccess_ReturnsKendoGridError_DoesNotDelete()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false);
+ var model = new ProductModel.ReservationModel { ProductId = "p1", ReservationId = "r1" };
+
+ var result = await _controller.ProductReservationDelete(model);
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ // Regression guard for a real cross-product IDOR found in Store's and Vendor's original code: the
+ // access check ran against model.ProductId while the delete ran against model.ReservationId, with no
+ // check that the two referred to the same product. A caller with access to *any* product could pass
+ // that product's id for the access check while supplying the ReservationId of a reservation belonging
+ // to a different, unowned product, deleting it.
+ [TestMethod]
+ public async Task ProductReservationDelete_ReservationBelongsToDifferentProduct_ReturnsKendoGridError_DoesNotDelete()
+ {
+ var ownedProduct = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(ownedProduct);
+ _scopeMock.Setup(s => s.HasAccess(ownedProduct)).ReturnsAsync(true);
+ var foreignReservation = NewReservation("r1", "p2");
+ _productReservationServiceMock.Setup(s => s.GetProductReservation("r1")).ReturnsAsync(foreignReservation);
+ var model = new ProductModel.ReservationModel { ProductId = "p1", ReservationId = "r1" };
+
+ var result = await _controller.ProductReservationDelete(model);
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.Products.Permissions"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ProductReservationDelete_ReservationHasOrder_ReturnsErrorsJson_DoesNotDelete()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ var reservation = NewReservation("r1", "p1", "order1");
+ _productReservationServiceMock.Setup(s => s.GetProductReservation("r1")).ReturnsAsync(reservation);
+ var model = new ProductModel.ReservationModel { ProductId = "p1", ReservationId = "r1" };
+
+ var result = await _controller.ProductReservationDelete(model);
+
+ var json = result as JsonResult;
+ Assert.IsNotNull(json);
+ var gridModel = json.Value as Grand.Web.Common.DataSource.DataSourceResult;
+ Assert.IsNotNull(gridModel);
+ Assert.IsNotNull(gridModel.Errors);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.Catalog.ProductReservations.CantDeleteWithOrder"), Times.Once);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ProductReservationDelete_ScopeGrantsAccess_SameProduct_Deletes()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ var reservation = NewReservation("r1", "p1");
+ _productReservationServiceMock.Setup(s => s.GetProductReservation("r1")).ReturnsAsync(reservation);
+ var model = new ProductModel.ReservationModel { ProductId = "p1", ReservationId = "r1" };
+
+ var result = await _controller.ProductReservationDelete(model);
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(s => s.DeleteProductReservation(reservation), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task ProductReservationDelete_ReservationNotFound_ReturnsEmptyJson_NoOp()
+ {
+ var product = new Product { Id = "p1" };
+ _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product);
+ _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(true);
+ _productReservationServiceMock.Setup(s => s.GetProductReservation("missing")).ReturnsAsync((ProductReservation)null);
+ var model = new ProductModel.ReservationModel { ProductId = "p1", ReservationId = "missing" };
+
+ var result = await _controller.ProductReservationDelete(model);
+
+ Assert.IsInstanceOfType<JsonResult>(result);
+ _productReservationServiceMock.Verify(
+ s => s.DeleteProductReservation(It.IsAny<ProductReservation>()), Times.Never);
+ }
}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs
index 85c245d5d..281242880 100644
--- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductController.cs
@@ -3084,4 +3084,249 @@ public abstract class BaseProductController(
}
#endregion
+
+ #region Reservation
+
+ [PermissionAuthorizeAction(PermissionActionName.Preview)]
+ [HttpPost]
+ public async Task<IActionResult> ListReservations(DataSourceRequest command, string productId)
+ {
+ var product = await productService.GetProductById(productId);
+
+ // HasAccess (strict): mirrors Store's CanAccessProduct and Vendor's CheckAccessToProduct checks;
+ // Admin's original had no check at all - normalized to scope.HasAccess for all three hosts.
+ if (!await scope.HasAccess(product))
+ return ErrorForKendoGridJson(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
+
+ var reservations =
+ await productReservationService.GetProductReservationsByProductId(productId, null, null,
+ command.Page - 1, command.PageSize);
+ var reservationModel = reservations
+ .Select(x => new ProductModel.ReservationModel {
+ ReservationId = x.Id,
+ Date = x.Date,
+ OrderId = x.OrderId,
+ ProductId = x.ProductId,
+ Parameter = x.Parameter,
+ Resource = x.Resource,
+ Duration = x.Duration
+ }).ToList();
+
+ var gridModel = new DataSourceResult {
+ Data = reservationModel,
+ Total = reservations.TotalCount
+ };
+
+ return Json(gridModel);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ [HttpPost]
+ public async Task<IActionResult> GenerateCalendar(string productId, ProductModel.GenerateCalendarModel model)
+ {
+ var product = await productService.GetProductById(productId);
+ if (product == null)
+ throw new ArgumentException("No product found with the specified id");
+
+ // HasAccess (strict), returning the same {errors:...} JSON shape as Store's CanAccessProduct
+ // check (the client's ajax success handler reads data.errors on denial). Vendor's original threw
+ // ArgumentException for the combined null-or-access-denied case instead, which the client's
+ // Kendo/ajax error callback only surfaces as a generic "Error" alert - returning the JSON errors
+ // message here is strictly more informative and closes Admin's original gap (no check at all).
+ if (!await scope.HasAccess(product))
+ return Json(new { errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions") });
+
+ var reservations = await productReservationService.GetProductReservationsByProductId(productId, null, null);
+ if (reservations.Any())
+ if (((product.IntervalUnitId == IntervalUnit.Minute || product.IntervalUnitId == IntervalUnit.Hour) &&
+ (IntervalUnit)model.Interval == IntervalUnit.Day) ||
+ (product.IntervalUnitId == IntervalUnit.Day &&
+ ((IntervalUnit)model.IntervalUnit == IntervalUnit.Minute ||
+ (IntervalUnit)model.IntervalUnit == IntervalUnit.Hour)))
+ return Json(new {
+ errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.CannotChangeInterval")
+ });
+
+ if (!ModelState.IsValid)
+ {
+ var error = (Dictionary<string, Dictionary<string, object>>)ModelState.SerializeErrors();
+ var s = "";
+ foreach (var error1 in error)
+ foreach (var error2 in error1.Value)
+ {
+ var v = (string[])error2.Value;
+ s += v[0] + "\n";
+ }
+
+ return Json(new { errors = s });
+ }
+
+ //update fields on product
+ await productService.UpdateProductField(product, x => x.Interval, model.Interval);
+ await productService.UpdateProductField(product, x => x.IntervalUnitId, (IntervalUnit)model.IntervalUnit);
+ await productService.UpdateProductField(product, x => x.IncBothDate, model.IncBothDate);
+
+ var minutesToAdd = (IntervalUnit)model.IntervalUnit switch {
+ IntervalUnit.Minute => model.Interval,
+ IntervalUnit.Hour => model.Interval * 60,
+ IntervalUnit.Day => model.Interval * 60 * 24,
+ _ => 0
+ };
+
+ var _hourFrom = model.StartTime.Hour;
+ var _minutesFrom = model.StartTime.Minute;
+ var _hourTo = model.EndTime.Hour;
+ var _minutesTo = model.EndTime.Minute;
+ var _dateFrom = new DateTime(model.StartDate.Value.Year, model.StartDate.Value.Month, model.StartDate.Value.Day,
+ 0, 0, 0, 0);
+ var _dateTo = new DateTime(model.EndDate.Value.Year, model.EndDate.Value.Month, model.EndDate.Value.Day, 23, 59,
+ 59, 999);
+ if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Day)
+ {
+ model.Quantity = 1;
+ model.Parameter = "";
+ }
+ else
+ {
+ model.Resource = "";
+ }
+
+ var dates = new List<DateTime>();
+ var counter = 0;
+ for (var iterator = _dateFrom; iterator <= _dateTo; iterator += new TimeSpan(0, minutesToAdd, 0))
+ {
+ if ((IntervalUnit)model.IntervalUnit != IntervalUnit.Day)
+ {
+ if (iterator.Hour >= _hourFrom && iterator.Hour <= _hourTo)
+ {
+ if (iterator.Hour == _hourTo)
+ if (iterator.Minute > _minutesTo)
+ continue;
+ if (iterator.Hour == _hourFrom)
+ if (iterator.Minute < _minutesFrom)
+ continue;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ if ((iterator.DayOfWeek == DayOfWeek.Monday && !model.Monday) ||
+ (iterator.DayOfWeek == DayOfWeek.Tuesday && !model.Tuesday) ||
+ (iterator.DayOfWeek == DayOfWeek.Wednesday && !model.Wednesday) ||
+ (iterator.DayOfWeek == DayOfWeek.Thursday && !model.Thursday) ||
+ (iterator.DayOfWeek == DayOfWeek.Friday && !model.Friday) ||
+ (iterator.DayOfWeek == DayOfWeek.Saturday && !model.Saturday) ||
+ (iterator.DayOfWeek == DayOfWeek.Sunday && !model.Sunday))
+ continue;
+
+ for (var i = 0; i < model.Quantity.MaxQuantity(); i++)
+ {
+ dates.Add(iterator);
+ try
+ {
+ var insert = true;
+ if ((IntervalUnit)model.IntervalUnit == IntervalUnit.Day)
+ if (reservations.Any(x => x.Resource == model.Resource && x.Date == iterator))
+ insert = false;
+ if (insert)
+ {
+ if (counter++ > 1000)
+ break;
+
+ await productReservationService.InsertProductReservation(new ProductReservation {
+ OrderId = "",
+ Date = iterator,
+ ProductId = productId,
+ Resource = model.Resource,
+ Parameter = model.Parameter,
+ Duration = model.Interval + " " + enumTranslationService.GetTranslationEnum((IntervalUnit)model.IntervalUnit)
+ });
+ }
+ }
+ catch { }
+ }
+ }
+
+ return Json(new { success = true });
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ public async Task<IActionResult> ClearCalendar(string productId)
+ {
+ var product = await productService.GetProductById(productId);
+ if (product == null)
+ throw new ArgumentException("No product found with the specified id");
+
+ // Throw, not Json({errors}): unlike GenerateCalendar, this view's success callback never reads
+ // the response body at all (see CreateOrUpdate.Calendar.cshtml on all three hosts - identical,
+ // no else branch) - a 200 here would silently refresh the grid as if the clear had succeeded. A
+ // thrown exception at least surfaces a generic error via the ajax error callback. The view not
+ // reading a denial message is a pre-existing gap, out of scope for this migration.
+ if (!await scope.HasAccess(product))
+ throw new ArgumentException(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
+
+ var toDelete = await productReservationService.GetProductReservationsByProductId(productId, true, null);
+ foreach (var record in toDelete) await productReservationService.DeleteProductReservation(record);
+
+ return Json("");
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ public async Task<IActionResult> ClearOld(string productId)
+ {
+ var product = await productService.GetProductById(productId);
+ if (product == null)
+ throw new ArgumentException("No product found with the specified id");
+
+ // Throw, not Json({errors}): see the comment on ClearCalendar above - this view's success
+ // callback doesn't read the response body either.
+ if (!await scope.HasAccess(product))
+ throw new ArgumentException(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
+
+ var toDelete =
+ (await productReservationService.GetProductReservationsByProductId(productId, true, null)).Where(x =>
+ x.Date < DateTime.UtcNow);
+ foreach (var record in toDelete) await productReservationService.DeleteProductReservation(record);
+
+ return Json("");
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ [HttpPost]
+ public async Task<IActionResult> ProductReservationDelete(ProductModel.ReservationModel model)
+ {
+ var product = await productService.GetProductById(model.ProductId);
+ if (product == null)
+ throw new ArgumentException("No product found with the specified id");
+
+ if (!await scope.HasAccess(product))
+ return ErrorForKendoGridJson(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
+
+ var toDelete = await productReservationService.GetProductReservation(model.ReservationId);
+
+ // Cross-product IDOR closed here: none of the three original hosts verified that the reservation
+ // being deleted (looked up purely by model.ReservationId) actually belongs to the product just
+ // access-checked (model.ProductId). Both are independent, attacker-supplied POST fields - Store
+ // and Vendor's original code let a caller who owns/has-access-to *any* product pass the access
+ // check with that product's id while supplying a ReservationId belonging to a different, unowned
+ // product, deleting a reservation on a product they have no access to.
+ if (toDelete != null && toDelete.ProductId != product.Id)
+ return ErrorForKendoGridJson(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
+
+ if (toDelete != null)
+ {
+ if (string.IsNullOrEmpty(toDelete.OrderId))
+ await productReservationService.DeleteProductReservation(toDelete);
+ else
+ return Json(new DataSourceResult {
+ Errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.ProductReservations.CantDeleteWithOrder")
+ });
+ }
+
+ return Json("");
+ }
+
+ #endregion
}