5d711bd13e
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>
287 lines
13 KiB
C#
287 lines
13 KiB
C#
using Fitness_core_BE.Interfaces;
|
|
using Fitness_core_BE.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Fitness_core_BE.Repos
|
|
{
|
|
public class CustomerSubscriptionRepository : ICustomerSubscriptionRepository
|
|
{
|
|
private readonly TenantDbContext _context;
|
|
private readonly CentralDbContext _central;
|
|
|
|
public CustomerSubscriptionRepository(TenantDbContext context, CentralDbContext central)
|
|
{
|
|
_context = context;
|
|
_central = central;
|
|
}
|
|
|
|
public async Task AddCustomerSubscriptionAsync(
|
|
CustomerSubscription subscription,
|
|
CustomerSubItem initialSubItem,
|
|
SubscriptionMember primaryMember,
|
|
IReadOnlyCollection<SubscriptionInstallment> installments,
|
|
CancellationToken ct = default)
|
|
{
|
|
await _context.CustomerSubscriptions.AddAsync(subscription, ct);
|
|
await _context.CustomerSubItems.AddAsync(initialSubItem, ct);
|
|
await _context.SubscriptionMembers.AddAsync(primaryMember, ct);
|
|
await _context.SubscriptionInstallments.AddRangeAsync(installments, ct);
|
|
}
|
|
|
|
public async Task<CustomerPlan?> GetPlanByIdAsync(
|
|
Guid customerPlanId,
|
|
CancellationToken ct = default)
|
|
{
|
|
return await _context.CustomerPlans.FindAsync(
|
|
new object[] { customerPlanId }, ct);
|
|
}
|
|
|
|
public Task<bool> IsActiveCustomerAsync(
|
|
Guid customerId,
|
|
CancellationToken ct = default)
|
|
{
|
|
return _central.Customer.AnyAsync(
|
|
customer => customer.CusId == customerId && customer.IsActive, ct);
|
|
}
|
|
|
|
public Task<List<CustomerSubItem>> GetSubItemsAsync(
|
|
Guid subscriptionId,
|
|
bool activeOnly,
|
|
bool newestFirst,
|
|
CancellationToken ct = default)
|
|
{
|
|
var query = _context.CustomerSubItems
|
|
.AsNoTracking()
|
|
.Where(item => item.FKCustomerSubscriptionId == subscriptionId);
|
|
|
|
if (activeOnly)
|
|
query = query.Where(item => item.IsActive);
|
|
|
|
query = newestFirst
|
|
? query.OrderByDescending(item => item.CreatedAt)
|
|
: query.OrderBy(item => item.CreatedAt);
|
|
|
|
return query.ToListAsync(ct);
|
|
}
|
|
|
|
public async Task AddSubItemAsync(
|
|
CustomerSubItem subItem,
|
|
CancellationToken ct = default)
|
|
{
|
|
await _context.CustomerSubItems.AddAsync(subItem, ct);
|
|
}
|
|
|
|
public Task<CustomerInvoice?> GetLatestInvoiceAsync(
|
|
Guid subscriptionId,
|
|
CancellationToken ct = default)
|
|
{
|
|
// IsActive filter: once an unapproved renewal invoice exists for this subscription,
|
|
// "latest" must still resolve to the real, still-collectible prior invoice -- not the
|
|
// pending-approval one. Defaults true for every other invoice (no-op elsewhere).
|
|
// RolledOver is excluded too: it's superseded by whatever invoice carried its balance
|
|
// forward, so it's never "the current invoice" for display/payment purposes.
|
|
return _context.CustomerInvoices
|
|
.AsNoTracking()
|
|
.Where(invoice =>
|
|
invoice.FKCustomerSubscriptionId == subscriptionId &&
|
|
invoice.Status != "Cancelled" &&
|
|
invoice.Status != "RolledOver" &&
|
|
invoice.IsActive)
|
|
.OrderByDescending(invoice => invoice.CustomerInvoiceDate)
|
|
.FirstOrDefaultAsync(ct);
|
|
}
|
|
|
|
public async Task<decimal> GetApprovedPaymentTotalAsync(
|
|
Guid invoiceId,
|
|
CancellationToken ct = default)
|
|
{
|
|
return await _context.PaymentTransactions
|
|
.AsNoTracking()
|
|
.Where(payment =>
|
|
payment.FK_CustomerInvoiceId == invoiceId &&
|
|
payment.IsApproved == true &&
|
|
payment.IsActive == true)
|
|
.Select(payment => (decimal?)payment.PayAmount)
|
|
.SumAsync(ct) ?? 0m;
|
|
}
|
|
|
|
public Task<CustomerCards?> GetCardByIdAsync(
|
|
Guid cardId,
|
|
CancellationToken ct = default)
|
|
{
|
|
return _context.CustomerCards
|
|
.AsNoTracking()
|
|
.FirstOrDefaultAsync(card => card.JobId == cardId, ct);
|
|
}
|
|
|
|
public async Task<CustomerSubscription?> GetCustomerSubscriptionById(Guid subscriptionId)
|
|
{
|
|
return await _context.CustomerSubscriptions
|
|
.Include(s => s.TenantCustomerLink)
|
|
.Include(s => s.CustomerPlan)
|
|
.Include(s => s.SubscriptionMembers)
|
|
.ThenInclude(m => m.TenantCustomerLink)
|
|
.Include(s => s.SubscriptionInstallments)
|
|
.FirstOrDefaultAsync(s => s.SubscriptionId == subscriptionId);
|
|
}
|
|
|
|
public async Task<List<CustomerSubscription>> GetCustomerSubscriptionsByCustomerId(Guid customerId)
|
|
{
|
|
return await _context.CustomerSubscriptions
|
|
.Include(s => s.CustomerPlan)
|
|
.Where(s => s.FKCustomerId == customerId)
|
|
.OrderByDescending(s => s.CreatedAt)
|
|
.ToListAsync();
|
|
}
|
|
|
|
// 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. 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 &&
|
|
GymAccessPlans().Any(p => p.CustomerPlanId == m.Subscription.FKCustomerPlanId), ct);
|
|
}
|
|
|
|
// ---------- Group membership ----------
|
|
|
|
public async Task<SubscriptionMember> AddSubscriptionMemberAsync(SubscriptionMember member)
|
|
{
|
|
member.SubscriptionMemberId = Guid.NewGuid();
|
|
member.JoinedAt = DateTime.UtcNow;
|
|
member.IsActive = true;
|
|
_context.SubscriptionMembers.Add(member);
|
|
|
|
return member;
|
|
}
|
|
|
|
public async Task<int> GetActiveMemberCountAsync(Guid subscriptionId)
|
|
{
|
|
// Unassigned members still hold their row (so they stay listed and can be put
|
|
// back), but they aren't using the plan -- so they don't occupy a MemberLimit slot.
|
|
return await _context.SubscriptionMembers
|
|
.CountAsync(m => m.FKSubscriptionId == subscriptionId && m.IsActive && m.IsPlanAssigned);
|
|
}
|
|
|
|
public async Task<SubscriptionMember?> GetSubscriptionMemberAsync(Guid subscriptionMemberId)
|
|
{
|
|
return await _context.SubscriptionMembers
|
|
.Include(m => m.Subscription)
|
|
.ThenInclude(s => s.CustomerPlan)
|
|
.FirstOrDefaultAsync(m => m.SubscriptionMemberId == subscriptionMemberId);
|
|
}
|
|
|
|
public async Task<SubscriptionMember?> GetActiveSubscriptionMemberByCustomerAsync(Guid subscriptionId, Guid customerId)
|
|
{
|
|
return await _context.SubscriptionMembers
|
|
.FirstOrDefaultAsync(m => m.FKSubscriptionId == subscriptionId && m.FKCustomerId == customerId && m.IsActive);
|
|
}
|
|
|
|
/// <summary>Subscriptions where the customer is an active member (primary OR group secondary).</summary>
|
|
public async Task<List<CustomerSubscription>> GetSubscriptionsForCustomerAsync(Guid customerId)
|
|
{
|
|
return await _context.SubscriptionMembers
|
|
.AsNoTracking()
|
|
.Where(m => m.FKCustomerId == customerId && m.IsActive && m.Subscription.IsActive)
|
|
.Include(m => m.Subscription).ThenInclude(s => s.CustomerPlan)
|
|
.Include(m => m.Subscription).ThenInclude(s => s.SubscriptionMembers).ThenInclude(sm => sm.TenantCustomerLink)
|
|
.Include(m => m.Subscription).ThenInclude(s => s.SubscriptionInstallments)
|
|
.Select(m => m.Subscription)
|
|
.OrderByDescending(s => s.OnboardDate)
|
|
.ToListAsync();
|
|
}
|
|
|
|
public async Task<List<SubscriptionInstallment>> GetInstallmentsAsync(Guid subscriptionId)
|
|
{
|
|
return await _context.SubscriptionInstallments
|
|
.Where(i => i.FKSubscriptionId == subscriptionId && i.IsActive)
|
|
.OrderBy(i => i.InstallmentNo)
|
|
.ToListAsync();
|
|
}
|
|
|
|
public async Task AdvanceRenewalDateAsync(Guid subscriptionId, DateTime newRenewalDate, CancellationToken ct = default)
|
|
{
|
|
var subscription = await _context.CustomerSubscriptions
|
|
.FirstOrDefaultAsync(s => s.SubscriptionId == subscriptionId, ct);
|
|
if (subscription == null)
|
|
return;
|
|
|
|
subscription.RenewalDate = newRenewalDate;
|
|
}
|
|
|
|
public async Task DeactivatePriorInstallmentsAsync(Guid subscriptionId, CancellationToken ct = default)
|
|
{
|
|
// Hard delete, not soft-deactivate: TenantDbContext has a unique index on
|
|
// (FKSubscriptionId, InstallmentNo), so a soft-deactivated row would still occupy
|
|
// its InstallmentNo and collide with the new cycle's schedule restarting at 1 on the
|
|
// same subscription. The payment record of truth is PaymentTransactions (linked to
|
|
// the invoice, not the installment), so this loses no financial history.
|
|
var installments = await _context.SubscriptionInstallments
|
|
.Where(i => i.FKSubscriptionId == subscriptionId)
|
|
.ToListAsync(ct);
|
|
_context.SubscriptionInstallments.RemoveRange(installments);
|
|
}
|
|
|
|
public async Task AddInstallmentsAsync(IReadOnlyCollection<SubscriptionInstallment> installments, CancellationToken ct = default)
|
|
{
|
|
await _context.SubscriptionInstallments.AddRangeAsync(installments, ct);
|
|
}
|
|
}
|
|
}
|