155 lines
7.4 KiB
C#
155 lines
7.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 = ResolveSriLankaTimeZone();
|
|
|
|
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.");
|
|
}
|
|
}
|
|
}
|
|
|
|
private static TimeZoneInfo ResolveSriLankaTimeZone()
|
|
{
|
|
try
|
|
{
|
|
return TimeZoneInfo.FindSystemTimeZoneById("Sri Lanka Standard Time"); // Windows ID
|
|
}
|
|
catch (TimeZoneNotFoundException)
|
|
{
|
|
try
|
|
{
|
|
return TimeZoneInfo.FindSystemTimeZoneById("Asia/Colombo"); // IANA ID (Linux/macOS)
|
|
}
|
|
catch (TimeZoneNotFoundException)
|
|
{
|
|
// Neither ID resolved (e.g. no tzdata on the host) -- Sri Lanka has kept a
|
|
// fixed UTC+5:30 offset with no DST since 2006, so a custom fixed-offset
|
|
// zone is a safe fallback rather than failing the whole job.
|
|
return TimeZoneInfo.CreateCustomTimeZone(
|
|
"Sri Lanka (fixed +05:30)", TimeSpan.FromMinutes(330), "Sri Lanka Time", "Sri Lanka Time");
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|