Facility booking-mode redesign, multi-plan subscriptions, and Classes

Implements the facility-classes-booking-dashboard plan (backend):

- Facility.BookingMode (single Scheduled/AdHoc choice) replaced with
  independent SupportsClasses/SupportsBooking flags, so one facility
  can run a class and accept walk-in bookings; a running class now
  blocks walk-in booking for its window on both create and reschedule.
- CustomerPlan.GrantsGymAccess + CustomerPlanClass join table let a
  customer hold one gym-access plan plus any number of class-only
  plans. Replaced the old single-subscription resolution
  (GetActiveSubscriptionByCustomerId/HasAnyActiveSubscriptionAsync)
  with gym-access-aware and class-aware resolvers across booking
  creation/cancellation, plan assignment, and customer self-service.
  Fixed ChangeMembershipPlan/renewal plan-changes, which resolved "the
  subscription to replace" by most-recent-created and would have
  deactivated a member's class subscription instead of their gym one.
- New FacilityClass model: recurring class definitions (Daily/Weekly/
  Monthly/Custom) with lazy occurrence generation (8-week horizon,
  race-safe via a unique index) and proper unlimited-capacity handling.
  "Mark not held" replaces the old bare-cancel: cascades to cancel and
  refund every confirmed booking on the occurrence through the same
  core CancelBooking uses, and frees the slot for walk-in booking.
  Scheduling conflicts (a walk-in booking now overlapping a class) are
  surfaced for staff to resolve via the existing Reschedule flow.
- Renamed the pre-existing "AdHoc" booking-mode terminology to
  "WalkIn" throughout (routes, methods, DTOs, the stored BookingMode
  value) for a clearer, simpler name.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 14:26:59 +05:30
parent 1a502767ba
commit 5d711bd13e
38 changed files with 1437 additions and 226 deletions
+81 -40
View File
@@ -50,8 +50,14 @@ namespace Fitness_core_BE.Services
if (await _bookingRepository.CustomerHasActiveBookingForSession(facilitySessionId, cusId))
throw new ArgumentException("You already have a booking for this session");
var subscription = await _customerSubscriptionRepository.GetActiveSubscriptionByCustomerId(cusId)
?? throw new ArgumentException("No active membership plan found");
// A class occurrence (FKFacilityClassId set) must be covered by a subscription
// linked to that specific class; a legacy/manually-created session (null) falls
// back to the customer's gym-access subscription, same as before Classes existed.
var subscription = session.FKFacilityClassId.HasValue
? await _customerSubscriptionRepository.GetActiveSubscriptionForClassAsync(cusId, session.FKFacilityClassId.Value)
?? throw new ArgumentException("Your membership doesn't cover this class.")
: await _customerSubscriptionRepository.GetActiveGymAccessSubscriptionAsync(cusId)
?? throw new ArgumentException("No active membership plan found");
// Null SessionsPerCycle = unlimited-access plan (existing gym behavior) --
// no allowance to check. A set value caps how many Facility sessions this
@@ -70,10 +76,13 @@ namespace Fitness_core_BE.Services
throw new ArgumentException("You've used all the sessions included in your current plan cycle");
}
var capacity = session.Capacity ?? session.Facility?.DefaultCapacity ?? 1;
var bookedCount = await _facilityRepository.GetActiveBookingCount(facilitySessionId);
if (bookedCount >= capacity)
throw new ArgumentException("This session is fully booked");
if (!session.IsUnlimitedCapacity)
{
var capacity = session.Capacity ?? session.Facility?.DefaultCapacity ?? 1;
var bookedCount = await _facilityRepository.GetActiveBookingCount(facilitySessionId);
if (bookedCount >= capacity)
throw new ArgumentException("This session is fully booked");
}
var booking = new Booking
{
@@ -124,10 +133,13 @@ namespace Fitness_core_BE.Services
if (session.StartTime <= DateTime.UtcNow)
throw new ArgumentException("This session has already started");
var capacity = session.Capacity ?? session.Facility?.DefaultCapacity ?? 1;
var bookedCount = await _facilityRepository.GetActiveBookingCount(facilitySessionId);
if (bookedCount >= capacity)
throw new ArgumentException("This session is fully booked");
if (!session.IsUnlimitedCapacity)
{
var capacity = session.Capacity ?? session.Facility?.DefaultCapacity ?? 1;
var bookedCount = await _facilityRepository.GetActiveBookingCount(facilitySessionId);
if (bookedCount >= capacity)
throw new ArgumentException("This session is fully booked");
}
var booking = new Booking
{
@@ -161,14 +173,14 @@ namespace Fitness_core_BE.Services
}
}
// ---------- AdHoc-mode creation (new) ----------
// ---------- WalkIn-mode creation (new) ----------
public async Task<object> CreateMemberAdhocBooking(object payload, HttpContext httpContext)
public async Task<object> CreateMemberWalkInBooking(object payload, HttpContext httpContext)
{
await _uow.BeginAsync();
try
{
var (facility, startTime, endTime, partySize, _) = await ValidateAdhocRequestAsync(payload);
var (facility, startTime, endTime, partySize, _) = await ValidateWalkInRequestAsync(payload);
var cusId = await _userRoleHelper.GetCusId(DataExtractor.GetUserIdFromContext(httpContext));
@@ -201,12 +213,12 @@ namespace Fitness_core_BE.Services
}
}
public async Task<object> CreateGuestAdhocBooking(object payload, HttpContext httpContext)
public async Task<object> CreateGuestWalkInBooking(object payload, HttpContext httpContext)
{
await _uow.BeginAsync();
try
{
var (facility, startTime, endTime, partySize, pricePerHour) = await ValidateAdhocRequestAsync(payload);
var (facility, startTime, endTime, partySize, pricePerHour) = await ValidateWalkInRequestAsync(payload);
var data = DeserializePayload.Deserialize(payload);
var guestName = data["guestName"].GetString() ?? throw new ArgumentException("guestName is required");
@@ -249,11 +261,11 @@ namespace Fitness_core_BE.Services
}
}
/// <summary>Shared validation for both AdHoc creation paths: facility must be AdHoc-mode,
/// requested window must have a free unit. Locks the facility row for the duration of the
/// caller's transaction so two concurrent claims on the same facility serialize instead of
/// both reading "room available" before either commits.</summary>
private async Task<(Facility facility, DateTime startTime, DateTime endTime, int? partySize, decimal? pricePerHour)> ValidateAdhocRequestAsync(object payload)
/// <summary>Shared validation for both WalkIn creation paths: facility must support
/// walk-in booking, requested window must have a free unit. Locks the facility row for
/// the duration of the caller's transaction so two concurrent claims on the same facility
/// serialize instead of both reading "room available" before either commits.</summary>
private async Task<(Facility facility, DateTime startTime, DateTime endTime, int? partySize, decimal? pricePerHour)> ValidateWalkInRequestAsync(object payload)
{
var data = DeserializePayload.Deserialize(payload);
var facilityId = Guid.Parse(data["facilityId"].GetString()!);
@@ -276,13 +288,20 @@ namespace Fitness_core_BE.Services
var facility = await _facilityRepository.GetFacilityById(facilityId)
?? throw new KeyNotFoundException("Facility not found");
if (facility.BookingMode != "AdHoc")
throw new ArgumentException("This facility does not support ad-hoc booking");
if (!facility.SupportsBooking)
throw new ArgumentException("This facility does not support walk-in booking");
if (!facility.IsActive)
throw new ArgumentException("This facility is not active");
await _facilityRepository.LockFacilityForUpdateAsync(facilityId);
var overlapping = await _facilityRepository.GetOverlappingAdhocBookingCountAsync(facilityId, startTime, endTime);
// A running class occupies the whole facility, not just a seat -- reject the walk-in
// request outright rather than letting it compete for units.
var overlappingSessions = await _facilityRepository.GetOverlappingActiveSessionsAsync(facilityId, startTime, endTime);
if (overlappingSessions.Count > 0)
throw new ArgumentException("This facility is occupied by a scheduled class during the requested time");
var overlapping = await _facilityRepository.GetOverlappingWalkInBookingCountAsync(facilityId, startTime, endTime);
if (overlapping >= facility.NumberOfUnits)
throw new ArgumentException("No units are free for the requested time");
@@ -291,7 +310,7 @@ namespace Fitness_core_BE.Services
/// <summary>Staff can optionally identify a walk-in guest as an already-registered member
/// (search-and-pick, not free-typed) -- purely for identification/auto-fill on the FE, see
/// CreateGuestBooking/CreateGuestAdhocBooking. Doesn't change IsGuest, PaymentStatus, or
/// CreateGuestBooking/CreateGuestWalkInBooking. Doesn't change IsGuest, PaymentStatus, or
/// any membership handling; FKCustomerId is just an informational link layered on top of
/// an otherwise-ordinary guest booking.</summary>
private async Task<Guid?> ResolveOptionalCustomerLinkAsync(Dictionary<string, JsonElement> data)
@@ -448,18 +467,7 @@ namespace Fitness_core_BE.Services
if (booking.Status == "CheckedIn")
throw new ArgumentException("This booking has already been checked in and can't be cancelled");
booking.Status = "Cancelled";
// Give the session allowance back -- only member bookings draw one down.
if (!booking.IsGuest && booking.FKCustomerSubscriptionId.HasValue)
{
var subscription = await _customerSubscriptionRepository.GetActiveSubscriptionByCustomerId(booking.FKCustomerId!.Value);
if (subscription != null && subscription.SubscriptionId == booking.FKCustomerSubscriptionId.Value
&& subscription.CustomerPlan.SessionsPerCycle.HasValue && subscription.SessionsUsedThisCycle > 0)
{
subscription.SessionsUsedThisCycle--;
}
}
await CancelBookingCore(booking);
await _uow.CommitAsync();
return MapToDto(booking, includeOtp: false);
@@ -471,6 +479,29 @@ namespace Fitness_core_BE.Services
}
}
/// <summary>Just the in-memory mutations (status + subscription allowance refund), no
/// transaction demarcation or status validation -- called both by CancelBooking (after
/// its own status checks) and by FacilityService's "mark not held" cascade (which does
/// its own per-booking filtering before calling this for each affected booking), so
/// there's one refund code path instead of two. Looks the subscription up by the exact
/// id the booking drew its allowance from, rather than re-resolving "the customer's
/// current active subscription" -- correct regardless of which kind of subscription
/// (gym-access or class-linked) it was, and unaffected by the customer holding others.</summary>
public async Task CancelBookingCore(Booking booking)
{
booking.Status = "Cancelled";
// Give the session allowance back -- only member bookings draw one down.
if (!booking.IsGuest && booking.FKCustomerSubscriptionId.HasValue)
{
var subscription = await _customerSubscriptionRepository.GetCustomerSubscriptionById(booking.FKCustomerSubscriptionId.Value);
if (subscription != null && subscription.CustomerPlan.SessionsPerCycle.HasValue && subscription.SessionsUsedThisCycle > 0)
{
subscription.SessionsUsedThisCycle--;
}
}
}
public async Task<object> ReassignBooking(object payload, HttpContext httpContext)
{
await _uow.BeginAsync();
@@ -514,9 +545,9 @@ namespace Fitness_core_BE.Services
if (booking.FKFacilitySessionId == null)
{
// AdHoc: move to a new time on the same facility.
// WalkIn: move to a new time on the same facility.
if (!data.ContainsKey("startTime") || !data.ContainsKey("durationMinutes"))
throw new ArgumentException("startTime and durationMinutes are required to reschedule an ad-hoc booking");
throw new ArgumentException("startTime and durationMinutes are required to reschedule a walk-in booking");
var startTime = DateTime.Parse(data["startTime"].GetString()!).ToUniversalTime();
var durationMinutes = data["durationMinutes"].GetInt32();
@@ -524,7 +555,15 @@ namespace Fitness_core_BE.Services
var endTime = startTime.AddMinutes(durationMinutes);
await _facilityRepository.LockFacilityForUpdateAsync(booking.FKFacilityId);
var overlapping = await _facilityRepository.GetOverlappingAdhocBookingCountAsync(
// Same class-occupancy guard as a fresh walk-in request -- otherwise staff
// could reschedule straight into a scheduled class's time.
var overlappingSessions = await _facilityRepository.GetOverlappingActiveSessionsAsync(
booking.FKFacilityId, startTime, endTime);
if (overlappingSessions.Count > 0)
throw new ArgumentException("This facility is occupied by a scheduled class during the requested time");
var overlapping = await _facilityRepository.GetOverlappingWalkInBookingCountAsync(
booking.FKFacilityId, startTime, endTime, excludeBookingId: booking.BookingId);
var facility = booking.Facility ?? await _facilityRepository.GetFacilityById(booking.FKFacilityId)
@@ -777,7 +816,9 @@ namespace Fitness_core_BE.Services
FacilitySessionId = booking.FKFacilitySessionId,
FacilityId = booking.FKFacilityId,
FacilityName = booking.Facility?.Name,
BookingMode = booking.Facility?.BookingMode ?? (booking.FKFacilitySessionId.HasValue ? "Scheduled" : "AdHoc"),
// Per-booking fact (which path created it) -- a facility can support both modes now,
// so this no longer derives from the facility at all.
BookingMode = booking.FKFacilitySessionId.HasValue ? "Scheduled" : "WalkIn",
StartTime = booking.StartTime,
EndTime = booking.EndTime,
PartySize = booking.PartySize,