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:
@@ -354,12 +354,22 @@ namespace Fitness_core_BE.Repos
|
||||
// Unlike CustomerSubscription.FKCustomerId (which only ever points at the primary
|
||||
// member), this resolves the caller's own SubscriptionMember row whether they're
|
||||
// the primary or a secondary member of a group subscription.
|
||||
// Both callers (ClientService.ChangeCustomerMembershipPlan,
|
||||
// SubscriptionRenewalApprovalService.ChangePlanAsync) reject a Group-scope new plan and
|
||||
// are conceptually "swap the member's individual gym plan" -- so this must resolve to
|
||||
// their GYM-ACCESS subscription specifically, not just whichever active subscription
|
||||
// happens to be most recently created. Without this filter, a member holding both a gym
|
||||
// plan and a class-only plan would have their class subscription silently deactivated
|
||||
// and replaced instead of their gym one, once a class subscription could outrank it by
|
||||
// CreatedAt.
|
||||
public async Task<SubscriptionMember?> GetActiveMembershipForCustomerAsync(Guid customerId, CancellationToken ct = default)
|
||||
{
|
||||
return await _dbContext.SubscriptionMembers
|
||||
.Include(m => m.Subscription)
|
||||
.ThenInclude(s => s.CustomerPlan)
|
||||
.Where(m => m.FKCustomerId == customerId && m.IsActive && m.Subscription.IsActive)
|
||||
.Where(m => !_dbContext.CustomerPlanClasses.Any(c => c.FKCustomerPlanId == m.Subscription.FKCustomerPlanId)
|
||||
|| m.Subscription.CustomerPlan.GrantsGymAccess)
|
||||
.OrderByDescending(m => m.Subscription.CreatedAt)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ namespace Fitness_core_BE.Repos
|
||||
}
|
||||
|
||||
// Staff picking an existing member to link a walk-in booking to (identification only,
|
||||
// see BookingService.CreateGuestBooking/CreateGuestAdhocBooking) -- tenant-scoped by
|
||||
// see BookingService.CreateGuestBooking/CreateGuestWalkInBooking) -- tenant-scoped by
|
||||
// construction, same as FindActiveLinkByIdentifierAsync above.
|
||||
public Task<TenantCustomerLink?> GetTenantCustomerLinkById(Guid id)
|
||||
=> _context.TenantCustomerLink
|
||||
|
||||
@@ -134,23 +134,69 @@ namespace Fitness_core_BE.Repos
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<CustomerSubscription?> GetActiveSubscriptionByCustomerId(Guid customerId)
|
||||
// A plan with no CustomerPlanClass links is an ordinary gym plan -- GrantsGymAccess is
|
||||
// never consulted for it (always true in effect). A class-linked plan only grants gym
|
||||
// access when GrantsGymAccess is explicitly set. Reused by every gym-access query below.
|
||||
private IQueryable<CustomerPlan> GymAccessPlans() => _context.CustomerPlans.Where(p =>
|
||||
!_context.CustomerPlanClasses.Any(c => c.FKCustomerPlanId == p.CustomerPlanId) || p.GrantsGymAccess);
|
||||
|
||||
public Task<bool> PlanGrantsGymAccessAsync(Guid customerPlanId, CancellationToken ct = default)
|
||||
=> GymAccessPlans().AnyAsync(p => p.CustomerPlanId == customerPlanId, ct);
|
||||
|
||||
public async Task<CustomerSubscription?> GetActiveGymAccessSubscriptionAsync(Guid customerId)
|
||||
{
|
||||
return await _context.CustomerSubscriptions
|
||||
.Include(s => s.TenantCustomerLink)
|
||||
.Include(s => s.CustomerPlan)
|
||||
.Where(s => s.FKCustomerId == customerId && s.IsActive)
|
||||
.Where(s => GymAccessPlans().Any(p => p.CustomerPlanId == s.FKCustomerPlanId))
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
public async Task<CustomerSubscription?> GetActiveSubscriptionForPlanAsync(Guid customerId, Guid customerPlanId)
|
||||
{
|
||||
return await _context.CustomerSubscriptions
|
||||
.Include(s => s.CustomerPlan)
|
||||
.Where(s => s.FKCustomerId == customerId && s.IsActive && s.FKCustomerPlanId == customerPlanId)
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
/// <summary>Resolves which of the customer's (possibly several) active subscriptions
|
||||
/// covers a specific class, preferring one that still has quota left this cycle over one
|
||||
/// that's already exhausted it -- two different plans can link the same class.</summary>
|
||||
public async Task<CustomerSubscription?> GetActiveSubscriptionForClassAsync(Guid customerId, Guid facilityClassId)
|
||||
{
|
||||
var candidates = await _context.CustomerSubscriptions
|
||||
.Include(s => s.CustomerPlan)
|
||||
.Where(s => s.FKCustomerId == customerId && s.IsActive)
|
||||
.Where(s => _context.CustomerPlanClasses.Any(c =>
|
||||
c.FKCustomerPlanId == s.FKCustomerPlanId && c.FKFacilityClassId == facilityClassId))
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.ToListAsync();
|
||||
|
||||
bool HasQuota(CustomerSubscription s)
|
||||
{
|
||||
if (!s.CustomerPlan.SessionsPerCycle.HasValue) return true;
|
||||
var carriedOver = s.SessionsCarriedOverExpiresAt.HasValue && s.SessionsCarriedOverExpiresAt.Value < DateTime.UtcNow
|
||||
? 0 : s.SessionsCarriedOver;
|
||||
return s.SessionsUsedThisCycle < s.CustomerPlan.SessionsPerCycle.Value + carriedOver;
|
||||
}
|
||||
|
||||
return candidates.FirstOrDefault(HasQuota) ?? candidates.FirstOrDefault();
|
||||
}
|
||||
|
||||
// SubscriptionMembers always has a row for the primary too (CustomerSubscriptionFactory
|
||||
// adds it alongside the CustomerSubscription itself), so this one query covers both
|
||||
// "primary somewhere" and "secondary/group member somewhere" in a single check.
|
||||
public Task<bool> HasAnyActiveSubscriptionAsync(Guid customerId, CancellationToken ct = default)
|
||||
// "primary somewhere" and "secondary/group member somewhere" in a single check. Scoped
|
||||
// to gym-access plans only -- a class-only subscription never blocks a second one via
|
||||
// this check (unlimited concurrent class-only subscriptions are allowed).
|
||||
public Task<bool> HasActiveGymAccessPlanAsync(Guid customerId, CancellationToken ct = default)
|
||||
{
|
||||
return _context.SubscriptionMembers.AnyAsync(m =>
|
||||
m.FKCustomerId == customerId && m.IsActive && m.Subscription.IsActive, ct);
|
||||
m.FKCustomerId == customerId && m.IsActive && m.Subscription.IsActive &&
|
||||
GymAccessPlans().Any(p => p.CustomerPlanId == m.Subscription.FKCustomerPlanId), ct);
|
||||
}
|
||||
|
||||
// ---------- Group membership ----------
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
using Fitness_core_BE.Interfaces;
|
||||
using Fitness_core_BE.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Fitness_core_BE.Repos
|
||||
{
|
||||
public class FacilityClassRepository : IFacilityClassRepository
|
||||
{
|
||||
private readonly TenantDbContext _context;
|
||||
|
||||
public FacilityClassRepository(TenantDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<FacilityClass> CreateFacilityClass(FacilityClass facilityClass)
|
||||
{
|
||||
facilityClass.FacilityClassId = Guid.NewGuid();
|
||||
facilityClass.CreatedAt = DateTime.UtcNow;
|
||||
facilityClass.IsActive = true;
|
||||
|
||||
_context.FacilityClasses.Add(facilityClass);
|
||||
return facilityClass;
|
||||
}
|
||||
|
||||
public async Task<List<FacilityClass>> GetFacilityClasses(Guid clientId, bool includeInactive = false)
|
||||
{
|
||||
var query = _context.FacilityClasses
|
||||
.Include(fc => fc.Facility)
|
||||
.Where(fc => fc.FKClientId == clientId);
|
||||
if (!includeInactive)
|
||||
query = query.Where(fc => fc.IsActive);
|
||||
|
||||
return await query.OrderBy(fc => fc.Name).ToListAsync();
|
||||
}
|
||||
|
||||
public Task<FacilityClass?> GetFacilityClassById(Guid facilityClassId)
|
||||
=> _context.FacilityClasses
|
||||
.Include(fc => fc.Facility)
|
||||
.FirstOrDefaultAsync(fc => fc.FacilityClassId == facilityClassId);
|
||||
|
||||
public async Task<FacilityClass> UpdateFacilityClass(FacilityClass facilityClass)
|
||||
{
|
||||
var existing = await _context.FacilityClasses.FindAsync(facilityClass.FacilityClassId)
|
||||
?? throw new KeyNotFoundException("Class not found");
|
||||
|
||||
existing.Name = facilityClass.Name;
|
||||
existing.Description = facilityClass.Description;
|
||||
existing.RecurrenceType = facilityClass.RecurrenceType;
|
||||
existing.StartTimeOfDay = facilityClass.StartTimeOfDay;
|
||||
existing.DurationMinutes = facilityClass.DurationMinutes;
|
||||
existing.WeekDaysMask = facilityClass.WeekDaysMask;
|
||||
existing.MonthDays = facilityClass.MonthDays;
|
||||
existing.SeriesStartDate = facilityClass.SeriesStartDate;
|
||||
existing.SeriesEndDate = facilityClass.SeriesEndDate;
|
||||
existing.Capacity = facilityClass.Capacity;
|
||||
existing.IsUnlimitedCapacity = facilityClass.IsUnlimitedCapacity;
|
||||
existing.IsActive = facilityClass.IsActive;
|
||||
existing.OccurrencesGeneratedThrough = facilityClass.OccurrencesGeneratedThrough;
|
||||
|
||||
return existing;
|
||||
}
|
||||
|
||||
public Task<List<FacilityClass>> GetClassesNeedingGenerationAsync(Guid clientId, DateTime horizon)
|
||||
=> _context.FacilityClasses
|
||||
.Where(fc => fc.FKClientId == clientId && fc.IsActive && fc.RecurrenceType != "Custom"
|
||||
&& fc.OccurrencesGeneratedThrough < horizon)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<HashSet<DateTime>> GetExistingOccurrenceStartTimesAsync(Guid facilityClassId, DateTime from, DateTime to)
|
||||
{
|
||||
var times = await _context.FacilitySessions
|
||||
.Where(s => s.FKFacilityClassId == facilityClassId && s.StartTime >= from && s.StartTime < to)
|
||||
.Select(s => s.StartTime)
|
||||
.ToListAsync();
|
||||
return times.ToHashSet();
|
||||
}
|
||||
|
||||
public async Task AddOccurrencesAsync(IEnumerable<FacilitySession> occurrences)
|
||||
{
|
||||
var list = occurrences.ToList();
|
||||
foreach (var occurrence in list)
|
||||
{
|
||||
occurrence.FacilitySessionId = Guid.NewGuid();
|
||||
occurrence.CreatedAt = DateTime.UtcNow;
|
||||
occurrence.IsCancelled = false;
|
||||
}
|
||||
await _context.FacilitySessions.AddRangeAsync(list);
|
||||
}
|
||||
|
||||
public Task<List<FacilitySession>> GetOccurrencesForClassAsync(Guid facilityClassId, bool includeCancelled)
|
||||
{
|
||||
var query = _context.FacilitySessions.Where(s => s.FKFacilityClassId == facilityClassId);
|
||||
if (!includeCancelled)
|
||||
query = query.Where(s => !s.IsCancelled);
|
||||
|
||||
return query.OrderByDescending(s => s.StartTime).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<int> DeleteFutureUnbookedOccurrencesAsync(Guid facilityClassId, DateTime nowUtc)
|
||||
{
|
||||
var candidates = await _context.FacilitySessions
|
||||
.Where(s => s.FKFacilityClassId == facilityClassId && s.StartTime > nowUtc)
|
||||
.Where(s => !_context.Bookings.Any(b => b.FKFacilitySessionId == s.FacilitySessionId))
|
||||
.ToListAsync();
|
||||
|
||||
_context.FacilitySessions.RemoveRange(candidates);
|
||||
return candidates.Count;
|
||||
}
|
||||
|
||||
public async Task LinkPlanToClassAsync(Guid customerPlanId, Guid facilityClassId)
|
||||
{
|
||||
_context.CustomerPlanClasses.Add(new CustomerPlanClass
|
||||
{
|
||||
CustomerPlanClassId = Guid.NewGuid(),
|
||||
FKCustomerPlanId = customerPlanId,
|
||||
FKFacilityClassId = facilityClassId
|
||||
});
|
||||
}
|
||||
|
||||
public Task<List<Booking>> GetSchedulingConflictsAsync(Guid clientId)
|
||||
{
|
||||
return _context.Bookings
|
||||
.Include(b => b.Facility)
|
||||
.Where(b => b.FKClientId == clientId && b.FKFacilitySessionId == null && b.Status == "Confirmed")
|
||||
.Where(b => _context.FacilitySessions.Any(s =>
|
||||
s.FKFacilityId == b.FKFacilityId && s.FKFacilityClassId != null && !s.IsCancelled &&
|
||||
s.StartTime < b.EndTime && s.EndTime > b.StartTime))
|
||||
.ToListAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,8 @@ namespace Fitness_core_BE.Repos
|
||||
?? throw new KeyNotFoundException("Facility not found");
|
||||
|
||||
existing.Name = facility.Name;
|
||||
existing.BookingMode = facility.BookingMode;
|
||||
existing.SupportsClasses = facility.SupportsClasses;
|
||||
existing.SupportsBooking = facility.SupportsBooking;
|
||||
existing.Description = facility.Description;
|
||||
existing.DefaultCapacity = facility.DefaultCapacity;
|
||||
existing.NumberOfUnits = facility.NumberOfUnits;
|
||||
@@ -76,12 +77,15 @@ namespace Fitness_core_BE.Repos
|
||||
.Include(s => s.Facility)
|
||||
.FirstOrDefaultAsync(s => s.FacilitySessionId == facilitySessionId);
|
||||
|
||||
public async Task<List<FacilitySession>> GetSessions(Guid clientId, Guid? facilityId, DateTime fromUtc, DateTime toUtc)
|
||||
public async Task<List<FacilitySession>> GetSessions(Guid clientId, Guid? facilityId, DateTime fromUtc, DateTime toUtc, bool includeCancelled = false)
|
||||
{
|
||||
var query = _context.FacilitySessions
|
||||
.Include(s => s.Facility)
|
||||
.Where(s => s.FKClientId == clientId && s.StartTime >= fromUtc && s.StartTime <= toUtc && !s.IsCancelled);
|
||||
.Include(s => s.FacilityClass)
|
||||
.Where(s => s.FKClientId == clientId && s.StartTime >= fromUtc && s.StartTime <= toUtc);
|
||||
|
||||
if (!includeCancelled)
|
||||
query = query.Where(s => !s.IsCancelled);
|
||||
if (facilityId.HasValue)
|
||||
query = query.Where(s => s.FKFacilityId == facilityId.Value);
|
||||
|
||||
@@ -91,13 +95,24 @@ namespace Fitness_core_BE.Repos
|
||||
public Task<int> GetActiveBookingCount(Guid facilitySessionId)
|
||||
=> _context.Bookings.CountAsync(b => b.FKFacilitySessionId == facilitySessionId && b.Status != "Cancelled");
|
||||
|
||||
public async Task<FacilitySession?> CancelFacilitySession(Guid facilitySessionId, Guid clientId)
|
||||
/// <summary>True interval overlap (StartTime < end && EndTime > start), not a
|
||||
/// "StartTime falls inside the window" filter like GetSessions -- a class that started
|
||||
/// before the window and is still running must still count as occupying it.</summary>
|
||||
public Task<List<FacilitySession>> GetOverlappingActiveSessionsAsync(Guid facilityId, DateTime startUtc, DateTime endUtc)
|
||||
=> _context.FacilitySessions
|
||||
.Where(s => s.FKFacilityId == facilityId && !s.IsCancelled && s.StartTime < endUtc && s.EndTime > startUtc)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<FacilitySession?> MarkFacilitySessionNotHeldAsync(Guid facilitySessionId, Guid clientId, string? reason)
|
||||
{
|
||||
var session = await _context.FacilitySessions
|
||||
.Include(s => s.Bookings)
|
||||
.FirstOrDefaultAsync(s => s.FacilitySessionId == facilitySessionId && s.FKClientId == clientId);
|
||||
if (session == null) return null;
|
||||
|
||||
session.IsCancelled = true;
|
||||
session.NotHeldReason = reason;
|
||||
session.NotHeldAt = DateTime.UtcNow;
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -188,13 +203,13 @@ namespace Fitness_core_BE.Repos
|
||||
.ToDictionary(g => g.Key, g => g.Select(pf => pf.FKFacilityId).ToList());
|
||||
}
|
||||
|
||||
// --- AdHoc booking support (new) ---
|
||||
// --- WalkIn booking support (new) ---
|
||||
|
||||
public Task<int> GetOverlappingAdhocBookingCountAsync(Guid facilityId, DateTime startTime, DateTime endTime, Guid? excludeBookingId = null)
|
||||
public Task<int> GetOverlappingWalkInBookingCountAsync(Guid facilityId, DateTime startTime, DateTime endTime, Guid? excludeBookingId = null)
|
||||
{
|
||||
var query = _context.Bookings.Where(b =>
|
||||
b.FKFacilityId == facilityId &&
|
||||
b.FKFacilitySessionId == null && // AdHoc bookings only
|
||||
b.FKFacilitySessionId == null && // WalkIn bookings only
|
||||
b.Status != "Cancelled" && b.Status != "NoShow" && b.Status != "Completed" &&
|
||||
b.StartTime < endTime && b.EndTime > startTime);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user