Files
Core_Be/Repos/FacilityRepository.cs
T
HarithaRandunu 5d711bd13e 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>
2026-10-09 14:26:59 +05:30

236 lines
10 KiB
C#

using Fitness_core_BE.Interfaces;
using Fitness_core_BE.Models;
using Microsoft.EntityFrameworkCore;
namespace Fitness_core_BE.Repos
{
public class FacilityRepository : IFacilityRepository
{
private readonly TenantDbContext _context;
public FacilityRepository(TenantDbContext context)
{
_context = context;
}
public async Task<List<Facility>> GetAllFacilities(Guid clientId, bool includeInactive = false)
{
var query = _context.Facilities.Where(f => f.FKClientId == clientId);
if (!includeInactive)
query = query.Where(f => f.IsActive);
return await query.OrderBy(f => f.Name).ToListAsync();
}
public Task<Facility?> GetFacilityById(Guid facilityId)
=> _context.Facilities.FirstOrDefaultAsync(f => f.FacilityId == facilityId);
public async Task<Facility> CreateFacility(Facility facility)
{
facility.FacilityId = Guid.NewGuid();
facility.CreatedAt = DateTime.UtcNow;
facility.IsActive = true;
_context.Facilities.Add(facility);
return facility;
}
public async Task<Facility> UpdateFacility(Facility facility)
{
var existing = await _context.Facilities.FindAsync(facility.FacilityId)
?? throw new KeyNotFoundException("Facility not found");
existing.Name = facility.Name;
existing.SupportsClasses = facility.SupportsClasses;
existing.SupportsBooking = facility.SupportsBooking;
existing.Description = facility.Description;
existing.DefaultCapacity = facility.DefaultCapacity;
existing.NumberOfUnits = facility.NumberOfUnits;
existing.PricePerHour = facility.PricePerHour;
existing.IsActive = facility.IsActive;
return existing;
}
public async Task<Facility?> SetFacilityActive(Guid facilityId, Guid clientId, bool isActive)
{
var facility = await _context.Facilities
.FirstOrDefaultAsync(f => f.FacilityId == facilityId && f.FKClientId == clientId);
if (facility == null) return null;
facility.IsActive = isActive;
return facility;
}
public async Task<FacilitySession> CreateFacilitySession(FacilitySession session)
{
session.FacilitySessionId = Guid.NewGuid();
session.CreatedAt = DateTime.UtcNow;
session.IsCancelled = false;
_context.FacilitySessions.Add(session);
return session;
}
public Task<FacilitySession?> GetFacilitySessionById(Guid facilitySessionId)
=> _context.FacilitySessions
.Include(s => s.Facility)
.FirstOrDefaultAsync(s => s.FacilitySessionId == facilitySessionId);
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)
.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);
return await query.OrderBy(s => s.StartTime).ToListAsync();
}
public Task<int> GetActiveBookingCount(Guid facilitySessionId)
=> _context.Bookings.CountAsync(b => b.FKFacilitySessionId == facilitySessionId && b.Status != "Cancelled");
/// <summary>True interval overlap (StartTime &lt; end &amp;&amp; EndTime &gt; 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;
}
// --- Device binding (absorbed from PlaceRepo) ---
public Task<AccessDevice?> GetDeviceByIdForClientAsync(Guid deviceId, Guid clientId)
=> _context.AccessDevices
.FirstOrDefaultAsync(d => d.DeviceId == deviceId && d.FKClientId == clientId);
public async Task<Dictionary<Guid, string>> GetFacilityNamesByIdsAsync(List<Guid> facilityIds)
{
return await _context.Facilities
.Where(f => facilityIds.Contains(f.FacilityId))
.ToDictionaryAsync(f => f.FacilityId, f => f.Name);
}
public async Task<Dictionary<Guid, AccessDevice>> GetDevicesByFacilityIdsAsync(List<Guid> facilityIds)
{
var devices = await _context.AccessDevices
.Where(d => d.FKFacilityId != null && facilityIds.Contains(d.FKFacilityId.Value))
.ToListAsync();
return devices.ToDictionary(d => d.FKFacilityId!.Value, d => d);
}
public Task<bool> IsDeviceAssignedToAnotherFacilityAsync(Guid deviceId, Guid facilityId)
=> _context.AccessDevices
.AnyAsync(d => d.DeviceId == deviceId && d.FKFacilityId != null && d.FKFacilityId != facilityId);
public async Task AssignDeviceAsync(Guid facilityId, Guid deviceId)
{
// A device can only sit in one facility at a time -- clear anywhere else it's
// currently assigned before pointing it at this facility.
var previouslyAssigned = await _context.AccessDevices
.Where(d => d.FKFacilityId == facilityId && d.DeviceId != deviceId)
.ToListAsync();
foreach (var device in previouslyAssigned)
device.FKFacilityId = null;
var target = await _context.AccessDevices.FindAsync(deviceId)
?? throw new KeyNotFoundException("Device not found");
target.FKFacilityId = facilityId;
}
public async Task UnassignDeviceAsync(Guid facilityId)
{
var devices = await _context.AccessDevices
.Where(d => d.FKFacilityId == facilityId)
.ToListAsync();
foreach (var device in devices)
device.FKFacilityId = null;
}
// --- CustomerPlan access-scoping (absorbed from PlaceRepo) ---
public async Task SetPlanFacilitiesAsync(Guid customerPlanId, List<Guid> facilityIds)
{
var existing = await _context.CustomerPlanFacilities
.Where(pf => pf.FKCustomerPlanId == customerPlanId)
.ToListAsync();
_context.CustomerPlanFacilities.RemoveRange(existing);
foreach (var facilityId in facilityIds.Distinct())
{
_context.CustomerPlanFacilities.Add(new CustomerPlanFacility
{
CustomerPlanFacilityId = Guid.NewGuid(),
FKCustomerPlanId = customerPlanId,
FKFacilityId = facilityId
});
}
}
public Task<List<Guid>> GetFacilityIdsForPlanAsync(Guid customerPlanId)
=> _context.CustomerPlanFacilities
.Where(pf => pf.FKCustomerPlanId == customerPlanId)
.Select(pf => pf.FKFacilityId)
.ToListAsync();
public async Task<Dictionary<Guid, List<Guid>>> GetFacilityIdsByPlanIdsAsync(List<Guid> customerPlanIds)
{
var rows = await _context.CustomerPlanFacilities
.Where(pf => customerPlanIds.Contains(pf.FKCustomerPlanId))
.ToListAsync();
return rows
.GroupBy(pf => pf.FKCustomerPlanId)
.ToDictionary(g => g.Key, g => g.Select(pf => pf.FKFacilityId).ToList());
}
// --- WalkIn booking support (new) ---
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 && // WalkIn bookings only
b.Status != "Cancelled" && b.Status != "NoShow" && b.Status != "Completed" &&
b.StartTime < endTime && b.EndTime > startTime);
if (excludeBookingId.HasValue)
query = query.Where(b => b.BookingId != excludeBookingId.Value);
return query.CountAsync();
}
public async Task LockFacilityForUpdateAsync(Guid facilityId)
{
// FromSqlInterpolated (not ExecuteSqlInterpolatedAsync, which is for non-query DML)
// is the correct EF Core idiom for a locking SELECT -- it runs through the same ADO
// connection/transaction as the caller's already-open _uow, so the row lock is held
// until that transaction commits/rolls back. AsNoTracking avoids clashing with any
// already-tracked Facility instance in this same context/request.
await _context.Facilities
.FromSqlInterpolated($"SELECT * FROM Facilities WHERE FacilityId = {facilityId} FOR UPDATE")
.AsNoTracking()
.ToListAsync();
}
}
}