From f399d4837641bc1f06281162aa2f2c64828886f1 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 17:28:32 +0100 Subject: [PATCH 1/7] Treat a reservation slot blocked by staff as taken --- .../Products/ProductReservationService.cs | 24 +++-- .../ProductReservationExtensions.cs | 14 ++- .../Utilities/Catalog/ReservationState.cs | 7 +- .../Catalog/ProductReservation.cs | 6 ++ .../ProductReservationExtensionsTests.cs | 13 +++ .../ProductReservationServiceTests.cs | 96 +++++++++++++++++++ 6 files changed, 150 insertions(+), 10 deletions(-) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index bba374ab0..acdbff68b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -96,10 +96,11 @@ public virtual async Task> SearchProductReservati var now = DateTime.UtcNow; //the same states as ProductReservationExtensions.State var query = state switch { - ReservationState.Free => NotHeld(VacantSlots(productId), now), - ReservationState.Held => VacantSlots(productId).Where(x => x.HeldUntilUtc > now), + ReservationState.Free => NotHeld(BookableSlots(productId), now), + ReservationState.Held => BookableSlots(productId).Where(x => x.HeldUntilUtc > now), ReservationState.Booked => _productReservationRepository.Table .Where(x => x.ProductId == productId && x.OrderId != "" && x.OrderId != null), + ReservationState.Blocked => VacantSlots(productId).Where(x => x.BlockedNote != null && x.BlockedNote != ""), _ => _productReservationRepository.Table.Where(x => x.ProductId == productId) }; @@ -155,7 +156,7 @@ await _productReservationRepository.DeleteManyAsync(x => public virtual async Task> GetFirstVacantDates(string productId, DateTime from) { //a slot in a cart, the customer's own included, is not offered again - var query = NotHeld(VacantSlots(productId), DateTime.UtcNow).Where(x => x.Date >= from); + var query = NotHeld(BookableSlots(productId), DateTime.UtcNow).Where(x => x.Date >= from); //one row per parameter, grouped in the database var groups = await _productReservationRepository.ToListAsync(query @@ -200,8 +201,8 @@ public virtual async Task> GetAvailability(Produ //only the item edited, when it is the customer's, keeps what it holds var itemId = customer.ShoppingCartItems.Any(x => x.Id == shoppingCartItemId) ? shoppingCartItemId : null; var query = string.IsNullOrEmpty(itemId) - ? NotHeld(VacantSlots(product.Id), now) - : VacantSlots(product.Id) + ? NotHeld(BookableSlots(product.Id), now) + : BookableSlots(product.Id) .Where(x => x.HeldUntilUtc == null || x.HeldUntilUtc <= now || x.ShoppingCartItemId == itemId); query = query.Where(x => x.Date >= from && x.Date < to); //a range books one resource whatever the parameter of its slots, as the cart does @@ -646,7 +647,7 @@ private async Task> SlotsToBook(Product product, Shopp { var slot = await _productReservationRepository.GetByIdAsync(shoppingCartItem.ReservationId); return slot != null && slot.ProductId == product.Id && string.IsNullOrEmpty(slot.OrderId) && - IsFreeFor(slot, shoppingCartItem.Id, now) + !slot.IsBlocked() && IsFreeFor(slot, shoppingCartItem.Id, now) ? [slot] : []; } @@ -658,10 +659,11 @@ private async Task> SlotsToBook(Product product, Shopp var (from, to) = ProductReservationExtensions.SlotRangeOfRentalPeriod(start, end); var itemId = shoppingCartItem.Id; - var free = await _productReservationRepository.ToListAsync(VacantSlots(product.Id) + var query = BookableSlots(product.Id) .Where(x => x.HeldUntilUtc == null || x.HeldUntilUtc <= now || x.ShoppingCartItemId == itemId) .Where(x => x.Date >= from && x.Date < to) - .OrderBy(x => x.Date)); + .OrderBy(x => x.Date); + var free = await _productReservationRepository.ToListAsync(query); //the resource the item holds first, so a renewed hold and the order keep what the customer was given var held = free.Where(x => x.ShoppingCartItemId == itemId).ToList(); @@ -697,6 +699,12 @@ private IQueryable VacantSlots(string productId) .Where(x => x.ProductId == productId && (x.OrderId == "" || x.OrderId == null)); } + //vacant and not blocked by staff: what a cart may hold and an order book + private IQueryable BookableSlots(string productId) + { + return VacantSlots(productId).Where(x => x.BlockedNote == null || x.BlockedNote == ""); + } + private static string LockKey(string productId) { return $"{nameof(ProductReservation)}:{productId}"; diff --git a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs index 84109cce7..c02bed2d0 100644 --- a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs @@ -203,13 +203,25 @@ public static DateTime FirstEndDate(this Product product, DateTime startDate) } /// - /// Gets the state of a slot at a moment: booked by an order, held by a cart until its hold ends, or free + /// Gets whether staff took a slot out of sale + /// + public static bool IsBlocked(this ProductReservation slot) + { + return !string.IsNullOrEmpty(slot.BlockedNote); + } + + /// + /// Gets the state of a slot at a moment: booked by an order, blocked by staff, held by a cart until its hold + /// ends, or free /// public static ReservationState State(this ProductReservation slot, DateTime utcNow) { if (!string.IsNullOrEmpty(slot.OrderId)) return ReservationState.Booked; + if (slot.IsBlocked()) + return ReservationState.Blocked; + //a stored date is read back in UTC (MongoDB) or local time (LiteDB) return slot.HeldUntilUtc.HasValue && slot.HeldUntilUtc.Value.ToUniversalTime() > utcNow ? ReservationState.Held diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationState.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationState.cs index 69c1f3281..21a96c066 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationState.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationState.cs @@ -18,5 +18,10 @@ public enum ReservationState /// /// An order booked it /// - Booked = 2 + Booked = 2, + + /// + /// Staff took it out of sale with a note + /// + Blocked = 3 } diff --git a/src/Core/Grand.Domain/Catalog/ProductReservation.cs b/src/Core/Grand.Domain/Catalog/ProductReservation.cs index f9c269ee6..a108cf08a 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReservation.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReservation.cs @@ -53,6 +53,12 @@ public class ProductReservation : BaseEntity /// public DateTime? ReminderSentOnUtc { get; set; } + /// + /// Gets or sets why staff took the slot out of sale; a slot with a note is blocked: no cart can hold it and no + /// order can book it + /// + public string? BlockedNote { get; set; } + /// /// Gets or sets resource name /// diff --git a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs index b130bd7cc..3cd64b515 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs @@ -21,6 +21,19 @@ private static ProductReservation Slot(int month, int day, string resource) => private static DateTime StoreDay(int month, int day) => new DateTime(2030, month, day).StoreTimeToUtc(Warsaw); + [TestMethod] + public void State_BlockedSlot_IsBlockedUnlessBooked() + { + var now = DateTime.UtcNow; + + Assert.AreEqual(ReservationState.Blocked, new ProductReservation { BlockedNote = "Repair" }.State(now)); + Assert.AreEqual(ReservationState.Blocked, + new ProductReservation { BlockedNote = "Repair", HeldUntilUtc = now.AddMinutes(5) }.State(now)); + Assert.AreEqual(ReservationState.Booked, + new ProductReservation { BlockedNote = "Repair", OrderId = "o1" }.State(now)); + Assert.AreEqual(ReservationState.Free, new ProductReservation { BlockedNote = "" }.State(now)); + } + [TestMethod] public void FindGroupToBook_WarsawMidnightSlots_MatchTheStoreDays() { diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs index 262407494..7118c0cd8 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs @@ -1454,6 +1454,102 @@ public async Task GetTimeZone_ProductOfEveryStore_UsesTheZoneOfAllStores() Assert.AreEqual(Warsaw.BaseUtcOffset, (await _service.GetTimeZone(new Product())).BaseUtcOffset); } + // --- Blocked by staff ------------------------------------------------------------------------------ + + private async Task InsertBlockedSlot(DateTime date, string? resource = null, + string? parameter = null, string id = "blocked") + { + var slot = new ProductReservation { + Id = id, ProductId = "p1", Date = date, Resource = resource, Parameter = parameter, OrderId = "", + BlockedNote = "Repair" + }; + await _repository.InsertAsync(slot); + return slot; + } + + [TestMethod] + public async Task GetAvailability_HourProduct_SkipsBlockedSlots() + { + var day = Day(10); + await _repository.InsertAsync(new ProductReservation + { Id = "free", ProductId = "p1", Date = day.AddHours(10), OrderId = "" }); + await InsertBlockedSlot(day.AddHours(11)); + + var dates = await _service.GetAvailability(HourProduct, new Customer { Id = "c1" }, day, day, null, null); + + CollectionAssert.AreEqual(new[] { "free" }, dates.SelectMany(x => x.Slots).Select(x => x.Id).ToArray()); + } + + [TestMethod] + public async Task GetAvailability_DayProduct_BlockedDayBreaksTheRun() + { + await InsertSlot(Day(10), "A"); + await InsertBlockedSlot(Day(11), "A"); + await InsertSlot(Day(12), "A"); + + var dates = await _service.GetAvailability(DayProduct, new Customer { Id = "c1" }, Day(10), Day(12), null, + null); + + CollectionAssert.AreEqual(new[] { "01-10>01-11", "01-12>01-13" }, LastEndDates(dates)); + } + + [TestMethod] + public async Task GetFirstVacantDates_SkipsBlockedSlots() + { + await InsertBlockedSlot(Day(10)); + await InsertSlot(Day(11)); + + var result = await _service.GetFirstVacantDates("p1", Day(1)); + + CollectionAssert.AreEqual(new[] { new FirstVacantDate("", Day(11)) }, result.ToArray()); + } + + [TestMethod] + public async Task TryHold_BlockedHourSlot_Refuses() + { + var slot = await InsertBlockedSlot(Day(10).AddHours(9)); + + Assert.IsFalse(await _service.TryHold(HourProduct, + new ShoppingCartItem { Id = "sci1", ProductId = "p1", ReservationId = slot.Id }, "c1")); + Assert.IsNull((await _repository.GetByIdAsync(slot.Id))!.ShoppingCartItemId); + } + + [TestMethod] + public async Task TryBook_BlockedHourSlot_ReturnsNull() + { + var slot = await InsertBlockedSlot(Day(10).AddHours(9)); + + Assert.IsNull(await _service.TryBook(HourProduct, new ShoppingCartItem { ReservationId = slot.Id }, "o1", + "oi1")); + Assert.AreEqual("", (await _repository.GetByIdAsync(slot.Id))!.OrderId); + } + + [TestMethod] + public async Task TryBook_DayRangeWithABlockedDay_BooksAnotherResource() + { + await InsertSlot(Day(10), "A"); + await InsertBlockedSlot(Day(11), "A"); + var b10 = await InsertSlot(Day(10), "B"); + var b11 = await InsertSlot(Day(11), "B"); + + var booked = await _service.TryBook(DayProduct, DayRange(10, 12), "o1", "oi1"); + + Assert.IsNotNull(booked); + CollectionAssert.AreEquivalent(new[] { b10.Id, b11.Id }, booked.Select(x => x.Id).ToList()); + } + + [TestMethod] + public async Task SearchProductReservations_ByState_Blocked() + { + await InsertSlotsInEveryState(); + await _repository.InsertAsync(new ProductReservation + { Id = "blocked", ProductId = "1", Date = Day(14), BlockedNote = "Repair" }); + + CollectionAssert.AreEqual(new[] { "free", "expired" }, await SearchIds(ReservationState.Free)); + CollectionAssert.AreEqual(new[] { "blocked" }, await SearchIds(ReservationState.Blocked)); + CollectionAssert.AreEqual(new[] { "booked" }, await SearchIds(ReservationState.Booked)); + } + [TestMethod] [DataRow("")] [DataRow("Gone/Zone")] From 942b7644f2775a71d5104c82541bae393276cdeb Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 17:30:46 +0100 Subject: [PATCH 2/7] Let staff block and unblock reservation slots --- .../Products/ProductReservationService.cs | 56 ++++++++++ .../Products/IProductReservationService.cs | 19 ++++ .../ProductReservationServiceTests.cs | 105 ++++++++++++++++++ 3 files changed, 180 insertions(+) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index acdbff68b..8d4b0c658 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -146,6 +146,62 @@ await _productReservationRepository.DeleteManyAsync(x => return vacant.Count; } + public virtual async Task BlockReservations(string productId, IList ids, string note) + { + ArgumentException.ThrowIfNullOrWhiteSpace(note); + if (ids.Count == 0) + return 0; + + List blocked; + //under the product lock: a checkout books a slot or the block takes it, never both + await using (await _resourceLock.Acquire([LockKey(productId)])) + { + var query = VacantSlots(productId).Where(x => ids.Contains(x.Id)); + blocked = (await _productReservationRepository.ToListAsync(query)).ToList(); + if (blocked.Count == 0) + return 0; + + var blockedIds = blocked.Select(x => x.Id).ToList(); + //a cart holding one of them finds it taken on its next check + await _productReservationRepository.UpdateManyAsync(x => blockedIds.Contains(x.Id), + ClearHold().Set(x => x.BlockedNote, note)); + } + + foreach (var slot in blocked) + { + slot.BlockedNote = note; + await PublishHold(slot, null, null, null); + } + + return blocked.Count; + } + + public virtual async Task UnblockReservations(string productId, IList ids) + { + if (ids.Count == 0) + return 0; + + var query = _productReservationRepository.Table.Where(x => + x.ProductId == productId && ids.Contains(x.Id) && x.BlockedNote != null && x.BlockedNote != ""); + var unblocked = await _productReservationRepository.ToListAsync(query); + if (unblocked.Count == 0) + return 0; + + var unblockedIds = unblocked.Select(x => x.Id).ToList(); + await _productReservationRepository.UpdateManyAsync(x => unblockedIds.Contains(x.Id), + UpdateBuilder.Create().Set(x => x.BlockedNote, null)); + + foreach (var slot in unblocked) + { + slot.BlockedNote = null; + + //event + await _mediator.EntityUpdated(slot); + } + + return unblocked.Count; + } + /// /// Gets, for each parameter of the vacant slots of a product at or after a date that no cart holds now, the /// date of its first slot diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs index 165377716..2247b28f7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs @@ -145,6 +145,25 @@ Task> SearchProductReservations(string productId, /// Number of the slots deleted Task DeleteVacantReservations(string productId, IList ids); + /// + /// Takes out of sale the slots of a product among the given ones that no order booked: no cart can hold them + /// and no order can book them until they are unblocked. A cart's hold on them ends; a blocked slot gets the + /// new note. A slot booked meanwhile, or one of another product, stays as it is. + /// + /// Product Id + /// Identifiers of the slots to block + /// Why the slots are blocked + /// Number of the slots blocked + Task BlockReservations(string productId, IList ids, string note); + + /// + /// Puts back on sale the blocked slots of a product among the given ones + /// + /// Product Id + /// Identifiers of the slots to unblock + /// Number of the slots unblocked + Task UnblockReservations(string productId, IList ids); + /// /// Gets, for each parameter of the vacant slots of a product at or after a date that no cart holds now, the /// date of its first slot diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs index 7118c0cd8..ab09b5c07 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs @@ -1550,6 +1550,111 @@ await _repository.InsertAsync(new ProductReservation CollectionAssert.AreEqual(new[] { "booked" }, await SearchIds(ReservationState.Booked)); } + [TestMethod] + public async Task BlockReservations_FreeAndHeld_BlocksAndEndsTheHold() + { + var free = await InsertSlot(Day(10)); + var held = await InsertSlot(Day(11)); + await Hold(new ShoppingCartItem { Id = "sci1" }, held); + + var blocked = await _service.BlockReservations("p1", [free.Id, held.Id], "Repair"); + + Assert.AreEqual(2, blocked); + foreach (var slot in _repository.Table.ToList()) + { + Assert.AreEqual("Repair", slot.BlockedNote); + Assert.IsNull(slot.ShoppingCartItemId); + Assert.IsNull(slot.HeldByCustomerId); + Assert.IsNull(slot.HeldUntilUtc); + } + } + + [TestMethod] + public async Task BlockReservations_BookedMeanwhile_StaysBooked() + { + var booked = await InsertSlot(Day(10), orderId: "o1"); + + Assert.AreEqual(0, await _service.BlockReservations("p1", [booked.Id], "Repair")); + var stored = (await _repository.GetByIdAsync(booked.Id))!; + Assert.IsNull(stored.BlockedNote); + Assert.AreEqual("o1", stored.OrderId); + } + + [TestMethod] + public async Task BlockReservations_SlotOfAnotherProduct_Untouched() + { + var foreign = await InsertSlot(Day(10), productId: "p2"); + + Assert.AreEqual(0, await _service.BlockReservations("p1", [foreign.Id], "Repair")); + Assert.IsNull((await _repository.GetByIdAsync(foreign.Id))!.BlockedNote); + } + + [TestMethod] + public async Task BlockReservations_AlreadyBlocked_ReplacesTheNote() + { + var slot = await InsertBlockedSlot(Day(10)); + + Assert.AreEqual(1, await _service.BlockReservations("p1", [slot.Id], "Phone booking")); + Assert.AreEqual("Phone booking", (await _repository.GetByIdAsync(slot.Id))!.BlockedNote); + } + + [TestMethod] + public async Task BlockReservations_PublishesAnEventPerSlot() + { + var a = await InsertSlot(Day(10)); + var b = await InsertSlot(Day(11)); + + await _service.BlockReservations("p1", [a.Id, b.Id], "Repair"); + + _mediatorMock.Verify(x => x.Publish(It.Is>(e => + e.Entity.BlockedNote == "Repair"), It.IsAny()), Times.Exactly(2)); + } + + [TestMethod] + public async Task UnblockReservations_ClearsTheNoteOfTheProductsSlotsOnly() + { + var blocked = await InsertBlockedSlot(Day(10)); + var free = await InsertSlot(Day(11)); + var foreign = new ProductReservation + { Id = "foreign", ProductId = "p2", Date = Day(10), OrderId = "", BlockedNote = "Repair" }; + await _repository.InsertAsync(foreign); + + var unblocked = await _service.UnblockReservations("p1", [blocked.Id, free.Id, foreign.Id]); + + Assert.AreEqual(1, unblocked); + Assert.IsNull((await _repository.GetByIdAsync(blocked.Id))!.BlockedNote); + Assert.AreEqual("Repair", (await _repository.GetByIdAsync(foreign.Id))!.BlockedNote); + _mediatorMock.Verify(x => x.Publish(It.Is>(e => + e.Entity.Id == blocked.Id && e.Entity.BlockedNote == null), It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task BlockAndUnblock_LiteDb() + { + _repository = new LiteDBRepositoryMock(); + _service = new ProductReservationService(_repository, _mediatorMock.Object, new MongoResourceLockTest(), + _shoppingCartSettings, _dateTimeServiceMock.Object, _settingServiceMock.Object); + //LiteDB stores the empty OrderId as null + await _repository.InsertAsync(new ProductReservation { Id = "free", ProductId = "p1", Date = Day(10), OrderId = "" }); + await _repository.InsertAsync(new ProductReservation { Id = "booked", ProductId = "p1", Date = Day(11), OrderId = "o1" }); + + Assert.AreEqual(1, await _service.BlockReservations("p1", ["free", "booked"], "Repair")); + Assert.AreEqual("Repair", (await _repository.GetByIdAsync("free"))!.BlockedNote); + Assert.IsNull((await _repository.GetByIdAsync("booked"))!.BlockedNote); + + Assert.AreEqual(1, await _service.UnblockReservations("p1", ["free", "booked"])); + Assert.IsNull((await _repository.GetByIdAsync("free"))!.BlockedNote); + } + + [TestMethod] + public async Task DeleteVacantReservations_DeletesBlockedSlots() + { + var slot = await InsertBlockedSlot(Day(10)); + + Assert.AreEqual(1, await _service.DeleteVacantReservations("p1", [slot.Id])); + Assert.AreEqual(0, _repository.Table.Count()); + } + [TestMethod] [DataRow("")] [DataRow("Gone/Zone")] From d9f0b0447c3562668d23970f773a233b4c5006f9 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 17:36:27 +0100 Subject: [PATCH 3/7] Block selected reservation slots from the calendar grid --- .../ProductReservationExtensions.cs | 5 + .../BaseProductReservationControllerTests.cs | 171 ++++++++++++++++++ .../BaseProductReservationController.cs | 79 +++++++- .../Models/Catalog/ProductModel.cs | 1 + 4 files changed, 253 insertions(+), 3 deletions(-) diff --git a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs index c02bed2d0..e6af6e828 100644 --- a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs @@ -21,6 +21,11 @@ public static class ProductReservationExtensions /// public const int MaxReservationHorizonDays = 3650; + /// + /// The most characters of the note staff block a slot with + /// + public const int MaxBlockedNoteLength = 400; + /// /// Gets the resource of the warning for a cart item whose slots are no longer free: an hour or minute item books /// its slot, a day item a free resource for its period diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs index 619da9694..d5436a0e6 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs @@ -525,11 +525,182 @@ public async Task DeleteSelectedReservations_AllDeleted_ReportsNoError() Assert.IsNull(JsonProperty(result, "errors")); } + // --- Block / UnblockSelectedReservations ------------------------------------------------------------ + + private void BlockingReturns(int blocked) => + _productReservationServiceMock + .Setup(s => s.BlockReservations("p1", It.IsAny>(), It.IsAny())) + .ReturnsAsync(blocked); + + [TestMethod] + public async Task BlockSelectedReservations_MissingProduct_Throws() + { + _productServiceMock.Setup(p => p.GetProductById("missing")).ReturnsAsync((Product?)null); + + await Assert.ThrowsExactlyAsync( + () => _controller.BlockSelectedReservations("missing", ["r1"], "Repair")); + } + + [TestMethod] + public async Task BlockSelectedReservations_ScopeDeniesAccess_ReturnsErrorsJson_DoesNotBlock() + { + var product = new Product { Id = "p1" }; + _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product); + _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Permissions")).Returns("denied"); + + var result = await _controller.BlockSelectedReservations("p1", ["r1"], "Repair"); + + Assert.AreEqual("denied", JsonProperty(result, "errors")); + _productReservationServiceMock.Verify(s => s.BlockReservations(It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Never); + } + + [TestMethod] + [DataRow(null)] + [DataRow(" ")] + public async Task BlockSelectedReservations_BlankNote_RefusedDoesNotBlock(string? note) + { + AccessibleProduct(); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.BlockedNote.Required")) + .Returns("note required"); + + var result = await _controller.BlockSelectedReservations("p1", ["r1"], note); + + Assert.AreEqual("note required", JsonProperty(result, "errors")); + _productReservationServiceMock.Verify(s => s.BlockReservations(It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task BlockSelectedReservations_NoteTooLong_RefusedDoesNotBlock() + { + AccessibleProduct(); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.BlockedNote.TooLong")) + .Returns("at most {0}"); + + var result = await _controller.BlockSelectedReservations("p1", ["r1"], new string('x', 401)); + + Assert.AreEqual("at most 400", JsonProperty(result, "errors")); + _productReservationServiceMock.Verify(s => s.BlockReservations(It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task BlockSelectedReservations_BlocksForTheCheckedProductOnly_TrimmedNote_EachIdOnce() + { + AccessibleProduct(); + BlockingReturns(2); + + await _controller.BlockSelectedReservations("p1", ["r1", "r2", "r1"], " Repair "); + + _productReservationServiceMock.Verify(s => s.BlockReservations("p1", + It.Is>(ids => ids.SequenceEqual(new[] { "r1", "r2" })), "Repair"), Times.Once); + } + + [TestMethod] + public async Task BlockSelectedReservations_SomeNotBlocked_SaysTheBookedStay() + { + AccessibleProduct(); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Blocked")).Returns("{0} blocked"); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.CantBlockBooked")) + .Returns("booked"); + BlockingReturns(1); + + var result = await _controller.BlockSelectedReservations("p1", ["free", "booked"], "Repair"); + + Assert.AreEqual(true, JsonProperty(result, "success")); + Assert.AreEqual("1 blocked", JsonProperty(result, "message")); + Assert.AreEqual("booked", JsonProperty(result, "errors")); + } + + [TestMethod] + public async Task UnblockSelectedReservations_ScopeDeniesAccess_ReturnsErrorsJson_DoesNotUnblock() + { + var product = new Product { Id = "p1" }; + _productServiceMock.Setup(p => p.GetProductById("p1")).ReturnsAsync(product); + _scopeMock.Setup(s => s.HasAccess(product)).ReturnsAsync(false); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Permissions")).Returns("denied"); + + var result = await _controller.UnblockSelectedReservations("p1", ["r1"]); + + Assert.AreEqual("denied", JsonProperty(result, "errors")); + _productReservationServiceMock.Verify( + s => s.UnblockReservations(It.IsAny(), It.IsAny>()), Times.Never); + } + + [TestMethod] + public async Task UnblockSelectedReservations_UnblocksForTheCheckedProductOnly() + { + AccessibleProduct(); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Unblocked")).Returns("{0} unblocked"); + _productReservationServiceMock.Setup(s => s.UnblockReservations("p1", It.IsAny>())).ReturnsAsync(1); + + var result = await _controller.UnblockSelectedReservations("p1", ["r1", "r1"]); + + Assert.AreEqual(true, JsonProperty(result, "success")); + Assert.AreEqual("1 unblocked", JsonProperty(result, "message")); + _productReservationServiceMock.Verify(s => s.UnblockReservations("p1", + It.Is>(ids => ids.SequenceEqual(new[] { "r1" }))), Times.Once); + } + + [TestMethod] + public async Task ClearCalendar_KeepsBlockedSlots_SaysHowMany() + { + AccessibleProduct(); + var free = NewReservation("free", "p1"); + var blocked = NewReservation("blocked", "p1"); + blocked.BlockedNote = "Repair"; + _productReservationServiceMock + .Setup(s => s.GetProductReservationsByProductId("p1", true, null, null, 0, int.MaxValue, null)) + .ReturnsAsync(new PagedList(new List { free, blocked }, 0, int.MaxValue)); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Deleted")).Returns("{0} deleted"); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.BlockedKept")).Returns("{0} kept"); + + var result = await _controller.ClearCalendar("p1"); + + Assert.AreEqual("1 deleted\n1 kept", JsonProperty(result, "message")); + _productReservationServiceMock.Verify(s => s.DeleteProductReservation(free), Times.Once); + _productReservationServiceMock.Verify(s => s.DeleteProductReservation(blocked), Times.Never); + } + + [TestMethod] + public async Task ClearOld_DeletesPastBlockedSlots() + { + AccessibleProduct(); + var blocked = NewReservation("blocked", "p1"); + blocked.BlockedNote = "Repair"; + _productReservationServiceMock + .Setup(s => s.GetProductReservationsByProductId("p1", true, null, It.IsAny(), 0, int.MaxValue, + null)) + .ReturnsAsync(new PagedList(new List { blocked }, 0, int.MaxValue)); + + await _controller.ClearOld("p1"); + + _productReservationServiceMock.Verify(s => s.DeleteProductReservation(blocked), Times.Once); + } + + [TestMethod] + public async Task ListReservations_ShowsBlockedStateAndNote() + { + ViewableProduct(); + var blocked = NewReservation("blocked", "p1"); + blocked.BlockedNote = "Repair"; + SearchReturns(blocked); + + var row = (await ListRows()).Single(); + + Assert.AreEqual((int)ReservationState.Blocked, row.State); + Assert.AreEqual("Repair", row.BlockedNote); + } + // the clearing actions delete slots: POST only, so the antiforgery token is checked [TestMethod] [DataRow(nameof(BaseProductReservationController.ClearCalendar))] [DataRow(nameof(BaseProductReservationController.ClearOld))] [DataRow(nameof(BaseProductReservationController.DeleteSelectedReservations))] + [DataRow(nameof(BaseProductReservationController.BlockSelectedReservations))] + [DataRow(nameof(BaseProductReservationController.UnblockSelectedReservations))] public void DeletingActions_ArePostOnly(string action) { var method = typeof(BaseProductReservationController).GetMethod(action)!; diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs index 7024b9727..ec771ea35 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs @@ -77,7 +77,8 @@ public async Task ListReservations(DataSourceRequest command, str Resource = x.Resource, Duration = x.Duration, State = (int)state, - HeldUntil = state == ReservationState.Held ? x.HeldUntilUtc!.Value.ToStoreTime(storeTimeZone) : null + HeldUntil = state == ReservationState.Held ? x.HeldUntilUtc!.Value.ToStoreTime(storeTimeZone) : null, + BlockedNote = x.BlockedNote }; }).ToList(); @@ -171,10 +172,19 @@ public async Task ClearCalendar(string productId) if (!await scope.HasAccess(product)) return Json(new { errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions") }); - var toDelete = await productReservationService.GetProductReservationsByProductId(productId, true, null, null); + var vacant = await productReservationService.GetProductReservationsByProductId(productId, true, null, null); + //a slot staff blocked stays until they unblock it: clearing the calendar would lose their note unnoticed + var toDelete = vacant.Where(x => !x.IsBlocked()).ToList(); foreach (var record in toDelete) await productReservationService.DeleteProductReservation(record); - return Json(new { success = true, message = DeletedMessage(toDelete.Count) }); + var kept = vacant.Count - toDelete.Count; + var message = DeletedMessage(toDelete.Count); + if (kept > 0) + message += "\n" + string.Format( + translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.BlockedKept"), + kept); + + return Json(new { success = true, message }); } [PermissionAuthorizeAction(PermissionActionName.Edit)] @@ -220,6 +230,69 @@ public async Task DeleteSelectedReservations(string productId, IC }); } + [PermissionAuthorizeAction(PermissionActionName.Edit)] + [HttpPost] + public async Task BlockSelectedReservations(string productId, ICollection? selectedIds, + string? note) + { + var product = await productService.GetProductById(productId); + if (product == null) + throw new ArgumentException("No product found with the specified id"); + + if (!await scope.HasAccess(product)) + return Json(new { errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions") }); + + note = note?.Trim(); + if (string.IsNullOrEmpty(note)) + return Json(new { + errors = translationService.GetResource( + $"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.BlockedNote.Required") + }); + if (note.Length > ProductReservationExtensions.MaxBlockedNoteLength) + return Json(new { + errors = string.Format( + translationService.GetResource( + $"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.BlockedNote.TooLong"), + ProductReservationExtensions.MaxBlockedNoteLength) + }); + + //as DeleteSelectedReservations: only this product's slots; a booked one belongs to its order and stays + var ids = selectedIds?.Distinct().ToList() ?? []; + var blocked = await productReservationService.BlockReservations(product.Id, ids, note); + + return Json(new { + success = true, + message = string.Format( + translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.Blocked"), + blocked), + errors = blocked < ids.Count + ? translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.CantBlockBooked") + : null + }); + } + + [PermissionAuthorizeAction(PermissionActionName.Edit)] + [HttpPost] + public async Task UnblockSelectedReservations(string productId, ICollection? selectedIds) + { + var product = await productService.GetProductById(productId); + if (product == null) + throw new ArgumentException("No product found with the specified id"); + + if (!await scope.HasAccess(product)) + return Json(new { errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions") }); + + var ids = selectedIds?.Distinct().ToList() ?? []; + var unblocked = await productReservationService.UnblockReservations(product.Id, ids); + + return Json(new { + success = true, + message = string.Format( + translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.Unblocked"), + unblocked) + }); + } + private string DeletedMessage(int count) { return string.Format( diff --git a/src/Web/Grand.Web.AdminShared/Models/Catalog/ProductModel.cs b/src/Web/Grand.Web.AdminShared/Models/Catalog/ProductModel.cs index 7cdecc8b6..7a02e625a 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Catalog/ProductModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Catalog/ProductModel.cs @@ -809,6 +809,7 @@ public class ReservationModel : BaseEntityModel public int? OrderNumber { get; set; } public int State { get; set; } public DateTime? HeldUntil { get; set; } + public string? BlockedNote { get; set; } } public class ReservationListModel : BaseModel From 65de3fe1aa8093c58be74afb35188a790d40d95c Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 17:47:54 +0100 Subject: [PATCH 4/7] Show and block reservation slots in the calendar grid --- .../Partials/CreateOrUpdate.Calendar.cshtml | 43 ++++++++++++- .../App_Data/Resources/DefaultLanguage.xml | Bin 1858676 -> 1864292 bytes .../App_Data/Resources/Upgrade/en_250.xml | 60 ++++++++++++++++++ 3 files changed, 102 insertions(+), 1 deletion(-) diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/Product/Partials/CreateOrUpdate.Calendar.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Product/Partials/CreateOrUpdate.Calendar.cshtml index 1c70b9bdf..d31f000d8 100644 --- a/src/Web/Grand.Web.AdminShared/Views/AdminShared/Product/Partials/CreateOrUpdate.Calendar.cshtml +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Product/Partials/CreateOrUpdate.Calendar.cshtml @@ -1,3 +1,4 @@ +@using Grand.Business.Core.Extensions @using Grand.Business.Core.Utilities.Catalog @using Grand.Web.Common.TagHelpers.Admin.Grid @model ProductModel @@ -13,7 +14,8 @@ new(Loc[$"{Scope.ResourceKeyPrefix}.Common.All"], ""), new(Loc[$"{Scope.ResourceKeyPrefix}.Catalog.Products.Calendar.State.Free"], ((int)ReservationState.Free).ToString()), new(Loc[$"{Scope.ResourceKeyPrefix}.Catalog.Products.Calendar.State.Held"], ((int)ReservationState.Held).ToString()), - new(Loc[$"{Scope.ResourceKeyPrefix}.Catalog.Products.Calendar.State.Booked"], ((int)ReservationState.Booked).ToString()) + new(Loc[$"{Scope.ResourceKeyPrefix}.Catalog.Products.Calendar.State.Booked"], ((int)ReservationState.Booked).ToString()), + new(Loc[$"{Scope.ResourceKeyPrefix}.Catalog.Products.Calendar.State.Blocked"], ((int)ReservationState.Blocked).ToString()) }; } @if (!string.IsNullOrEmpty(Model.Id)) @@ -97,7 +99,18 @@ @* what the last action did: the slots added or deleted, or why it did not *@ + @* a blocked slot is out of sale for everyone until it is unblocked; the note says why *@ + + + @@ -115,6 +128,7 @@ + @@ -125,6 +139,8 @@ {{ $texts.booked }} {{ $texts.held }} {{ $texts.free }} + {{ $texts.blocked }} +
{{ BlockedNote }}
@@ -264,6 +280,31 @@ }); }); + $("#blockSelectedReservations").click(function () { + post("@(Url.Action("BlockSelectedReservations", "ProductReservation", new { area = area }))", { + productId: '@(Model.Id)', + selectedIds: reservationsSelectedIds, + note: $("#reservationBlockNote").val() + }).done(function (data) { + if (data.success) $("#reservationBlockNote").val(""); + }); + }); + + @* Enter in the note blocks instead of posting the product form *@ + $("#reservationBlockNote").keydown(function (event) { + if (event.keyCode == 13) { + $("#blockSelectedReservations").click(); + return false; + } + }); + + $("#unblockSelectedReservations").click(function () { + post("@(Url.Action("UnblockSelectedReservations", "ProductReservation", new { area = area }))", { + productId: '@(Model.Id)', + selectedIds: reservationsSelectedIds + }); + }); + $("#deleteSelectedReservations").click(function () { confirmThen('@Loc[$"{Scope.ResourceKeyPrefix}.Common.Delete"]', function () { post("@(Url.Action("DeleteSelectedReservations", "ProductReservation", new { area = area }))", { diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 7542b26c0d4e0c045ece3f769f621c5e4e88a18e..d4507352d382d8a86cf27a89f04e93d771b20dbf 100644 GIT binary patch delta 1404 zcmb`H&ubGw6vro>WNXuG(ll)*+oqU{CG-%g7K8?B)A|ENN+Wm?#cXS^Rnw$xv{)^T zP>86-iqhw)BnN*SJa`b}Ndg|ki&gQMi_oi>L;nE3I}taDsRxzi%goMu^WMyNKkWAF z*{!YF%!*~D=_OZ&EE5#T+avU5lsj4`*kzVvlk5_GUlx;;`^H1mc96Hbeg#;Zok!UH zUJcWDsaY9CvRn(WdAT`_F(B7cEX@Wnzs~yE5({B=ip?;yQULKO>`hR9vt7{kx^j`q zLwuiVrl1)`!W|l|4Y%BtK~GH(^^z=2de(A`ihhgZfQ~M54Rr%-0rjt8tn{fpq0Z)H zj;u$^&$_3n{|Fxt4eBE=^gvDTri^Y22{e=&6HJ%Ir!Zb+af&K_5B2-IQl@QHe(J~7 z!_qKrxO=~q-=o+e?j^^f7^HHC8l=>sSd?1}aQvagrQ;%L(=OT^;}HtD6)P-A;;FHn zZhE|0XYJVy@2BBT_?@cRFk$obb zPMg=DwQ=q!d>rG?n`~E%PiPXO%J&_psS8#t5Q??R7So8>N$#Z5s%WF!hPyXgjB>~d z*&qdKhIT1khf5biW9*K>pkmVM39Q3++KAM@cy_F z<$^NX8nVf0{jaE>pU#6UyJ_v)5CRPOQxseFq&_x~m4XJz9*WB$n( z(#-NZfj&p6B{5v(Vg9Xlw1)Ax>{S5cPnsI>+(Us2qVFGgj?R1aN)PZn0B=8?H_VZ0;59@{Gv3|K<$`mCYL^O&8Kh3hbgLJT;> zApuEHAq5(wL5B=vAqROVKoLq%maZcLn-FVn9MP0~CAz;Vp<1I`AX@UX7Mf1zTjZ&h zO|LO?$X$vq-9n+!cESt_>!wW)BhELY;_yGd2!E?oI~q25UV$&vg8&0eu%vpZOz&U6 Cc34XQ diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml index a44ad216b..4aa779aaa 100644 --- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml +++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml @@ -2919,6 +2919,36 @@ In a cart + + Block selected + + + Slots blocked: {0}. + + + Blocked slots kept: {0}. Unblock them to delete them. + + + Note + + + Enter a note why the slots are blocked. + + + The note may have at most {0} characters. + + + A booked slot cannot be blocked: it belongs to its order. + + + Blocked + + + Slots unblocked: {0}. + + + Unblock selected + Slots deleted: {0}. @@ -2937,6 +2967,36 @@ In a cart + + Block selected + + + Slots blocked: {0}. + + + Blocked slots kept: {0}. Unblock them to delete them. + + + Note + + + Enter a note why the slots are blocked. + + + The note may have at most {0} characters. + + + A booked slot cannot be blocked: it belongs to its order. + + + Blocked + + + Slots unblocked: {0}. + + + Unblock selected + Held for you until {0} From 3ee11f89f1ab79b0d55376d1306809be333216b1 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 20:22:15 +0100 Subject: [PATCH 5/7] End the whole cart hold when staff block one of its slots Blocking one day of a held day range now releases the other days of that cart item too, so they are not kept from other customers until the hold runs out and the cart no longer shows a hold label for an item it cannot book. The service trims the note and enforces its maximum length for every caller. A selection that is only partly blocked says how many slots were left out instead of blaming a booking. --- .../Products/ProductReservationService.cs | 21 +++++++- .../Products/IProductReservationService.cs | 10 ++-- .../ProductReservationServiceTests.cs | 46 ++++++++++++++++++ .../BaseProductReservationControllerTests.cs | 10 ++-- .../BaseProductReservationController.cs | 5 +- .../App_Data/Resources/DefaultLanguage.xml | Bin 1864292 -> 1864376 bytes .../App_Data/Resources/Upgrade/en_250.xml | 8 +-- 7 files changed, 86 insertions(+), 14 deletions(-) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index 8d4b0c658..022660b49 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -149,10 +149,14 @@ await _productReservationRepository.DeleteManyAsync(x => public virtual async Task BlockReservations(string productId, IList ids, string note) { ArgumentException.ThrowIfNullOrWhiteSpace(note); + note = note.Trim(); + ArgumentOutOfRangeException.ThrowIfGreaterThan(note.Length, ProductReservationExtensions.MaxBlockedNoteLength, + nameof(note)); if (ids.Count == 0) return 0; List blocked; + List released; //under the product lock: a checkout books a slot or the block takes it, never both await using (await _resourceLock.Acquire([LockKey(productId)])) { @@ -162,11 +166,26 @@ public virtual async Task BlockReservations(string productId, IList return 0; var blockedIds = blocked.Select(x => x.Id).ToList(); - //a cart holding one of them finds it taken on its next check + //a cart item holding one of them can no longer book its choice, and its next check finds no slots to + //hold, so the rest of its hold ends here: the other days of a range would stay out of sale until then + var holders = blocked.Select(x => x.ShoppingCartItemId).Where(x => !string.IsNullOrEmpty(x)).Distinct() + .ToList(); + released = holders.Count > 0 + ? (await _productReservationRepository.ToListAsync(VacantSlots(productId) + .Where(x => holders.Contains(x.ShoppingCartItemId) && !blockedIds.Contains(x.Id)))).ToList() + : []; + if (released.Count > 0) + { + var releasedIds = released.Select(x => x.Id).ToList(); + await _productReservationRepository.UpdateManyAsync(x => releasedIds.Contains(x.Id), ClearHold()); + } + await _productReservationRepository.UpdateManyAsync(x => blockedIds.Contains(x.Id), ClearHold().Set(x => x.BlockedNote, note)); } + foreach (var slot in released) + await PublishHold(slot, null, null, null); foreach (var slot in blocked) { slot.BlockedNote = note; diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs index 2247b28f7..8dc48ccfa 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs @@ -147,12 +147,16 @@ Task> SearchProductReservations(string productId, /// /// Takes out of sale the slots of a product among the given ones that no order booked: no cart can hold them - /// and no order can book them until they are unblocked. A cart's hold on them ends; a blocked slot gets the - /// new note. A slot booked meanwhile, or one of another product, stays as it is. + /// and no order can book them until they are unblocked. The hold of a cart item on any of them ends, on its + /// other slots too; a blocked slot gets the new note. A slot booked meanwhile, or one of another product, + /// stays as it is. /// /// Product Id /// Identifiers of the slots to block - /// Why the slots are blocked + /// + /// Why the slots are blocked, stored trimmed; at most + /// characters + /// /// Number of the slots blocked Task BlockReservations(string productId, IList ids, string note); diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs index ab09b5c07..11a898e24 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs @@ -1610,6 +1610,52 @@ public async Task BlockReservations_PublishesAnEventPerSlot() e.Entity.BlockedNote == "Repair"), It.IsAny()), Times.Exactly(2)); } + [TestMethod] + public async Task BlockReservations_OneDayOfAHeldRange_EndsTheHoldOnTheOtherDays() + { + var a10 = await InsertSlot(Day(10), "A"); + var a11 = await InsertSlot(Day(11), "A"); + var a12 = await InsertSlot(Day(12), "A"); + var b10 = await InsertSlot(Day(10), "B"); + var item = DayRange(10, 13); + await Hold(item, a10, a11, a12); + await Hold(new ShoppingCartItem { Id = "other" }, b10); + + Assert.AreEqual(1, await _service.BlockReservations("p1", [a11.Id], "Repair")); + + foreach (var id in new[] { a10.Id, a12.Id }) + { + var stored = (await _repository.GetByIdAsync(id))!; + Assert.IsNull(stored.ShoppingCartItemId); + Assert.IsNull(stored.HeldUntilUtc); + Assert.IsNull(stored.BlockedNote); + } + Assert.AreEqual("other", (await _repository.GetByIdAsync(b10.Id))!.ShoppingCartItemId); + Assert.IsNull(await _service.GetHeldUntil(item)); + _mediatorMock.Verify(x => x.Publish(It.Is>(e => + e.Entity.Id == a10.Id && e.Entity.ShoppingCartItemId == null), It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task BlockReservations_StoresTheNoteTrimmed() + { + var slot = await InsertSlot(Day(10)); + + await _service.BlockReservations("p1", [slot.Id], " Repair "); + + Assert.AreEqual("Repair", (await _repository.GetByIdAsync(slot.Id))!.BlockedNote); + } + + [TestMethod] + public async Task BlockReservations_NoteTooLong_ThrowsAndBlocksNothing() + { + var slot = await InsertSlot(Day(10)); + + await Assert.ThrowsExactlyAsync(() => _service.BlockReservations("p1", [slot.Id], + new string('x', ProductReservationExtensions.MaxBlockedNoteLength + 1))); + Assert.IsNull((await _repository.GetByIdAsync(slot.Id))!.BlockedNote); + } + [TestMethod] public async Task UnblockReservations_ClearsTheNoteOfTheProductsSlotsOnly() { diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs index d5436a0e6..fd369b690 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs @@ -599,19 +599,19 @@ public async Task BlockSelectedReservations_BlocksForTheCheckedProductOnly_Trimm } [TestMethod] - public async Task BlockSelectedReservations_SomeNotBlocked_SaysTheBookedStay() + public async Task BlockSelectedReservations_SomeNotBlocked_SaysHowMany() { AccessibleProduct(); _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Blocked")).Returns("{0} blocked"); - _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.CantBlockBooked")) - .Returns("booked"); + _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.CantBlockSome")) + .Returns("{0} not blocked"); BlockingReturns(1); - var result = await _controller.BlockSelectedReservations("p1", ["free", "booked"], "Repair"); + var result = await _controller.BlockSelectedReservations("p1", ["free", "booked", "deleted"], "Repair"); Assert.AreEqual(true, JsonProperty(result, "success")); Assert.AreEqual("1 blocked", JsonProperty(result, "message")); - Assert.AreEqual("booked", JsonProperty(result, "errors")); + Assert.AreEqual("2 not blocked", JsonProperty(result, "errors")); } [TestMethod] diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs index ec771ea35..d543e1fa9 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs @@ -260,13 +260,16 @@ public async Task BlockSelectedReservations(string productId, ICo var ids = selectedIds?.Distinct().ToList() ?? []; var blocked = await productReservationService.BlockReservations(product.Id, ids, note); + //the grid keeps its selection across pages, so a slot left out may be booked or deleted meanwhile return Json(new { success = true, message = string.Format( translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.Blocked"), blocked), errors = blocked < ids.Count - ? translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.CantBlockBooked") + ? string.Format( + translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.CantBlockSome"), + ids.Count - blocked) : null }); } diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index d4507352d382d8a86cf27a89f04e93d771b20dbf..293919e04a7b8a7c7c2b59039f161b7ed6147992 100644 GIT binary patch delta 305 zcmaFzq;SX6!iE;c7N#xCe(sFL(+@rt5})pHoylPOhXvd$!U_z<3^@$>3?)EXfgumX znjUD!EX%CG5HdY-r?f1)4p2Owp=i2cgP8dAC-<2|rf1kP^GsK1lx}Ko@L&dF79eH? zVm2UV2VxE&<^*CcAm#>Q9w6ogVm=_|2Vwyr76f7;AQlE<5g--?VzKQF9^yA#VUB#@ zCay8vK$C@wGM7$f`5ZDmp_P{{-<9Yh$Vnn5{RX?|LK>` Gcmx1}x@OV< delta 298 zcmbu(yAA4N2at%M(Rl(V zUO^_`6lbP5hv(?=7|rIExpgPisyxuta=1w*rcZ5Zkw#-0kjWR#m*Ce*D5*TM9!;>D z_`r>Z)WMgA%;dsHowCu8a?7JGfeq~704KP>4KjGZ3qDZ54*>{52*MD7D8%+hU7RZR rUpG!KL~&bp+5WBC The note may have at most {0} characters. - - A booked slot cannot be blocked: it belongs to its order. + + Selected slots not blocked: {0}. They are booked, or no longer in this calendar. Blocked @@ -2985,8 +2985,8 @@ The note may have at most {0} characters. - - A booked slot cannot be blocked: it belongs to its order. + + Selected slots not blocked: {0}. They are booked, or no longer in this calendar. Blocked From 918e32f1ef56df1c136e549bf352ea1172b741f3 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 21:24:01 +0100 Subject: [PATCH 6/7] Mark a blocked reservation slot with its own field A slot was blocked when its note was not empty, so every query had to test both null and the empty string. ProductReservation.IsBlocked now decides the state and the note only says why. Queries test IsBlocked != true, which also matches a slot stored before the field existed. --- .../Products/ProductReservationService.cs | 15 ++-- .../ProductReservationExtensions.cs | 10 +-- .../Catalog/ProductReservation.cs | 8 +- .../ProductReservationExtensionsTests.cs | 9 ++- .../ProductReservationServiceTests.cs | 75 ++++++++++++++++--- .../BaseProductReservationControllerTests.cs | 3 + .../BaseProductReservationController.cs | 2 +- 7 files changed, 91 insertions(+), 31 deletions(-) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index 022660b49..7a31a2044 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -100,7 +100,7 @@ public virtual async Task> SearchProductReservati ReservationState.Held => BookableSlots(productId).Where(x => x.HeldUntilUtc > now), ReservationState.Booked => _productReservationRepository.Table .Where(x => x.ProductId == productId && x.OrderId != "" && x.OrderId != null), - ReservationState.Blocked => VacantSlots(productId).Where(x => x.BlockedNote != null && x.BlockedNote != ""), + ReservationState.Blocked => VacantSlots(productId).Where(x => x.IsBlocked), _ => _productReservationRepository.Table.Where(x => x.ProductId == productId) }; @@ -181,13 +181,14 @@ public virtual async Task BlockReservations(string productId, IList } await _productReservationRepository.UpdateManyAsync(x => blockedIds.Contains(x.Id), - ClearHold().Set(x => x.BlockedNote, note)); + ClearHold().Set(x => x.IsBlocked, true).Set(x => x.BlockedNote, note)); } foreach (var slot in released) await PublishHold(slot, null, null, null); foreach (var slot in blocked) { + slot.IsBlocked = true; slot.BlockedNote = note; await PublishHold(slot, null, null, null); } @@ -201,17 +202,18 @@ public virtual async Task UnblockReservations(string productId, IList - x.ProductId == productId && ids.Contains(x.Id) && x.BlockedNote != null && x.BlockedNote != ""); + x.ProductId == productId && ids.Contains(x.Id) && x.IsBlocked); var unblocked = await _productReservationRepository.ToListAsync(query); if (unblocked.Count == 0) return 0; var unblockedIds = unblocked.Select(x => x.Id).ToList(); await _productReservationRepository.UpdateManyAsync(x => unblockedIds.Contains(x.Id), - UpdateBuilder.Create().Set(x => x.BlockedNote, null)); + UpdateBuilder.Create().Set(x => x.IsBlocked, false).Set(x => x.BlockedNote, null)); foreach (var slot in unblocked) { + slot.IsBlocked = false; slot.BlockedNote = null; //event @@ -722,7 +724,7 @@ private async Task> SlotsToBook(Product product, Shopp { var slot = await _productReservationRepository.GetByIdAsync(shoppingCartItem.ReservationId); return slot != null && slot.ProductId == product.Id && string.IsNullOrEmpty(slot.OrderId) && - !slot.IsBlocked() && IsFreeFor(slot, shoppingCartItem.Id, now) + !slot.IsBlocked && IsFreeFor(slot, shoppingCartItem.Id, now) ? [slot] : []; } @@ -777,7 +779,8 @@ private IQueryable VacantSlots(string productId) //vacant and not blocked by staff: what a cart may hold and an order book private IQueryable BookableSlots(string productId) { - return VacantSlots(productId).Where(x => x.BlockedNote == null || x.BlockedNote == ""); + //!= true: a slot stored before the field has none, and only a test that is not "true" matches a missing field + return VacantSlots(productId).Where(x => x.IsBlocked != true); } private static string LockKey(string productId) diff --git a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs index e6af6e828..ed57456e4 100644 --- a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs @@ -207,14 +207,6 @@ public static DateTime FirstEndDate(this Product product, DateTime startDate) return null; } - /// - /// Gets whether staff took a slot out of sale - /// - public static bool IsBlocked(this ProductReservation slot) - { - return !string.IsNullOrEmpty(slot.BlockedNote); - } - /// /// Gets the state of a slot at a moment: booked by an order, blocked by staff, held by a cart until its hold /// ends, or free @@ -224,7 +216,7 @@ public static ReservationState State(this ProductReservation slot, DateTime utcN if (!string.IsNullOrEmpty(slot.OrderId)) return ReservationState.Booked; - if (slot.IsBlocked()) + if (slot.IsBlocked) return ReservationState.Blocked; //a stored date is read back in UTC (MongoDB) or local time (LiteDB) diff --git a/src/Core/Grand.Domain/Catalog/ProductReservation.cs b/src/Core/Grand.Domain/Catalog/ProductReservation.cs index a108cf08a..43178a3e7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReservation.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReservation.cs @@ -54,8 +54,12 @@ public class ProductReservation : BaseEntity public DateTime? ReminderSentOnUtc { get; set; } /// - /// Gets or sets why staff took the slot out of sale; a slot with a note is blocked: no cart can hold it and no - /// order can book it + /// Gets or sets whether staff took the slot out of sale: no cart can hold it and no order can book it + /// + public bool IsBlocked { get; set; } + + /// + /// Gets or sets why staff took the slot out of sale /// public string? BlockedNote { get; set; } diff --git a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs index 3cd64b515..2fe846604 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductReservationExtensionsTests.cs @@ -26,12 +26,13 @@ public void State_BlockedSlot_IsBlockedUnlessBooked() { var now = DateTime.UtcNow; - Assert.AreEqual(ReservationState.Blocked, new ProductReservation { BlockedNote = "Repair" }.State(now)); + Assert.AreEqual(ReservationState.Blocked, new ProductReservation { IsBlocked = true }.State(now)); Assert.AreEqual(ReservationState.Blocked, - new ProductReservation { BlockedNote = "Repair", HeldUntilUtc = now.AddMinutes(5) }.State(now)); + new ProductReservation { IsBlocked = true, HeldUntilUtc = now.AddMinutes(5) }.State(now)); Assert.AreEqual(ReservationState.Booked, - new ProductReservation { BlockedNote = "Repair", OrderId = "o1" }.State(now)); - Assert.AreEqual(ReservationState.Free, new ProductReservation { BlockedNote = "" }.State(now)); + new ProductReservation { IsBlocked = true, OrderId = "o1" }.State(now)); + //the note only says why: it does not block + Assert.AreEqual(ReservationState.Free, new ProductReservation { BlockedNote = "Repair" }.State(now)); } [TestMethod] diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs index 11a898e24..e10a352c2 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs @@ -4,6 +4,7 @@ using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Utilities.Catalog; using Grand.Data; +using Grand.Data.Mongo; using Grand.Data.Tests.LiteDb; using Grand.Data.Tests.MongoDb; using Grand.Domain.Catalog; @@ -1461,7 +1462,7 @@ private async Task InsertBlockedSlot(DateTime date, string? { var slot = new ProductReservation { Id = id, ProductId = "p1", Date = date, Resource = resource, Parameter = parameter, OrderId = "", - BlockedNote = "Repair" + IsBlocked = true, BlockedNote = "Repair" }; await _repository.InsertAsync(slot); return slot; @@ -1543,7 +1544,7 @@ public async Task SearchProductReservations_ByState_Blocked() { await InsertSlotsInEveryState(); await _repository.InsertAsync(new ProductReservation - { Id = "blocked", ProductId = "1", Date = Day(14), BlockedNote = "Repair" }); + { Id = "blocked", ProductId = "1", Date = Day(14), IsBlocked = true, BlockedNote = "Repair" }); CollectionAssert.AreEqual(new[] { "free", "expired" }, await SearchIds(ReservationState.Free)); CollectionAssert.AreEqual(new[] { "blocked" }, await SearchIds(ReservationState.Blocked)); @@ -1562,6 +1563,7 @@ public async Task BlockReservations_FreeAndHeld_BlocksAndEndsTheHold() Assert.AreEqual(2, blocked); foreach (var slot in _repository.Table.ToList()) { + Assert.IsTrue(slot.IsBlocked); Assert.AreEqual("Repair", slot.BlockedNote); Assert.IsNull(slot.ShoppingCartItemId); Assert.IsNull(slot.HeldByCustomerId); @@ -1576,6 +1578,7 @@ public async Task BlockReservations_BookedMeanwhile_StaysBooked() Assert.AreEqual(0, await _service.BlockReservations("p1", [booked.Id], "Repair")); var stored = (await _repository.GetByIdAsync(booked.Id))!; + Assert.IsFalse(stored.IsBlocked); Assert.IsNull(stored.BlockedNote); Assert.AreEqual("o1", stored.OrderId); } @@ -1662,16 +1665,19 @@ public async Task UnblockReservations_ClearsTheNoteOfTheProductsSlotsOnly() var blocked = await InsertBlockedSlot(Day(10)); var free = await InsertSlot(Day(11)); var foreign = new ProductReservation - { Id = "foreign", ProductId = "p2", Date = Day(10), OrderId = "", BlockedNote = "Repair" }; + { Id = "foreign", ProductId = "p2", Date = Day(10), OrderId = "", IsBlocked = true, BlockedNote = "Repair" }; await _repository.InsertAsync(foreign); var unblocked = await _service.UnblockReservations("p1", [blocked.Id, free.Id, foreign.Id]); Assert.AreEqual(1, unblocked); - Assert.IsNull((await _repository.GetByIdAsync(blocked.Id))!.BlockedNote); - Assert.AreEqual("Repair", (await _repository.GetByIdAsync(foreign.Id))!.BlockedNote); + var stored = (await _repository.GetByIdAsync(blocked.Id))!; + Assert.IsFalse(stored.IsBlocked); + Assert.IsNull(stored.BlockedNote); + Assert.IsTrue((await _repository.GetByIdAsync(foreign.Id))!.IsBlocked); _mediatorMock.Verify(x => x.Publish(It.Is>(e => - e.Entity.Id == blocked.Id && e.Entity.BlockedNote == null), It.IsAny()), Times.Once); + e.Entity.Id == blocked.Id && !e.Entity.IsBlocked && e.Entity.BlockedNote == null), + It.IsAny()), Times.Once); } [TestMethod] @@ -1685,11 +1691,62 @@ public async Task BlockAndUnblock_LiteDb() await _repository.InsertAsync(new ProductReservation { Id = "booked", ProductId = "p1", Date = Day(11), OrderId = "o1" }); Assert.AreEqual(1, await _service.BlockReservations("p1", ["free", "booked"], "Repair")); - Assert.AreEqual("Repair", (await _repository.GetByIdAsync("free"))!.BlockedNote); - Assert.IsNull((await _repository.GetByIdAsync("booked"))!.BlockedNote); + Assert.IsTrue((await _repository.GetByIdAsync("free"))!.IsBlocked); + Assert.IsFalse((await _repository.GetByIdAsync("booked"))!.IsBlocked); + CollectionAssert.AreEqual(new[] { "free" }, await IdsInState(ReservationState.Blocked)); + Assert.IsEmpty(await IdsInState(ReservationState.Free)); Assert.AreEqual(1, await _service.UnblockReservations("p1", ["free", "booked"])); - Assert.IsNull((await _repository.GetByIdAsync("free"))!.BlockedNote); + Assert.IsFalse((await _repository.GetByIdAsync("free"))!.IsBlocked); + CollectionAssert.AreEqual(new[] { "free" }, await IdsInState(ReservationState.Free)); + } + + [TestMethod] + public async Task SlotStoredBeforeIsBlocked_IsFree() + { + await InsertSlot(Day(10)); + var collection = ((MongoRepository)_repository).Collection; + var raw = collection.Database.GetCollection( + collection.CollectionNamespace.CollectionName); + var result = await raw.UpdateManyAsync(MongoDB.Driver.FilterDefinition.Empty, + MongoDB.Driver.Builders.Update.Unset(nameof(ProductReservation.IsBlocked))); + Assert.AreEqual(1, result.ModifiedCount); + + Assert.HasCount(1, await IdsInState(ReservationState.Free)); + Assert.IsEmpty(await IdsInState(ReservationState.Blocked)); + } + + [TestMethod] + public async Task SlotStoredBeforeIsBlocked_IsFree_LiteDb() + { + var repository = new LiteDbRepositoryOfOldSlots(); + _repository = repository; + _service = new ProductReservationService(_repository, _mediatorMock.Object, new MongoResourceLockTest(), + _shoppingCartSettings, _dateTimeServiceMock.Object, _settingServiceMock.Object); + await _repository.InsertAsync(new ProductReservation { Id = "old", ProductId = "p1", Date = Day(10), OrderId = "" }); + repository.RemoveIsBlocked(); + + CollectionAssert.AreEqual(new[] { "old" }, await IdsInState(ReservationState.Free)); + Assert.IsEmpty(await IdsInState(ReservationState.Blocked)); + } + + private async Task> IdsInState(ReservationState state) + { + return (await _service.SearchProductReservations("p1", state: state)).Select(x => x.Id).ToList(); + } + + //a slot stored before IsBlocked was added has no such field + private sealed class LiteDbRepositoryOfOldSlots : LiteDBRepositoryMock + { + public void RemoveIsBlocked() + { + var raw = Database.GetCollection(nameof(ProductReservation)); + foreach (var doc in raw.FindAll().ToList()) + { + doc.Remove(nameof(ProductReservation.IsBlocked)); + raw.Update(doc); + } + } } [TestMethod] diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs index fd369b690..d79dd7293 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs @@ -650,6 +650,7 @@ public async Task ClearCalendar_KeepsBlockedSlots_SaysHowMany() AccessibleProduct(); var free = NewReservation("free", "p1"); var blocked = NewReservation("blocked", "p1"); + blocked.IsBlocked = true; blocked.BlockedNote = "Repair"; _productReservationServiceMock .Setup(s => s.GetProductReservationsByProductId("p1", true, null, null, 0, int.MaxValue, null)) @@ -669,6 +670,7 @@ public async Task ClearOld_DeletesPastBlockedSlots() { AccessibleProduct(); var blocked = NewReservation("blocked", "p1"); + blocked.IsBlocked = true; blocked.BlockedNote = "Repair"; _productReservationServiceMock .Setup(s => s.GetProductReservationsByProductId("p1", true, null, It.IsAny(), 0, int.MaxValue, @@ -685,6 +687,7 @@ public async Task ListReservations_ShowsBlockedStateAndNote() { ViewableProduct(); var blocked = NewReservation("blocked", "p1"); + blocked.IsBlocked = true; blocked.BlockedNote = "Repair"; SearchReturns(blocked); diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs index d543e1fa9..0b5791948 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs @@ -174,7 +174,7 @@ public async Task ClearCalendar(string productId) var vacant = await productReservationService.GetProductReservationsByProductId(productId, true, null, null); //a slot staff blocked stays until they unblock it: clearing the calendar would lose their note unnoticed - var toDelete = vacant.Where(x => !x.IsBlocked()).ToList(); + var toDelete = vacant.Where(x => !x.IsBlocked).ToList(); foreach (var record in toDelete) await productReservationService.DeleteProductReservation(record); var kept = vacant.Count - toDelete.Count; From 23b02233919e77e507cfa135ffb38ad2312a9531 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 2 Dec 2026 21:46:04 +0100 Subject: [PATCH 7/7] Clear a reservation calendar in the service The rule that Clear calendar keeps blocked slots lived in the controller, which filtered the slots in memory and deleted them one by one. IProductReservationService.ClearCalendar now deletes the unblocked vacant slots in one filtered delete and returns what it deleted and kept. The blocked-slot query is one BlockedSlots helper next to BookableSlots. --- .../Products/ProductReservationService.cs | 24 +++++++++++-- .../Products/IProductReservationService.cs | 8 +++++ .../Catalog/ReservationCalendarCleared.cs | 10 ++++++ .../ProductReservationServiceTests.cs | 34 +++++++++++++++++++ .../BaseProductReservationControllerTests.cs | 26 ++++---------- .../BaseProductReservationController.cs | 12 +++---- 6 files changed, 84 insertions(+), 30 deletions(-) create mode 100644 src/Business/Grand.Business.Core/Utilities/Catalog/ReservationCalendarCleared.cs diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index 7a31a2044..b61fc0bf9 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -100,7 +100,7 @@ public virtual async Task> SearchProductReservati ReservationState.Held => BookableSlots(productId).Where(x => x.HeldUntilUtc > now), ReservationState.Booked => _productReservationRepository.Table .Where(x => x.ProductId == productId && x.OrderId != "" && x.OrderId != null), - ReservationState.Blocked => VacantSlots(productId).Where(x => x.IsBlocked), + ReservationState.Blocked => BlockedSlots(productId), _ => _productReservationRepository.Table.Where(x => x.ProductId == productId) }; @@ -146,6 +146,19 @@ await _productReservationRepository.DeleteManyAsync(x => return vacant.Count; } + public virtual async Task ClearCalendar(string productId) + { + var query = BookableSlots(productId); + var deleted = await _productReservationRepository.CountAsync(query); + //one filtered delete: a slot booked or blocked meanwhile is checked as it is deleted, and stays + await _productReservationRepository.DeleteManyAsync(x => + x.ProductId == productId && (x.OrderId == "" || x.OrderId == null) && x.IsBlocked != true); + + var blockedQuery = BlockedSlots(productId); + var blockedKept = await _productReservationRepository.CountAsync(blockedQuery); + return new ReservationCalendarCleared(deleted, blockedKept); + } + public virtual async Task BlockReservations(string productId, IList ids, string note) { ArgumentException.ThrowIfNullOrWhiteSpace(note); @@ -201,8 +214,7 @@ public virtual async Task UnblockReservations(string productId, IList - x.ProductId == productId && ids.Contains(x.Id) && x.IsBlocked); + var query = BlockedSlots(productId).Where(x => ids.Contains(x.Id)); var unblocked = await _productReservationRepository.ToListAsync(query); if (unblocked.Count == 0) return 0; @@ -783,6 +795,12 @@ private IQueryable BookableSlots(string productId) return VacantSlots(productId).Where(x => x.IsBlocked != true); } + //taken out of sale by staff; a booked slot cannot be blocked + private IQueryable BlockedSlots(string productId) + { + return VacantSlots(productId).Where(x => x.IsBlocked); + } + private static string LockKey(string productId) { return $"{nameof(ProductReservation)}:{productId}"; diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs index 8dc48ccfa..8f56655cc 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs @@ -145,6 +145,14 @@ Task> SearchProductReservations(string productId, /// Number of the slots deleted Task DeleteVacantReservations(string productId, IList ids); + /// + /// Deletes the slots of a product that no order booked, a slot held in a cart included; a slot staff blocked + /// stays until they unblock it, so its note is not lost unnoticed + /// + /// Product Id + /// Slots deleted, and blocked slots kept + Task ClearCalendar(string productId); + /// /// Takes out of sale the slots of a product among the given ones that no order booked: no cart can hold them /// and no order can book them until they are unblocked. The hold of a cart item on any of them ends, on its diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationCalendarCleared.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationCalendarCleared.cs new file mode 100644 index 000000000..82913537b --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ReservationCalendarCleared.cs @@ -0,0 +1,10 @@ +namespace Grand.Business.Core.Utilities.Catalog; + +/// +/// What clearing a calendar did +/// +/// slots deleted +/// slots kept because staff blocked them +public record ReservationCalendarCleared( + int Deleted, + int BlockedKept); diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs index e10a352c2..c8842f3ac 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs @@ -1701,6 +1701,40 @@ public async Task BlockAndUnblock_LiteDb() CollectionAssert.AreEqual(new[] { "free" }, await IdsInState(ReservationState.Free)); } + [TestMethod] + public async Task ClearCalendar_DeletesFreeAndHeld_KeepsBookedBlockedAndOtherProducts() + { + var free = await InsertSlot(Day(10)); + var held = await InsertSlot(Day(11)); + await Hold(new ShoppingCartItem { Id = "sci1" }, held); + var booked = await InsertSlot(Day(12), orderId: "o1"); + var blocked = await InsertBlockedSlot(Day(13)); + var foreign = await InsertSlot(Day(10), productId: "p2"); + + var cleared = await _service.ClearCalendar("p1"); + + Assert.AreEqual(new ReservationCalendarCleared(2, 1), cleared); + CollectionAssert.AreEquivalent(new[] { booked.Id, blocked.Id, foreign.Id }, + _repository.Table.Select(x => x.Id).ToList()); + Assert.IsNull(await _repository.GetByIdAsync(free.Id)); + } + + [TestMethod] + public async Task ClearCalendar_LiteDb() + { + _repository = new LiteDBRepositoryMock(); + _service = new ProductReservationService(_repository, _mediatorMock.Object, new MongoResourceLockTest(), + _shoppingCartSettings, _dateTimeServiceMock.Object, _settingServiceMock.Object); + //LiteDB stores the empty OrderId as null + await _repository.InsertAsync(new ProductReservation { Id = "free", ProductId = "p1", Date = Day(10), OrderId = "" }); + await _repository.InsertAsync(new ProductReservation { Id = "booked", ProductId = "p1", Date = Day(11), OrderId = "o1" }); + await _repository.InsertAsync(new ProductReservation + { Id = "blocked", ProductId = "p1", Date = Day(12), OrderId = "", IsBlocked = true, BlockedNote = "Repair" }); + + Assert.AreEqual(new ReservationCalendarCleared(1, 1), await _service.ClearCalendar("p1")); + CollectionAssert.AreEquivalent(new[] { "booked", "blocked" }, _repository.Table.Select(x => x.Id).ToList()); + } + [TestMethod] public async Task SlotStoredBeforeIsBlocked_IsFree() { diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs index d79dd7293..a86ffc8c2 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductReservationControllerTests.cs @@ -382,27 +382,23 @@ public async Task ClearCalendar_ScopeDeniesAccess_ReturnsErrorsJson_DoesNotDelet var result = await _controller.ClearCalendar("p1"); Assert.AreEqual("denied", JsonProperty(result, "errors")); - _productReservationServiceMock.Verify( - s => s.DeleteProductReservation(It.IsAny()), Times.Never); + _productReservationServiceMock.Verify(s => s.ClearCalendar(It.IsAny()), Times.Never); } [TestMethod] - public async Task ClearCalendar_ScopeGrantsAccess_DeletesAllReservations() + public async Task ClearCalendar_ScopeGrantsAccess_ClearsTheCheckedProduct() { 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, null)) - .ReturnsAsync(new PagedList(new List { reservation }, 0, int.MaxValue)); + _productReservationServiceMock.Setup(s => s.ClearCalendar("p1")).ReturnsAsync(new ReservationCalendarCleared(1, 0)); _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Deleted")).Returns("{0} deleted"); var result = await _controller.ClearCalendar("p1"); Assert.AreEqual(true, JsonProperty(result, "success")); Assert.AreEqual("1 deleted", JsonProperty(result, "message")); - _productReservationServiceMock.Verify(s => s.DeleteProductReservation(reservation), Times.Once); + _productReservationServiceMock.Verify(s => s.ClearCalendar("p1"), Times.Once); } // --- ClearOld --------------------------------------------------------------------------------------- @@ -645,24 +641,16 @@ public async Task UnblockSelectedReservations_UnblocksForTheCheckedProductOnly() } [TestMethod] - public async Task ClearCalendar_KeepsBlockedSlots_SaysHowMany() + public async Task ClearCalendar_BlockedSlotsKept_SaysHowMany() { AccessibleProduct(); - var free = NewReservation("free", "p1"); - var blocked = NewReservation("blocked", "p1"); - blocked.IsBlocked = true; - blocked.BlockedNote = "Repair"; - _productReservationServiceMock - .Setup(s => s.GetProductReservationsByProductId("p1", true, null, null, 0, int.MaxValue, null)) - .ReturnsAsync(new PagedList(new List { free, blocked }, 0, int.MaxValue)); + _productReservationServiceMock.Setup(s => s.ClearCalendar("p1")).ReturnsAsync(new ReservationCalendarCleared(1, 2)); _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.Deleted")).Returns("{0} deleted"); _translationServiceMock.Setup(t => t.GetResource("Admin.Catalog.Products.Calendar.BlockedKept")).Returns("{0} kept"); var result = await _controller.ClearCalendar("p1"); - Assert.AreEqual("1 deleted\n1 kept", JsonProperty(result, "message")); - _productReservationServiceMock.Verify(s => s.DeleteProductReservation(free), Times.Once); - _productReservationServiceMock.Verify(s => s.DeleteProductReservation(blocked), Times.Never); + Assert.AreEqual("1 deleted\n2 kept", JsonProperty(result, "message")); } [TestMethod] diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs index 0b5791948..fb745cb7e 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseProductReservationController.cs @@ -172,17 +172,13 @@ public async Task ClearCalendar(string productId) if (!await scope.HasAccess(product)) return Json(new { errors = translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions") }); - var vacant = await productReservationService.GetProductReservationsByProductId(productId, true, null, null); - //a slot staff blocked stays until they unblock it: clearing the calendar would lose their note unnoticed - var toDelete = vacant.Where(x => !x.IsBlocked).ToList(); - foreach (var record in toDelete) await productReservationService.DeleteProductReservation(record); + var cleared = await productReservationService.ClearCalendar(product.Id); - var kept = vacant.Count - toDelete.Count; - var message = DeletedMessage(toDelete.Count); - if (kept > 0) + var message = DeletedMessage(cleared.Deleted); + if (cleared.BlockedKept > 0) message += "\n" + string.Format( translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Calendar.BlockedKept"), - kept); + cleared.BlockedKept); return Json(new { success = true, message }); }