Files
Core_Be/Services/SubscriptionRenewalJob.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

132 lines
6.4 KiB
C#

using Fitness_core_BE.Infra.Tenancy;
namespace Fitness_core_BE.Services
{
/// <summary>
/// Daily sweep (01:00 Sri Lanka time) that checks every provisioned tenant schema for
/// CustomerSubscriptions due for renewal (RenewalDate on or before today) and creates an
/// unapproved (IsActive=false) renewal invoice for each -- see SubscriptionRenewalRunner for
/// the actual per-subscription algorithm (Paid vs. Pending/Partial carry-forward). Nothing on
/// the subscription itself changes here; approving/changing-plan/rejecting the invoice
/// (SubscriptionRenewalApprovalService) is what advances RenewalDate or replaces the plan.
/// Own, independent loop from OverdueLockJob's 6-hour cadence -- deliberately not merged with it.
///
/// Same as OverdueLockJob, this is a background service with no HttpContext, so it can't
/// rely on TenantConnectionResolver's per-request tenant resolution -- it loops every
/// provisioned tenant schema directly via TenantSchemaIterator instead.
/// </summary>
public class SubscriptionRenewalJob : BackgroundService
{
private const string JobName = "SubscriptionRenewalJob";
// 01:00 Sri Lanka local time (UTC+5:30, no DST observed since 2006) -- the gyms this
// runs for are all Sri Lanka-based, so the trigger point is anchored to local time
// rather than UTC. The actual RenewalDate/candidate comparisons inside
// SubscriptionRenewalRunner still use DateTime.UtcNow, unaffected by this -- only the
// wake-up point shifts.
private static readonly TimeSpan RunAtLocal = TimeSpan.FromHours(1);
private static readonly TimeZoneInfo SriLankaTimeZone = Helpers.TimeZoneHelper.SriLanka;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<SubscriptionRenewalJob> _logger;
public SubscriptionRenewalJob(IServiceScopeFactory scopeFactory, ILogger<SubscriptionRenewalJob> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var delay = ComputeDelayUntilNextRun(DateTime.UtcNow);
_logger.LogInformation(
"SubscriptionRenewalJob: next run scheduled at {NextRunUtc:u} UTC (in {Delay}).",
DateTime.UtcNow.Add(delay), delay);
try
{
await Task.Delay(delay, stoppingToken);
}
catch (TaskCanceledException)
{
// Shutting down.
break;
}
try
{
_logger.LogInformation("SubscriptionRenewalJob: daily run starting.");
await RunOnceAsync(stoppingToken);
_logger.LogInformation("SubscriptionRenewalJob: daily run finished.");
}
catch (Exception ex)
{
_logger.LogError(ex, "SubscriptionRenewalJob run failed.");
}
}
}
// Delay-then-run, not run-then-delay: a fixed daily time trigger shouldn't fire an extra
// run just because the app happened to restart. Internal + static so it's unit-testable
// without spinning up the whole hosted service.
internal static TimeSpan ComputeDelayUntilNextRun(DateTime nowUtc)
{
var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, SriLankaTimeZone);
var todayRunLocal = nowLocal.Date + RunAtLocal;
var nextRunLocal = nowLocal < todayRunLocal ? todayRunLocal : todayRunLocal.AddDays(1);
var nextRunUtc = TimeZoneInfo.ConvertTimeToUtc(
DateTime.SpecifyKind(nextRunLocal, DateTimeKind.Unspecified), SriLankaTimeZone);
return nextRunUtc - nowUtc;
}
private async Task RunOnceAsync(CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var iterator = scope.ServiceProvider.GetRequiredService<TenantSchemaIterator>();
var runner = scope.ServiceProvider.GetRequiredService<SubscriptionRenewalRunner>();
var history = scope.ServiceProvider.GetRequiredService<IJobRunHistory>();
var now = DateTime.UtcNow;
await foreach (var (clientId, schemaName) in iterator.GetProvisionedRegistrationsAsync(ct))
{
// Declared outside the try so the catch block can still use schemaCtx.Central to
// record the failure -- central is one fixed database regardless of tenant, so
// it's safe to reuse (or lazily open) here even though the schema-specific work failed.
TenantSchemaContext? schemaCtx = null;
try
{
schemaCtx = iterator.OpenSchema(clientId, schemaName);
var result = await runner.RunForSchemaAsync(schemaCtx, now, ct);
await history.RecordAsync(schemaCtx.Central, new JobRunRecord(
JobName, clientId, now,
result.Failed > 0 ? "PartialFailure" : "Success",
result.Renewed,
result.Failed > 0 ? string.Join("; ", result.Notes) : null), ct);
if (result.Renewed > 0 || result.Failed > 0)
{
_logger.LogInformation(
"SubscriptionRenewalJob: client {ClientId} ({Schema}) -- {Candidates} candidate(s), {Renewed} renewed, {Failed} failed.",
clientId, schemaName, result.Candidates, result.Renewed, result.Failed);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "SubscriptionRenewalJob failed for client {ClientId} schema {Schema}.", clientId, schemaName);
schemaCtx ??= iterator.OpenSchema(clientId, schemaName);
await history.RecordAsync(schemaCtx.Central, new JobRunRecord(JobName, clientId, now, "Failed", 0, ex.Message), ct);
}
finally
{
if (schemaCtx != null)
await schemaCtx.DisposeAsync();
}
}
}
}
}