PlotDirector/PlotLine/Services/SubscriptionServices.cs

343 lines
17 KiB
C#

using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public interface ISubscriptionService
{
Task<UserSubscriptionDetail?> GetCurrentSubscriptionAsync(int userId);
Task<bool> HasPaidBillingRiskAsync(int userId);
Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId);
Task<IReadOnlyList<SubscriptionLevel>> GetActiveSubscriptionLevelsAsync();
Task<SubscriptionLimitResult> CanCreateBookAsync(int userId);
Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId);
Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId);
Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId);
Task<SubscriptionLimitResult> CanCreateCharactersAsync(int projectId, int userId, int additionalCount);
Task<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId);
Task<StorageUsage> GetStorageUsageAsync(int userId);
Task<SubscriptionUsageSummary> GetUsageSummaryAsync(int userId);
Task<StorageLimitResult> CanUploadFileAsync(int userId, long fileSizeBytes);
Task<EffectiveEntitlement> GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null);
Task<EntitlementDecision> CanUseFeatureAsync(int userId, SubscriptionFeature feature, DateTime? utcNow = null);
Task<BookSlotReservation> ReserveBookSlotsAsync(int userId, int requestedSlots = 1, DateTime? utcNow = null);
Task ReleaseBookSlotReservationAsync(Guid reservationId);
Task<EntitlementDecision> CanUseResourcesAsync(int userId, SubscriptionResourceRequest request, DateTime? utcNow = null);
}
public sealed class SubscriptionService(ISubscriptionRepository subscriptions, IUserFileRepository userFiles) : ISubscriptionService
{
private const int PracticalUnlimited = 999999;
public Task<UserSubscriptionDetail?> GetCurrentSubscriptionAsync(int userId) =>
subscriptions.GetCurrentSubscriptionAsync(userId);
public async Task<bool> HasPaidBillingRiskAsync(int userId)
{
var subscription = await subscriptions.GetCurrentSubscriptionAsync(userId);
return HasPaidBillingRisk(subscription, DateTime.UtcNow);
}
public Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId) =>
subscriptions.GetSubscriptionLevelAsync(subscriptionLevelId);
public Task<IReadOnlyList<SubscriptionLevel>> GetActiveSubscriptionLevelsAsync() =>
subscriptions.GetActiveSubscriptionLevelsAsync();
public async Task<SubscriptionLimitResult> CanCreateBookAsync(int userId)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
var currentUsage = await subscriptions.GetOwnedBookCountAsync(userId);
return Evaluate(subscription, currentUsage, subscription.MaxBooks, "books");
}
public async Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
var currentUsage = await subscriptions.GetChapterCountForBookAsync(bookId);
return Evaluate(subscription, currentUsage, subscription.MaxChaptersPerBook, "chapters per book");
}
public async Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
var currentUsage = await subscriptions.GetSceneCountForBookAsync(bookId);
return Evaluate(subscription, currentUsage, subscription.MaxScenesPerBook, "scenes per book");
}
public async Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId)
=> await CanCreateCharactersAsync(projectId, userId, 1);
public async Task<SubscriptionLimitResult> CanCreateCharactersAsync(int projectId, int userId, int additionalCount)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
var currentUsage = await subscriptions.GetCharacterCountForProjectAsync(projectId);
if (additionalCount <= 0 || subscription.MaxCharactersPerProject >= PracticalUnlimited
|| currentUsage + additionalCount <= subscription.MaxCharactersPerProject)
{
return SubscriptionLimitResult.AllowedResult(currentUsage, subscription.MaxCharactersPerProject);
}
return SubscriptionLimitResult.Blocked(currentUsage, subscription.MaxCharactersPerProject,
$"This operation would exceed the maximum number of characters allowed by your {subscription.DisplayName} subscription ({subscription.MaxCharactersPerProject:N0}). Upgrade your subscription to add more.");
}
public async Task<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
var currentUsage = await subscriptions.GetCollaboratorCountForOwnerAsync(userId);
return Evaluate(subscription, currentUsage, subscription.MaxCollaborators, "collaborators");
}
public async Task<StorageUsage> GetStorageUsageAsync(int userId)
{
var subscription = await GetRequiredEffectiveLevelAsync(userId);
return new StorageUsage
{
UsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId),
MaximumBytes = ToBytes(subscription.MaxStorageMB)
};
}
public async Task<SubscriptionUsageSummary> GetUsageSummaryAsync(int userId)
{
var entitlement = await GetEffectiveEntitlementAsync(userId);
var subscription = entitlement.EffectiveLevel
?? throw new SubscriptionLimitException(entitlement.Reason);
var usage = await subscriptions.GetUsageSummaryForOwnerAsync(userId);
usage.StorageUsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId);
usage.StorageMaximumBytes = ToBytes(subscription.MaxStorageMB);
return usage;
}
public async Task<StorageLimitResult> CanUploadFileAsync(int userId, long fileSizeBytes)
{
var usage = await GetStorageUsageAsync(userId);
if (usage.MaximumBytes >= ToBytes(PracticalUnlimited) || usage.UsedBytes + fileSizeBytes <= usage.MaximumBytes)
{
return StorageLimitResult.AllowedResult(usage.UsedBytes, usage.MaximumBytes);
}
return StorageLimitResult.Blocked(usage.UsedBytes, usage.MaximumBytes, fileSizeBytes);
}
public async Task<EffectiveEntitlement> GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null)
{
var now = utcNow ?? DateTime.UtcNow;
var subscription = await subscriptions.GetSubscriptionForEntitlementAsync(userId);
var activeOverride = await subscriptions.GetActiveOverrideAsync(userId, now);
if (activeOverride is not null)
{
var overrideLevel = await subscriptions.GetSubscriptionLevelAsync(activeOverride.SubscriptionLevelID);
if (overrideLevel is not null && overrideLevel.IsActive)
{
return new EffectiveEntitlement
{
UserID = userId,
UnderlyingSubscription = subscription,
EffectiveLevel = overrideLevel,
ActiveOverride = activeOverride,
State = EntitlementState.ActiveOverride,
EvaluatedAtUTC = now,
Reason = activeOverride.ExpiryDateUTC.HasValue
? $"Administrative {overrideLevel.DisplayName} access is active until {activeOverride.ExpiryDateUTC.Value:d MMMM yyyy}."
: $"Administrative {overrideLevel.DisplayName} access is active."
};
}
}
if (subscription is null)
{
return Inactive(userId, now, EntitlementState.MissingSubscription, "No subscription is assigned to your account.");
}
var isTrial = subscription.IsTrial
|| (!subscription.RequiresStripeSubscription && string.IsNullOrWhiteSpace(subscription.StripeSubscriptionId));
if (isTrial)
{
var expiry = subscription.TrialExpiryDateUTC ?? subscription.StartDateUTC.AddDays(30);
return new EffectiveEntitlement
{
UserID = userId,
UnderlyingSubscription = subscription,
EffectiveLevel = ToLevel(subscription),
State = subscription.StartDateUTC <= now && now < expiry && subscription.IsActive
? EntitlementState.ActiveTrial
: EntitlementState.ExpiredTrial,
EvaluatedAtUTC = now,
TrialStartDateUTC = subscription.StartDateUTC,
TrialExpiryDateUTC = expiry,
Reason = subscription.StartDateUTC <= now && now < expiry && subscription.IsActive
? $"Trial access is active until {expiry:d MMMM yyyy}."
: "Your trial has ended. Your existing books are still available to read. Upgrade your subscription to continue editing or create new books."
};
}
var status = (subscription.StripeStatus ?? string.Empty).Trim().ToLowerInvariant();
var periodEnded = subscription.CurrentPeriodEndUTC.HasValue && subscription.CurrentPeriodEndUTC.Value <= now;
var recordEnded = subscription.EndDateUTC.HasValue && subscription.EndDateUTC.Value <= now;
var providerInactive = status is "canceled" or "cancelled" or "incomplete_expired" or "ended" or "expired" or "inactive" or "unpaid";
var isActive = subscription.StartDateUTC <= now && subscription.IsActive && subscription.SubscriptionLevelIsActive && !recordEnded && !(periodEnded && providerInactive);
return new EffectiveEntitlement
{
UserID = userId,
UnderlyingSubscription = subscription,
EffectiveLevel = ToLevel(subscription),
State = isActive ? EntitlementState.ActivePaid : EntitlementState.InactiveSubscription,
EvaluatedAtUTC = now,
Reason = isActive ? $"The {subscription.DisplayName} subscription is active." : "Your subscription is inactive. Existing work remains available to read and export."
};
}
public async Task<EntitlementDecision> CanUseFeatureAsync(int userId, SubscriptionFeature feature, DateTime? utcNow = null)
{
var entitlement = await GetEffectiveEntitlementAsync(userId, utcNow);
return entitlement.IsActive
? new EntitlementDecision { Allowed = true, Code = "allowed", Entitlement = entitlement }
: new EntitlementDecision { Allowed = false, Code = entitlement.IsTrialExpired ? "trial_expired" : "subscription_inactive", Message = entitlement.Reason, Entitlement = entitlement };
}
public async Task<BookSlotReservation> ReserveBookSlotsAsync(int userId, int requestedSlots = 1, DateTime? utcNow = null)
{
if (requestedSlots <= 0)
{
return new BookSlotReservation { Allowed = true };
}
var decision = await CanUseFeatureAsync(userId, SubscriptionFeature.EditContent, utcNow);
if (!decision.Allowed)
{
return new BookSlotReservation { Allowed = false, Message = decision.Message };
}
return await subscriptions.TryReserveBookSlotsAsync(userId, requestedSlots, utcNow ?? DateTime.UtcNow);
}
public Task ReleaseBookSlotReservationAsync(Guid reservationId) => subscriptions.ReleaseBookSlotReservationAsync(reservationId);
public async Task<EntitlementDecision> CanUseResourcesAsync(int userId, SubscriptionResourceRequest request, DateTime? utcNow = null)
{
var entitlement = await GetEffectiveEntitlementAsync(userId, utcNow);
var level = entitlement.EffectiveLevel;
if (!entitlement.IsActive || level is null)
{
return Denied(entitlement, entitlement.IsTrialExpired ? "trial_expired" : "subscription_inactive", entitlement.Reason);
}
var booksUsed = await subscriptions.GetOwnedBookCountAsync(userId);
if (level.MaxBooks < PracticalUnlimited && booksUsed + request.AdditionalBooks > level.MaxBooks)
{
return Denied(entitlement, "book_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxBooks:N0} books.");
}
if (level.MaxChaptersPerBook < PracticalUnlimited && request.FinalChapterCounts.Any(count => count > level.MaxChaptersPerBook))
{
return Denied(entitlement, "chapter_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxChaptersPerBook:N0} chapters per book.");
}
if (level.MaxScenesPerBook < PracticalUnlimited && request.FinalSceneCounts.Any(count => count > level.MaxScenesPerBook))
{
return Denied(entitlement, "scene_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxScenesPerBook:N0} scenes per book.");
}
if (request.FinalCharacterCount.HasValue && level.MaxCharactersPerProject < PracticalUnlimited
&& request.FinalCharacterCount.Value > level.MaxCharactersPerProject)
{
return Denied(entitlement, "character_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxCharactersPerProject:N0} characters per project.");
}
return new EntitlementDecision { Allowed = true, Code = "allowed", Entitlement = entitlement };
}
private async Task<SubscriptionLevel> GetRequiredEffectiveLevelAsync(int userId)
{
var entitlement = await GetEffectiveEntitlementAsync(userId);
if (!entitlement.IsActive || entitlement.EffectiveLevel is null)
{
throw new SubscriptionLimitException(entitlement.Reason);
}
return entitlement.EffectiveLevel;
}
private static SubscriptionLimitResult Evaluate(SubscriptionLevel subscription, int currentUsage, int maximumAllowed, string limitName)
{
if (maximumAllowed >= PracticalUnlimited || currentUsage < maximumAllowed)
{
return SubscriptionLimitResult.AllowedResult(currentUsage, maximumAllowed);
}
return SubscriptionLimitResult.Blocked(
currentUsage,
maximumAllowed,
$"You have reached the maximum number of {limitName} allowed by your {subscription.DisplayName} subscription ({maximumAllowed:N0}). Upgrade your subscription to add more.");
}
private static EffectiveEntitlement Inactive(int userId, DateTime now, EntitlementState state, string reason) => new()
{
UserID = userId,
EvaluatedAtUTC = now,
State = state,
Reason = reason
};
private static EntitlementDecision Denied(EffectiveEntitlement entitlement, string code, string message) => new()
{
Allowed = false,
Code = code,
Message = message,
Entitlement = entitlement
};
private static SubscriptionLevel ToLevel(UserSubscriptionDetail source) => new()
{
SubscriptionLevelID = source.SubscriptionLevelID,
Name = source.Name,
DisplayName = source.DisplayName,
Description = source.Description,
MaxBooks = source.MaxBooks,
MaxChaptersPerBook = source.MaxChaptersPerBook,
MaxScenesPerBook = source.MaxScenesPerBook,
MaxCharactersPerProject = source.MaxCharactersPerProject,
MaxStorageMB = source.MaxStorageMB,
MaxCollaborators = source.MaxCollaborators,
IsActive = source.SubscriptionLevelIsActive,
SortOrder = source.SortOrder,
RequiresStripeSubscription = source.RequiresStripeSubscription,
MonthlyPricePence = source.MonthlyPricePence,
AnnualPricePence = source.AnnualPricePence,
CurrencyCode = source.CurrencyCode
};
private static long ToBytes(int megabytes) => megabytes * 1024L * 1024L;
internal static bool HasPaidBillingRisk(UserSubscriptionDetail? subscription, DateTime utcNow)
{
if (subscription is null || string.IsNullOrWhiteSpace(subscription.StripeSubscriptionId))
{
return false;
}
var stripeStatus = (subscription.StripeStatus ?? string.Empty).Trim().ToLowerInvariant();
if (stripeStatus is "canceled" or "cancelled" or "incomplete_expired")
{
return false;
}
if (subscription.CancelAtPeriodEnd
&& (!subscription.CurrentPeriodEndUTC.HasValue || subscription.CurrentPeriodEndUTC.Value > utcNow))
{
return true;
}
if (subscription.CurrentPeriodEndUTC.HasValue
&& subscription.CurrentPeriodEndUTC.Value <= utcNow
&& stripeStatus is "ended" or "expired" or "inactive")
{
return false;
}
return stripeStatus is "active" or "trialing" or "past_due" or "unpaid" or "incomplete" or "paused"
|| string.IsNullOrWhiteSpace(stripeStatus);
}
}
public sealed class SubscriptionLimitException(string message) : InvalidOperationException(message);