Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,11 @@ public virtual async Task<IPagedList<ProductReservation>> 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 => BlockedSlots(productId),
_ => _productReservationRepository.Table.Where(x => x.ProductId == productId)
};

Expand Down Expand Up @@ -145,6 +146,95 @@ await _productReservationRepository.DeleteManyAsync(x =>
return vacant.Count;
}

public virtual async Task<ReservationCalendarCleared> 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<int> BlockReservations(string productId, IList<string> ids, string note)
{
ArgumentException.ThrowIfNullOrWhiteSpace(note);
note = note.Trim();
ArgumentOutOfRangeException.ThrowIfGreaterThan(note.Length, ProductReservationExtensions.MaxBlockedNoteLength,
nameof(note));
if (ids.Count == 0)
return 0;

List<ProductReservation> blocked;
List<ProductReservation> released;
//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 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.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);
}

return blocked.Count;
}

public virtual async Task<int> UnblockReservations(string productId, IList<string> ids)
{
if (ids.Count == 0)
return 0;

var query = BlockedSlots(productId).Where(x => ids.Contains(x.Id));
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<ProductReservation>.Create().Set(x => x.IsBlocked, false).Set(x => x.BlockedNote, null));

foreach (var slot in unblocked)
{
slot.IsBlocked = false;
slot.BlockedNote = null;

//event
await _mediator.EntityUpdated(slot);
}

return unblocked.Count;
}

/// <summary>
/// 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
Expand All @@ -155,7 +245,7 @@ await _productReservationRepository.DeleteManyAsync(x =>
public virtual async Task<IList<FirstVacantDate>> 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
Expand Down Expand Up @@ -200,8 +290,8 @@ public virtual async Task<IList<ReservationAvailableDate>> 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
Expand Down Expand Up @@ -646,7 +736,7 @@ private async Task<IList<ProductReservation>> 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]
: [];
}
Expand All @@ -658,10 +748,11 @@ private async Task<IList<ProductReservation>> 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();
Expand Down Expand Up @@ -697,6 +788,19 @@ private IQueryable<ProductReservation> 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<ProductReservation> BookableSlots(string productId)
{
//!= 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);
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
}

//taken out of sale by staff; a booked slot cannot be blocked
private IQueryable<ProductReservation> BlockedSlots(string productId)
{
return VacantSlots(productId).Where(x => x.IsBlocked);
}

private static string LockKey(string productId)
{
return $"{nameof(ProductReservation)}:{productId}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ public static class ProductReservationExtensions
/// </summary>
public const int MaxReservationHorizonDays = 3650;

/// <summary>
/// The most characters of the note staff block a slot with
/// </summary>
public const int MaxBlockedNoteLength = 400;

/// <summary>
/// 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
Expand Down Expand Up @@ -203,13 +208,17 @@ public static DateTime FirstEndDate(this Product product, DateTime startDate)
}

/// <summary>
/// Gets the state of a slot at a moment: booked by an order, held by a cart until its hold ends, or free
/// 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
/// </summary>
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,37 @@ Task<IPagedList<ProductReservation>> SearchProductReservations(string productId,
/// <returns>Number of the slots deleted</returns>
Task<int> DeleteVacantReservations(string productId, IList<string> ids);

/// <summary>
/// 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
/// </summary>
/// <param name="productId">Product Id</param>
/// <returns>Slots deleted, and blocked slots kept</returns>
Task<ReservationCalendarCleared> ClearCalendar(string productId);

/// <summary>
/// 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
/// other slots too; a blocked slot gets the new note. A slot booked meanwhile, or one of another product,
/// stays as it is.
/// </summary>
/// <param name="productId">Product Id</param>
/// <param name="ids">Identifiers of the slots to block</param>
/// <param name="note">
/// Why the slots are blocked, stored trimmed; at most
/// <see cref="Extensions.ProductReservationExtensions.MaxBlockedNoteLength" /> characters
/// </param>
/// <returns>Number of the slots blocked</returns>
Task<int> BlockReservations(string productId, IList<string> ids, string note);

/// <summary>
/// Puts back on sale the blocked slots of a product among the given ones
/// </summary>
/// <param name="productId">Product Id</param>
/// <param name="ids">Identifiers of the slots to unblock</param>
/// <returns>Number of the slots unblocked</returns>
Task<int> UnblockReservations(string productId, IList<string> ids);

/// <summary>
/// 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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Grand.Business.Core.Utilities.Catalog;

/// <summary>
/// What clearing a calendar did
/// </summary>
/// <param name="Deleted">slots deleted</param>
/// <param name="BlockedKept">slots kept because staff blocked them</param>
public record ReservationCalendarCleared(
int Deleted,
int BlockedKept);
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,10 @@ public enum ReservationState
/// <summary>
/// An order booked it
/// </summary>
Booked = 2
Booked = 2,

/// <summary>
/// Staff took it out of sale with a note
/// </summary>
Blocked = 3
}
10 changes: 10 additions & 0 deletions src/Core/Grand.Domain/Catalog/ProductReservation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ public class ProductReservation : BaseEntity
/// </summary>
public DateTime? ReminderSentOnUtc { get; set; }

/// <summary>
/// Gets or sets whether staff took the slot out of sale: no cart can hold it and no order can book it
/// </summary>
public bool IsBlocked { get; set; }

/// <summary>
/// Gets or sets why staff took the slot out of sale
/// </summary>
public string? BlockedNote { get; set; }

/// <summary>
/// Gets or sets resource name
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,20 @@ 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 { IsBlocked = true }.State(now));
Assert.AreEqual(ReservationState.Blocked,
new ProductReservation { IsBlocked = true, HeldUntilUtc = now.AddMinutes(5) }.State(now));
Assert.AreEqual(ReservationState.Booked,
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]
public void FindGroupToBook_WarsawMidnightSlots_MatchTheStoreDays()
{
Expand Down
Loading
Loading