PlotDirector/PlotLine.Tests/SubscriptionEntitlementTests.cs

305 lines
18 KiB
C#

using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
internal static class SubscriptionEntitlementTests
{
public static void EffectiveStateAndLimits()
{
var now = DateTime.UtcNow;
var subscription = Trial(now.AddDays(-10), now.AddSeconds(1));
SubscriptionOverride? activeOverride = null;
var ownedBooks = 1;
var levels = new Dictionary<int, SubscriptionLevel>
{
[1] = Level(1, "DraftDesk", "Draft Desk", 2, false),
[2] = Level(2, "WritingRoom", "Writing Room", 10, true),
[3] = Level(3, "StoryForge", "Story Forge", 30, true),
[4] = Level(4, "AuthorStudio", "Author Studio", 999999, true)
};
var repository = Proxy<ISubscriptionRepository>((method, args) => method switch
{
nameof(ISubscriptionRepository.GetCurrentSubscriptionAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)),
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks),
_ => DefaultTask(method)
});
var service = new SubscriptionService(repository, Proxy<IUserFileRepository>((method, _) => DefaultTask(method)));
var active = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(active.State == EntitlementState.ActiveTrial, "A trial immediately before expiry must remain active.");
Check(service.CanUseFeatureAsync(7, SubscriptionFeature.StoryIntelligence, now).GetAwaiter().GetResult().Allowed,
"An active trial must be able to use entitled features.");
var boundary = service.GetEffectiveEntitlementAsync(7, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult();
Check(boundary.State == EntitlementState.ExpiredTrial && boundary.IsReadOnly,
"The exact trial expiry boundary must be read-only.");
Check(!service.CanUseFeatureAsync(7, SubscriptionFeature.Import, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult().Allowed,
"An expired trial must not be able to import.");
subscription.TrialExpiryDateUTC = now.AddDays(30);
var extended = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(extended.State == EntitlementState.ActiveTrial, "A genuine application trial with a later stored expiry must be active.");
subscription.TrialExpiryDateUTC = null;
subscription.StartDateUTC = now.AddDays(-31);
Check(service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult().State == EntitlementState.ExpiredTrial,
"A malformed historical trial with no expiry must safely fall back to start plus 30 days.");
subscription.StartDateUTC = now.AddDays(-10);
subscription.TrialExpiryDateUTC = now.AddDays(20);
ownedBooks = 1;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Below the real Draft Desk book limit should be allowed.");
ownedBooks = 2;
Check(!service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Exactly at the book limit must block another book.");
ownedBooks = 1;
var oversizedImport = service.CanUseResourcesAsync(7, new SubscriptionResourceRequest
{
AdditionalBooks = 1,
FinalChapterCounts = [76],
FinalSceneCounts = [301],
FinalCharacterCount = 76
}, now).GetAwaiter().GetResult();
Check(!oversizedImport.Allowed && oversizedImport.Code == "chapter_limit",
"Bulk creation must enforce configured per-book limits before persistence.");
activeOverride = new SubscriptionOverride
{
SubscriptionOverrideID = 9,
UserID = 7,
SubscriptionLevelID = 3,
StartDateUTC = now.AddDays(-1),
ExpiryDateUTC = now.AddMonths(3),
Reason = "Complimentary review",
LevelDisplayName = "Story Forge"
};
var overridden = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(overridden.State == EntitlementState.ActiveOverride && overridden.EffectiveLevel?.Name == "StoryForge",
"An active temporary override must take precedence over the underlying trial.");
ownedBooks = 8;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "A higher-plan override must use that plan's resource limit.");
activeOverride = null;
var fallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(fallback.State == EntitlementState.ActiveTrial && fallback.EffectiveLevel?.Name == "DraftDesk",
"Removing or expiring an override must fall back to underlying access.");
subscription = Paid(now, "active");
var paid = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(paid.State == EntitlementState.ActivePaid, "An active paid subscription must be active.");
foreach (var (levelId, maximum) in new[] { (2, 10), (3, 30) })
{
var level = levels[levelId];
subscription = Paid(now, "active");
subscription.SubscriptionLevelID = levelId;
subscription.Name = level.Name;
subscription.DisplayName = level.DisplayName;
subscription.MaxBooks = maximum;
ownedBooks = maximum - 1;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, $"{level.DisplayName} must allow its final configured book slot.");
ownedBooks = maximum;
Check(!service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, $"{level.DisplayName} must enforce its configured {maximum}-book limit.");
}
subscription = Paid(now, "active");
subscription.SubscriptionLevelID = 4;
subscription.Name = "AuthorStudio";
subscription.DisplayName = "Author Studio";
subscription.MaxBooks = 999999;
ownedBooks = 999999;
Check(service.CanCreateBookAsync(7).GetAwaiter().GetResult().Allowed, "Author Studio's configured practical-unlimited value must remain unlimited.");
subscription.StripeStatus = "canceled";
subscription.CurrentPeriodEndUTC = now;
Check(service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult().State == EntitlementState.InactiveSubscription,
"A cancelled paid subscription at its period boundary must be read-only.");
}
public static void OverridePrecedenceAndPresentation()
{
var now = new DateTime(2026, 11, 2, 12, 0, 0, DateTimeKind.Utc);
var underlying = Trial(now.AddDays(-10), now.AddDays(20));
SubscriptionOverride? activeOverride = null;
var levels = new Dictionary<int, SubscriptionLevel>
{
[1] = Level(1, "DraftDesk", "Draft Desk", 2, false),
[4] = Level(4, "AuthorStudio", "Author Studio", 999999, true)
};
var repository = Proxy<ISubscriptionRepository>((method, args) => method switch
{
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(underlying),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)),
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
_ => DefaultTask(method)
});
var service = new SubscriptionService(repository, Proxy<IUserFileRepository>((method, _) => DefaultTask(method)));
var genuineTrial = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var genuineBanner = TrialVisibilityViewModel.FromEntitlement(genuineTrial, now);
Check(genuineTrial.State == EntitlementState.ActiveTrial && genuineBanner is { IsAdministrativeOverride: false },
"A genuine Draft Desk application trial must retain trial presentation when no override exists.");
Check(genuineBanner!.Description.Contains("30-day Draft Desk trial", StringComparison.Ordinal),
"Only a genuine application trial should use 30-day trial wording.");
activeOverride = Override(1, now.AddDays(-1), now.AddDays(60), "Draft Desk");
var draftTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var draftTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(draftTemporary, now);
Check(draftTemporary.EffectiveLevel?.Name == "DraftDesk" && draftTemporaryBanner is { IsAdministrativeOverride: true },
"A temporary Draft Desk override must be effective access, not an extension of the underlying trial.");
Check(!draftTemporaryBanner!.Description.Contains("trial", StringComparison.OrdinalIgnoreCase)
&& !draftTemporaryBanner.Description.Contains("30-day", StringComparison.OrdinalIgnoreCase),
"A temporary Draft Desk override must not be described as a trial.");
activeOverride = Override(1, now.AddDays(-1), null, "Draft Desk");
var draftIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(draftIndefinite.State == EntitlementState.ActiveOverride
&& TrialVisibilityViewModel.FromEntitlement(draftIndefinite, now) is null,
"An indefinite Draft Desk override must not show an expiry banner.");
activeOverride = Override(4, now.AddDays(-1), now.AddMonths(3), "Author Studio");
var authorTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var authorTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(authorTemporary, now);
Check(authorTemporary.EffectiveLevel?.Name == "AuthorStudio"
&& authorTemporaryBanner?.StatusLabel.Contains("Author Studio access until", StringComparison.Ordinal) == true,
"A temporary Author Studio override must show its effective access expiry.");
activeOverride = Override(4, now.AddDays(-1), null, "Author Studio");
underlying.TrialExpiryDateUTC = now.AddDays(-1);
var authorIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(authorIndefinite.State == EntitlementState.ActiveOverride && authorIndefinite.IsActive
&& TrialVisibilityViewModel.FromEntitlement(authorIndefinite, now) is null,
"An expired underlying trial must not compete with an indefinite higher override.");
underlying.TrialExpiryDateUTC = now.AddDays(20);
activeOverride = Override(4, now.AddDays(-10), now, "Author Studio");
var expiredFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(expiredFallback.State == EntitlementState.ActiveTrial && expiredFallback.EffectiveLevel?.Name == "DraftDesk",
"An expired override must automatically fall back to the underlying trial state.");
activeOverride = null;
var removedFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(removedFallback.State == EntitlementState.ActiveTrial && removedFallback.EffectiveLevel?.Name == "DraftDesk",
"A removed override must fall back to the underlying entitlement.");
underlying = Paid(now, "active");
activeOverride = Override(1, now.AddDays(-1), now.AddDays(30), "Draft Desk");
var paidWithOverride = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(paidWithOverride.State == EntitlementState.ActiveOverride && paidWithOverride.EffectiveLevel?.Name == "DraftDesk"
&& paidWithOverride.UnderlyingSubscription?.StripeStatus == "active",
"An administrative override must control effective access while preserving underlying paid billing state.");
var root = FindRepositoryRoot();
var projectService = File.ReadAllText(Path.Combine(root, "PlotLine", "Services", "CoreServices.cs"));
var projectView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Projects", "Index.cshtml"));
var adminView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Admin", "Subscriptions.cshtml"));
Check(projectService.Contains("FromEntitlement(entitlement", StringComparison.Ordinal)
&& !projectService.Contains("TrialVisibilityViewModel.FromSubscription", StringComparison.Ordinal),
"The Projects dashboard must build its banner from effective entitlement.");
Check(projectView.Contains("@trial.Description", StringComparison.Ordinal)
&& !projectView.Contains("Your 30-day trial expires", StringComparison.Ordinal),
"The Projects dashboard must not hard-code contradictory trial wording.");
Check(!adminView.Contains("Change trial expiry", StringComparison.Ordinal)
&& adminView.Contains("sole administrator control", StringComparison.Ordinal),
"The separate administrative trial-expiry control must be removed.");
Check(typeof(AdminController).GetMethod("ExtendTrial") is null
&& typeof(ISubscriptionRepository).GetMethod("ExtendTrialAsync") is null,
"The removed trial-expiry panel must not leave a callable application endpoint or repository mutation path.");
}
public static void EnforcementAndAdminSecurity()
{
var sql = File.ReadAllText(Path.Combine(FindRepositoryRoot(), "PlotLine", "Sql", "201_SubscriptionEntitlementEnforcement.sql"));
Check(sql.Contains("sp_getapplock", StringComparison.Ordinal) && sql.Contains("SubscriptionBookSlotReservation", StringComparison.Ordinal),
"Book creation concurrency must be protected by a database lock and reservation.");
Check(sql.Contains("SubscriptionAdministrationAudit", StringComparison.Ordinal), "Administrative subscription changes must be audited.");
var authorize = typeof(AdminController).GetCustomAttribute<AuthorizeAttribute>();
Check(authorize?.Policy == "AdminOnly", "Subscription administration must remain under the existing AdminOnly policy.");
Check(typeof(SubscriptionEnforcementFilter).GetInterfaces().Any(x => x.Name == "IAsyncActionFilter"),
"Unsafe requests must have a server-side entitlement filter.");
}
private static UserSubscriptionDetail Trial(DateTime start, DateTime expiry) => new()
{
UserID = 7, SubscriptionLevelID = 1, StartDateUTC = start, TrialExpiryDateUTC = expiry,
IsActive = true, IsTrial = true, SubscriptionLevelIsActive = true, Name = "DraftDesk", DisplayName = "Draft Desk",
MaxBooks = 2, MaxChaptersPerBook = 75, MaxScenesPerBook = 300, MaxCharactersPerProject = 75,
MaxStorageMB = 100, MaxCollaborators = 0, RequiresStripeSubscription = false
};
private static UserSubscriptionDetail Paid(DateTime now, string status) => new()
{
UserID = 7, SubscriptionLevelID = 3, StartDateUTC = now.AddMonths(-1), IsActive = true,
SubscriptionLevelIsActive = true, Name = "StoryForge", DisplayName = "Story Forge", RequiresStripeSubscription = true,
StripeSubscriptionId = "sub_test", StripeStatus = status, CurrentPeriodEndUTC = now.AddMonths(1),
MaxBooks = 30, MaxChaptersPerBook = 200, MaxScenesPerBook = 2000, MaxCharactersPerProject = 500,
MaxStorageMB = 5120, MaxCollaborators = 3
};
private static SubscriptionOverride Override(int levelId, DateTime start, DateTime? expiry, string displayName) => new()
{
SubscriptionOverrideID = 9,
UserID = 7,
SubscriptionLevelID = levelId,
StartDateUTC = start,
ExpiryDateUTC = expiry,
Reason = "Complimentary access",
LevelDisplayName = displayName
};
private static SubscriptionOverride? ActiveAt(SubscriptionOverride? candidate, DateTime utcNow)
=> candidate is not null
&& candidate.RevokedDateUTC is null
&& candidate.StartDateUTC <= utcNow
&& (!candidate.ExpiryDateUTC.HasValue || candidate.ExpiryDateUTC.Value > utcNow)
? candidate
: null;
private static SubscriptionLevel Level(int id, string name, string display, int maxBooks, bool stripe) => new()
{
SubscriptionLevelID = id, Name = name, DisplayName = display, MaxBooks = maxBooks,
MaxChaptersPerBook = id == 1 ? 75 : 200, MaxScenesPerBook = id == 1 ? 300 : 2000,
MaxCharactersPerProject = id == 1 ? 75 : 500, MaxStorageMB = id == 1 ? 100 : 5120,
MaxCollaborators = id == 1 ? 0 : 3, RequiresStripeSubscription = stripe, IsActive = true
};
private static object DefaultTask(string method) => method switch
{
nameof(IUserFileRepository.GetStorageUsageForOwnerAsync) => Task.FromResult(0L),
_ => Task.CompletedTask
};
private static T Proxy<T>(Func<string, object?[]?, object> handler) where T : class
{
var proxy = DispatchProxy.Create<T, EntitlementProxy>();
((EntitlementProxy)(object)proxy).Handler = handler;
return proxy;
}
private static string FindRepositoryRoot()
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "PlotLine.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
}
private static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
public class EntitlementProxy : DispatchProxy
{
public Func<string, object?[]?, object> Handler { get; set; } = null!;
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) => Handler(targetMethod!.Name, args);
}
}