From 45b6b2b537084fecc98d08a6c07a468b6eff2eeb Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 29 Oct 2026 15:30:10 +0000 Subject: [PATCH] Add Plot Lines workspace and subscription enforcement --- PlotLine.Tests/PlotLineWorkspaceTests.cs | 115 ++++ PlotLine.Tests/Program.cs | 5 + .../SubscriptionEntitlementTests.cs | 193 ++++++ PlotLine/Controllers/AdminController.cs | 92 +++ .../Controllers/ManageAccountController.cs | 12 +- .../PlotLineWorkspaceController.cs | 39 ++ PlotLine/Controllers/ScenesController.cs | 4 +- PlotLine/Controllers/TimelineController.cs | 1 - PlotLine/Data/PlotLineWorkspaceRepository.cs | 33 + PlotLine/Data/SubscriptionRepository.cs | 78 +++ PlotLine/Help/Articles/PlotLines/Index.md | 3 +- PlotLine/Help/Articles/PlotLines/Workspace.md | 42 ++ .../Articles/SceneInspector/Characters.md | 6 +- .../SceneInspector/Fields/CharacterRole.md | 2 +- .../Articles/Timeline/CharacterAppearances.md | 4 +- .../Timeline/Fields/DragCharacterRole.md | 2 +- PlotLine/Models/PlotLineWorkspaceModels.cs | 146 +++++ PlotLine/Models/SubscriptionModels.cs | 89 +++ PlotLine/Program.cs | 4 + PlotLine/Services/ApplicationNavigation.cs | 2 +- PlotLine/Services/ApplicationRibbon.cs | 4 +- PlotLine/Services/CoreServices.cs | 73 ++- PlotLine/Services/ImportServices.cs | 48 +- PlotLine/Services/PlotLineWorkspaceService.cs | 217 +++++++ PlotLine/Services/ProjectAccessFilter.cs | 1 + .../StoryIntelligenceOperationalServices.cs | 29 +- .../Services/SubscriptionEnforcementFilter.cs | 52 ++ PlotLine/Services/SubscriptionServices.cs | 207 ++++++- PlotLine/Services/ToolbarCommands.cs | 1 + PlotLine/Services/WordCompanionService.cs | 124 +++- ...201_SubscriptionEntitlementEnforcement.sql | 449 ++++++++++++++ PlotLine/Sql/204_PlotLineWorkspaceV1.sql | 294 +++++++++ .../EntitlementBannerViewComponent.cs | 20 + PlotLine/ViewModels/AuthViewModels.cs | 43 ++ PlotLine/ViewModels/CoreViewModels.cs | 2 +- .../ViewModels/PlotLineWorkspaceViewModels.cs | 95 +++ PlotLine/Views/Admin/Index.cshtml | 104 ++-- PlotLine/Views/Admin/Subscriptions.cshtml | 52 ++ PlotLine/Views/ManageAccount/Index.cshtml | 4 + .../Views/ManageAccount/Subscription.cshtml | 14 +- PlotLine/Views/PlotLineWorkspace/Index.cshtml | 177 ++++++ .../Views/PlotLineWorkspace/_Inspector.cshtml | 102 +++ .../PlotLineWorkspace/_Manuscript.cshtml | 2 + PlotLine/Views/Projects/Index.cshtml | 9 +- .../EntitlementBanner/Default.cshtml | 7 + .../_SceneCharactersEditor.cshtml | 8 + PlotLine/Views/Shared/_Layout.cshtml | 2 + PlotLine/Views/Timeline/Index.cshtml | 301 +-------- PlotLine/Views/Timeline/Settings.cshtml | 7 - PlotLine/wwwroot/css/plot-line-workspace.css | 63 ++ PlotLine/wwwroot/css/plotline-theme.css | 130 ++++ PlotLine/wwwroot/css/plotline-theme.min.css | 2 +- PlotLine/wwwroot/js/plot-line-workspace.js | 62 ++ PlotLine/wwwroot/js/site.js | 1 - docs/discovery-plot-line-data-audit.md | 522 ++++++++++++++++ ...ene-contribution-timeline-investigation.md | 582 ++++++++++++++++++ docs/subscription-entitlements.md | 56 ++ 57 files changed, 4272 insertions(+), 466 deletions(-) create mode 100644 PlotLine.Tests/PlotLineWorkspaceTests.cs create mode 100644 PlotLine.Tests/SubscriptionEntitlementTests.cs create mode 100644 PlotLine/Controllers/PlotLineWorkspaceController.cs create mode 100644 PlotLine/Data/PlotLineWorkspaceRepository.cs create mode 100644 PlotLine/Help/Articles/PlotLines/Workspace.md create mode 100644 PlotLine/Models/PlotLineWorkspaceModels.cs create mode 100644 PlotLine/Services/PlotLineWorkspaceService.cs create mode 100644 PlotLine/Services/SubscriptionEnforcementFilter.cs create mode 100644 PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql create mode 100644 PlotLine/Sql/204_PlotLineWorkspaceV1.sql create mode 100644 PlotLine/ViewComponents/EntitlementBannerViewComponent.cs create mode 100644 PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs create mode 100644 PlotLine/Views/Admin/Subscriptions.cshtml create mode 100644 PlotLine/Views/PlotLineWorkspace/Index.cshtml create mode 100644 PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml create mode 100644 PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml create mode 100644 PlotLine/Views/Shared/Components/EntitlementBanner/Default.cshtml create mode 100644 PlotLine/wwwroot/css/plot-line-workspace.css create mode 100644 PlotLine/wwwroot/js/plot-line-workspace.js create mode 100644 docs/discovery-plot-line-data-audit.md create mode 100644 docs/plot-lines-scene-contribution-timeline-investigation.md create mode 100644 docs/subscription-entitlements.md diff --git a/PlotLine.Tests/PlotLineWorkspaceTests.cs b/PlotLine.Tests/PlotLineWorkspaceTests.cs new file mode 100644 index 00000000..56a87354 --- /dev/null +++ b/PlotLine.Tests/PlotLineWorkspaceTests.cs @@ -0,0 +1,115 @@ +using PlotLine.Models; +using PlotLine.Services; + +internal static class PlotLineWorkspaceTests +{ + public static void FocusWeaveGapsAndSharedScenes() + { + var data = Fixture(); + var focus = PlotLineWorkspaceComposer.Compose(data, [1]); + Check(focus.Count == 2, "Focus mode should contain the selected line's two scenes."); + Check(focus[1].GapBefore == 4, "Dormancy should report the four intervening narrative scenes."); + Check(focus[1].ChapterGapBefore == 2, "Chapter dormancy should report whole intervening chapters."); + + var weave = PlotLineWorkspaceComposer.Compose(data, [1, 2]); + Check(weave.Count == 2, "Weave mode should render a shared scene once, not once per line."); + Check(weave[0].IsShared && weave[0].Memberships.Count == 2, "A shared scene should retain both line memberships."); + Check(weave[0].Memberships.SelectMany(x => x.Contributions).Any(x => + x.CanonicalTitle == "Canonical event" && x.CandidateTitle == "Supporting imported detail"), + "Imported supporting detail must enrich rather than replace the canonical event."); + } + + public static void ThreadFilteringAndInspectorContracts() + { + var data = Fixture(); + var filtered = PlotLineWorkspaceComposer.Compose(data, [1, 2], [12]); + Check(filtered.Count == 1 && filtered[0].SceneID == 101, "Thread filtering should retain only contributions from selected threads."); + Check(filtered[0].Memberships.Single().PlotLineID == 2, "Thread filtering must not leak another line's events."); + + var root = RepositoryRoot(); + var timeline = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Timeline/Index.cshtml")); + var settings = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Timeline/Settings.cshtml")); + var characterEditor = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml")); + var controller = File.ReadAllText(Path.Combine(root, "PlotLine/Controllers/ScenesController.cs")); + var sql = File.ReadAllText(Path.Combine(root, "PlotLine/Sql/204_PlotLineWorkspaceV1.sql")); + + Check(!timeline.Contains("character-lane-board", StringComparison.Ordinal), "Timeline must not render Character lane presentation."); + Check(!settings.Contains("ShowCharacterAppearances", StringComparison.Ordinal), "Timeline settings must not offer Character lanes."); + Check(characterEditor.Contains("Knowledge notes", StringComparison.Ordinal) && controller.Contains("KnowledgeNotes = row.KnowledgeNotes", StringComparison.Ordinal), + "Scene Inspector must expose and save character knowledge notes."); + Check(sql.Contains("cm.NarrativeCandidateID = te.SourceReferenceID AND cm.SceneID = te.SceneID", StringComparison.Ordinal), + "Imported event enrichment must require SourceReferenceID and SceneID."); + Check(sql.Contains("nc.Status = N'Pending'", StringComparison.Ordinal), "Suggestions must be restricted to pending candidates."); + } + + public static void GeneratedScale() + { + const int lineCount = 40; + const int sceneCount = 1200; + var lines = Enumerable.Range(1, lineCount).Select(id => new PlotLineWorkspaceLineRow + { + PlotLineID = id, + PlotLineName = $"Generated line {id}", + SortOrder = id + }).ToList(); + var contributions = new List(lineCount * 300); + for (var lineId = 1; lineId <= lineCount; lineId++) + { + for (var index = 0; index < 300; index++) + { + var sceneId = 10_000 + ((index * 7 + lineId * 13) % sceneCount); + contributions.Add(Contribution(lineId, lineId * 10, sceneId, sceneId - 9_999, 1 + (sceneId % 40), $"Event {lineId}-{index}", null)); + } + } + + var composed = PlotLineWorkspaceComposer.Compose(new PlotLineWorkspaceData { PlotLines = lines, Contributions = contributions }, lines.Select(x => x.PlotLineID).ToArray()); + Check(composed.Count <= sceneCount, "Large weave must still render each scene at most once."); + Check(composed.Select(x => x.SceneID).Distinct().Count() == composed.Count, "Large weave contains duplicate scene cards."); + Check(composed.Zip(composed.Skip(1), (left, right) => left.NarrativeOrder <= right.NarrativeOrder).All(x => x), "Large weave lost narrative ordering."); + } + + private static PlotLineWorkspaceData Fixture() => new() + { + PlotLines = + [ + new() { PlotLineID = 1, PlotLineName = "Line A", Colour = "#111111", SortOrder = 1 }, + new() { PlotLineID = 2, PlotLineName = "Line B", Colour = "#222222", SortOrder = 2 } + ], + Contributions = + [ + Contribution(1, 11, 101, 2, 1, "Canonical event", "Supporting imported detail"), + Contribution(2, 12, 101, 2, 1, "Other canonical event", null), + Contribution(1, 11, 102, 7, 4, "Later event", null) + ] + }; + + private static PlotLineWorkspaceContributionRow Contribution( + int lineId, int threadId, int sceneId, int order, decimal chapter, string canonicalTitle, string? candidateTitle) => new() + { + ThreadEventID = sceneId * 10 + lineId, + PlotLineID = lineId, + PlotThreadID = threadId, + SceneID = sceneId, + NarrativeOrder = order, + ChapterNumber = chapter, + ChapterTitle = $"Chapter {chapter}", + SceneNumber = order, + SceneTitle = $"Scene {sceneId}", + CanonicalTitle = canonicalTitle, + CandidateTitle = candidateTitle, + ThreadTitle = $"Thread {threadId}", + CanonicalRole = "Developed" + }; + + private static string RepositoryRoot() + { + 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); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 05b4d61d..0b705d41 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -25,6 +25,11 @@ if (args.Contains("--toolbar-browser-host")) var tests = new (string Name, Action Test)[] { + ("Subscription entitlement evaluates trials, paid access, overrides and real plan limits", SubscriptionEntitlementTests.EffectiveStateAndLimits), + ("Subscription enforcement is concurrent, audited and admin-authorised", SubscriptionEntitlementTests.EnforcementAndAdminSecurity), + ("Plot Lines Focus and Weave preserve gaps and shared-scene identity", PlotLineWorkspaceTests.FocusWeaveGapsAndSharedScenes), + ("Plot Lines thread, enrichment and Timeline inspector contracts hold", PlotLineWorkspaceTests.ThreadFilteringAndInspectorContracts), + ("Plot Lines composition remains bounded with a large generated weave", PlotLineWorkspaceTests.GeneratedScale), ("Exception review uses evidence, identity, consequence and directional conflicts", ExceptionReviewTests.DomainPolicy), ("Exception assessment preserves author decisions and scene history", ExceptionReviewTests.PreserveDecisionsAndObservations), ("Character card widths reflect displayed text without changing character data", CharacterCardLayoutTests.DisplayedContent), diff --git a/PlotLine.Tests/SubscriptionEntitlementTests.cs b/PlotLine.Tests/SubscriptionEntitlementTests.cs new file mode 100644 index 00000000..d66421c3 --- /dev/null +++ b/PlotLine.Tests/SubscriptionEntitlementTests.cs @@ -0,0 +1,193 @@ +using System.Reflection; +using Microsoft.AspNetCore.Authorization; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; + +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 + { + [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((method, args) => method switch + { + nameof(ISubscriptionRepository.GetCurrentSubscriptionAsync) => Task.FromResult(subscription), + nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult(subscription), + nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(activeOverride), + nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult(levels[(int)args![0]!]), + nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks), + _ => DefaultTask(method) + }); + var service = new SubscriptionService(repository, Proxy((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, "An administrator-extended trial must become 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 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(); + 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 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(Func handler) where T : class + { + var proxy = DispatchProxy.Create(); + ((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 Handler { get; set; } = null!; + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) => Handler(targetMethod!.Name, args); + } +} diff --git a/PlotLine/Controllers/AdminController.cs b/PlotLine/Controllers/AdminController.cs index cd18b65b..4eb21992 100644 --- a/PlotLine/Controllers/AdminController.cs +++ b/PlotLine/Controllers/AdminController.cs @@ -29,6 +29,9 @@ public sealed class AdminController( IBookRepository books, IOnboardingBuildRepository onboardingBuilds, ICoreImportBasicLocationService coreImportBasicLocations, + ISubscriptionRepository subscriptionRepository, + ISubscriptionService subscriptions, + IUserRepository users, IWebHostEnvironment environment, ILogger logger) : Controller { @@ -46,6 +49,95 @@ public sealed class AdminController( }); } + [HttpGet("subscriptions")] + public async Task Subscriptions(string? search, int? userId) + { + var model = new AdminSubscriptionsViewModel + { + Search = search, + Users = await subscriptionRepository.SearchUsersAsync(search), + Levels = await subscriptions.GetActiveSubscriptionLevelsAsync() + }; + + if (userId.HasValue) + { + model.SelectedUser = await users.GetByIdAsync(userId.Value); + if (model.SelectedUser is null) + { + return NotFound(); + } + + model.Entitlement = await subscriptions.GetEffectiveEntitlementAsync(userId.Value); + model.Usage = await subscriptionRepository.GetUsageSummaryForOwnerAsync(userId.Value); + } + + return View(model); + } + + [HttpPost("subscriptions/trial")] + [ValidateAntiForgeryToken] + public async Task ExtendTrial(AdminTrialExtensionForm form) + { + if (!ModelState.IsValid || currentUser.UserId is not int administratorUserId) + { + TempData["AdminError"] = "Enter a valid trial expiry date and reason."; + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + + try + { + await subscriptionRepository.ExtendTrialAsync(form.UserID, DateTime.SpecifyKind(form.TrialExpiryDateUTC, DateTimeKind.Utc), administratorUserId, form.Reason); + TempData["AdminMessage"] = "Trial expiry updated. The change was recorded in the subscription audit log."; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Administrator {AdministratorUserID} could not extend trial for user {UserID}.", administratorUserId, form.UserID); + TempData["AdminError"] = ex.Message; + } + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + + [HttpPost("subscriptions/override")] + [ValidateAntiForgeryToken] + public async Task SaveSubscriptionOverride(AdminSubscriptionOverrideForm form) + { + if (!ModelState.IsValid || currentUser.UserId is not int administratorUserId) + { + TempData["AdminError"] = "Enter a valid plan, date range and reason."; + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + + try + { + await subscriptionRepository.SaveOverrideAsync(form.UserID, form.SubscriptionLevelID, + DateTime.SpecifyKind(form.StartDateUTC, DateTimeKind.Utc), + form.ExpiryDateUTC.HasValue ? DateTime.SpecifyKind(form.ExpiryDateUTC.Value, DateTimeKind.Utc) : null, + form.Reason, administratorUserId); + TempData["AdminMessage"] = "Administrative access override saved without changing billing-provider state."; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Administrator {AdministratorUserID} could not override subscription for user {UserID}.", administratorUserId, form.UserID); + TempData["AdminError"] = ex.Message; + } + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + + [HttpPost("subscriptions/override/revoke")] + [ValidateAntiForgeryToken] + public async Task RevokeSubscriptionOverride(AdminOverrideRevokeForm form) + { + if (!ModelState.IsValid || currentUser.UserId is not int administratorUserId) + { + TempData["AdminError"] = "A reason is required to remove an override."; + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + + await subscriptionRepository.RevokeOverrideAsync(form.UserID, administratorUserId, form.Reason); + TempData["AdminMessage"] = "Administrative access override removed; underlying billing or trial access now applies."; + return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); + } + [HttpGet("theme-audit")] public IActionResult ThemeAudit() { diff --git a/PlotLine/Controllers/ManageAccountController.cs b/PlotLine/Controllers/ManageAccountController.cs index 5cecc9b0..12c00b31 100644 --- a/PlotLine/Controllers/ManageAccountController.cs +++ b/PlotLine/Controllers/ManageAccountController.cs @@ -30,13 +30,15 @@ public sealed class ManageAccountController( return RedirectToAction("Login", "Account"); } - var subscription = await subscriptions.GetCurrentSubscriptionAsync(user.UserID); + var entitlement = await subscriptions.GetEffectiveEntitlementAsync(user.UserID); + var subscription = entitlement.UnderlyingSubscription; return View(new ManageAccountViewModel { User = user, Subscription = subscription, Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow), - HasPaidBillingRisk = await subscriptions.HasPaidBillingRiskAsync(user.UserID) + HasPaidBillingRisk = await subscriptions.HasPaidBillingRiskAsync(user.UserID), + Entitlement = entitlement }); } @@ -101,14 +103,16 @@ public sealed class ManageAccountController( return RedirectToAction("Login", "Account"); } - var subscription = await subscriptions.GetCurrentSubscriptionAsync(user.UserID); + var entitlement = await subscriptions.GetEffectiveEntitlementAsync(user.UserID); + var subscription = entitlement.UnderlyingSubscription; return View(new ManageSubscriptionViewModel { User = user, CurrentSubscription = subscription, Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow), Usage = subscription is null ? null : await subscriptions.GetUsageSummaryAsync(user.UserID), - AvailableLevels = await subscriptions.GetActiveSubscriptionLevelsAsync() + AvailableLevels = await subscriptions.GetActiveSubscriptionLevelsAsync(), + Entitlement = entitlement }); } diff --git a/PlotLine/Controllers/PlotLineWorkspaceController.cs b/PlotLine/Controllers/PlotLineWorkspaceController.cs new file mode 100644 index 00000000..b5d44977 --- /dev/null +++ b/PlotLine/Controllers/PlotLineWorkspaceController.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Services; + +namespace PlotLine.Controllers; + +[Authorize] +public sealed class PlotLineWorkspaceController(IPlotLineWorkspaceService workspace) : Controller +{ + public async Task Index( + int projectId, + int? bookId, + [FromQuery(Name = "plotLineId")] int[]? plotLineIds, + [FromQuery(Name = "threadId")] int[]? threadIds, + int? scenarioId, + bool showSuggestions = false) + { + var model = await workspace.GetAsync(projectId, bookId, plotLineIds, threadIds, scenarioId, showSuggestions, false); + return model is null ? NotFound() : View(model); + } + + public async Task Unattributed(int projectId, int? bookId, int? scenarioId) + { + var model = await workspace.GetAsync(projectId, bookId, [], [], scenarioId, false, true); + return model is null ? NotFound() : View("Index", model); + } + + public async Task Inspector(int projectId, int? bookId, int sceneId, int? scenarioId) + { + var model = await workspace.GetInspectorAsync(projectId, bookId, sceneId, scenarioId); + return model is null ? NotFound() : PartialView("_Inspector", model); + } + + public async Task Manuscript(int projectId, int? bookId, int sceneId) + { + var model = await workspace.GetManuscriptAsync(projectId, bookId, sceneId); + return model is null ? NotFound() : PartialView("_Manuscript", model); + } +} diff --git a/PlotLine/Controllers/ScenesController.cs b/PlotLine/Controllers/ScenesController.cs index 60540090..9cf003b7 100644 --- a/PlotLine/Controllers/ScenesController.cs +++ b/PlotLine/Controllers/ScenesController.cs @@ -416,7 +416,8 @@ public sealed class ScenesController( AppearanceNotes = row.AppearanceNotes, OutfitDescription = row.OutfitDescription, PhysicalCondition = row.PhysicalCondition, - EmotionalState = row.EmotionalState + EmotionalState = row.EmotionalState, + KnowledgeNotes = row.KnowledgeNotes }); } @@ -424,7 +425,6 @@ public sealed class ScenesController( { model.NewCharacter.SceneID = model.SceneID; model.NewCharacter.NewCharacterName = null; - model.NewCharacter.KnowledgeNotes = null; model.NewCharacter.ReturnProjectID = current.ReturnProjectID; model.NewCharacter.ReturnBookID = current.ReturnBookID; await characters.AddSceneCharacterAsync(model.NewCharacter); diff --git a/PlotLine/Controllers/TimelineController.cs b/PlotLine/Controllers/TimelineController.cs index e7f1ac63..f12e3963 100644 --- a/PlotLine/Controllers/TimelineController.cs +++ b/PlotLine/Controllers/TimelineController.cs @@ -47,7 +47,6 @@ public sealed class TimelineController(ITimelineService timeline) : Controller current.ShowMetricShape = model.ShowMetricShape; current.ShowPlotLines = model.ShowPlotLines; current.ShowStoryAssets = model.ShowStoryAssets; - current.ShowCharacterAppearances = model.ShowCharacterAppearances; current.ShowWarnings = model.ShowWarnings; current.SelectedMetricTypeIDs = model.SelectedMetricTypeIDs; current.MetricOptions = current.MetricOptions diff --git a/PlotLine/Data/PlotLineWorkspaceRepository.cs b/PlotLine/Data/PlotLineWorkspaceRepository.cs new file mode 100644 index 00000000..51a33d46 --- /dev/null +++ b/PlotLine/Data/PlotLineWorkspaceRepository.cs @@ -0,0 +1,33 @@ +using System.Data; +using Dapper; +using PlotLine.Models; + +namespace PlotLine.Data; + +public interface IPlotLineWorkspaceRepository +{ + Task GetAsync(int projectId, int? bookId, int? scenarioId); +} + +public sealed class PlotLineWorkspaceRepository(ISqlConnectionFactory connectionFactory) : IPlotLineWorkspaceRepository +{ + public async Task GetAsync(int projectId, int? bookId, int? scenarioId) + { + using var connection = connectionFactory.CreateConnection(); + using var results = await connection.QueryMultipleAsync( + "dbo.PlotLineWorkspace_Get", + new { ProjectID = projectId, BookID = bookId, ScenarioID = scenarioId }, + commandType: CommandType.StoredProcedure); + + return new PlotLineWorkspaceData + { + PlotLines = (await results.ReadAsync()).AsList(), + Threads = (await results.ReadAsync()).AsList(), + Contributions = (await results.ReadAsync()).AsList(), + Targets = (await results.ReadAsync()).AsList(), + Dependencies = (await results.ReadAsync()).AsList(), + AttributionScenes = (await results.ReadAsync()).AsList(), + Suggestions = (await results.ReadAsync()).AsList() + }; + } +} diff --git a/PlotLine/Data/SubscriptionRepository.cs b/PlotLine/Data/SubscriptionRepository.cs index c141beda..1f1f23df 100644 --- a/PlotLine/Data/SubscriptionRepository.cs +++ b/PlotLine/Data/SubscriptionRepository.cs @@ -7,6 +7,7 @@ namespace PlotLine.Data; public interface ISubscriptionRepository { Task GetCurrentSubscriptionAsync(int userId); + Task GetSubscriptionForEntitlementAsync(int userId); Task GetSubscriptionLevelAsync(int subscriptionLevelId); Task> GetActiveSubscriptionLevelsAsync(); Task GetOwnedBookCountAsync(int userId); @@ -23,6 +24,13 @@ public interface ISubscriptionRepository Task DowngradeToDraftDeskAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId); Task RecordPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId); Task ClearPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId); + Task GetActiveOverrideAsync(int userId, DateTime utcNow); + Task TryReserveBookSlotsAsync(int userId, int requestedSlots, DateTime utcNow); + Task ReleaseBookSlotReservationAsync(Guid reservationId); + Task> SearchUsersAsync(string? search, int maximumRows = 50); + Task ExtendTrialAsync(int userId, DateTime trialExpiryDateUtc, int administratorUserId, string reason); + Task SaveOverrideAsync(int userId, int subscriptionLevelId, DateTime startDateUtc, DateTime? expiryDateUtc, string reason, int administratorUserId); + Task RevokeOverrideAsync(int userId, int administratorUserId, string reason); } public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFactory) : ISubscriptionRepository @@ -36,6 +44,15 @@ public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFacto commandType: CommandType.StoredProcedure); } + public async Task GetSubscriptionForEntitlementAsync(int userId) + { + using var connection = connectionFactory.CreateConnection(); + return await connection.QuerySingleOrDefaultAsync( + "dbo.UserSubscription_GetForEntitlement", + new { UserID = userId }, + commandType: CommandType.StoredProcedure); + } + public async Task GetSubscriptionLevelAsync(int subscriptionLevelId) { using var connection = connectionFactory.CreateConnection(); @@ -179,4 +196,65 @@ public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFacto new { StripeCustomerId = stripeCustomerId, StripeSubscriptionId = stripeSubscriptionId, LastStripeEventId = lastStripeEventId }, commandType: CommandType.StoredProcedure); } + + public async Task GetActiveOverrideAsync(int userId, DateTime utcNow) + { + using var connection = connectionFactory.CreateConnection(); + return await connection.QuerySingleOrDefaultAsync( + "dbo.SubscriptionOverride_GetActive", + new { UserID = userId, UtcNow = utcNow }, + commandType: CommandType.StoredProcedure); + } + + public async Task TryReserveBookSlotsAsync(int userId, int requestedSlots, DateTime utcNow) + { + using var connection = connectionFactory.CreateConnection(); + return await connection.QuerySingleAsync( + "dbo.SubscriptionEntitlement_TryReserveBookSlots", + new { UserID = userId, RequestedSlots = requestedSlots, UtcNow = utcNow }, + commandType: CommandType.StoredProcedure); + } + + public async Task ReleaseBookSlotReservationAsync(Guid reservationId) + { + using var connection = connectionFactory.CreateConnection(); + await connection.ExecuteAsync( + "dbo.SubscriptionEntitlement_ReleaseBookSlots", + new { ReservationID = reservationId }, + commandType: CommandType.StoredProcedure); + } + + public async Task> SearchUsersAsync(string? search, int maximumRows = 50) + { + using var connection = connectionFactory.CreateConnection(); + var rows = await connection.QueryAsync( + "dbo.SubscriptionAdmin_SearchUsers", + new { Search = search, MaximumRows = maximumRows }, + commandType: CommandType.StoredProcedure); + return rows.ToList(); + } + + public async Task ExtendTrialAsync(int userId, DateTime trialExpiryDateUtc, int administratorUserId, string reason) + { + using var connection = connectionFactory.CreateConnection(); + await connection.ExecuteAsync("dbo.SubscriptionAdmin_ExtendTrial", + new { UserID = userId, TrialExpiryDateUTC = trialExpiryDateUtc, AdministratorUserID = administratorUserId, Reason = reason }, + commandType: CommandType.StoredProcedure); + } + + public async Task SaveOverrideAsync(int userId, int subscriptionLevelId, DateTime startDateUtc, DateTime? expiryDateUtc, string reason, int administratorUserId) + { + using var connection = connectionFactory.CreateConnection(); + await connection.ExecuteAsync("dbo.SubscriptionAdmin_SaveOverride", + new { UserID = userId, SubscriptionLevelID = subscriptionLevelId, StartDateUTC = startDateUtc, ExpiryDateUTC = expiryDateUtc, Reason = reason, AdministratorUserID = administratorUserId }, + commandType: CommandType.StoredProcedure); + } + + public async Task RevokeOverrideAsync(int userId, int administratorUserId, string reason) + { + using var connection = connectionFactory.CreateConnection(); + await connection.ExecuteAsync("dbo.SubscriptionAdmin_RevokeOverride", + new { UserID = userId, AdministratorUserID = administratorUserId, Reason = reason }, + commandType: CommandType.StoredProcedure); + } } diff --git a/PlotLine/Help/Articles/PlotLines/Index.md b/PlotLine/Help/Articles/PlotLines/Index.md index 265ca77e..bb03aabf 100644 --- a/PlotLine/Help/Articles/PlotLines/Index.md +++ b/PlotLine/Help/Articles/PlotLines/Index.md @@ -13,7 +13,7 @@ screenshot: Plot Lines are the larger story questions, promises, mysteries, arcs or unresolved concerns you want to track. They can cover a main mystery, a relationship arc, a character's emotional journey, a trail of foreshadowing or a question that spans multiple books. -Use the Plot Lines list to review the big strands your story has opened. It helps you see what is visible on the timeline, what belongs to one book or the whole project, and which lines may need threads, scenes, clues, reveals or payoffs. +Use the dedicated Plot Lines workspace to follow one line in Focus mode or compare several in Weave mode. It compresses scenes without contributions into gap labels and renders a scene shared by several lines once as a junction. Use **Manage lines** when you need to edit the records themselves. # Plot Lines And Plot Threads @@ -26,5 +26,6 @@ If readers are waiting for an answer, payoff or emotional turn, it probably dese # Related Guides - [Edit Plot Line](/Help/Article/plotLines.edit) +- [Plot Lines Workspace](/Help/Article/plotLines.workspace) - [Plot Threads](/Help/Article/plotThreads.index) - [Scenes](/Help/Article/scenes.overview) diff --git a/PlotLine/Help/Articles/PlotLines/Workspace.md b/PlotLine/Help/Articles/PlotLines/Workspace.md new file mode 100644 index 00000000..9caece3c --- /dev/null +++ b/PlotLine/Help/Articles/PlotLines/Workspace.md @@ -0,0 +1,42 @@ +--- +title: Plot Lines Workspace +category: Plot Lines +tags: plot lines, focus, weave, contributions, gaps, scenarios +contextKey: plotLines.workspace +micro: Follow one plot line or compare several across narrative order. +quickTitle: Using the Plot Lines workspace +quickSummary: Focus follows one line; Weave combines selected lines into one scene contribution map with gaps and shared scenes. +screenshot: +--- + +# Overview + +The Plot Lines workspace is a story map of scenes that contribute to selected plot lines. It follows canonical plot-thread events in manuscript order. It does not repeat every scene: a gap label shows how many scenes or whole chapters pass before the next selected contribution. + +# Focus And Weave + +Select one plot line for **Focus** mode. Select two or more for **Weave** mode. In Weave, a scene that contributes to several selected lines appears once as a shared junction, with each line's contribution shown inside the card. + +Use the thread filter when you need to isolate a smaller strand inside the selected lines. Use the book selector to narrow a series, or choose a scenario to inspect the same contributions in that scenario's proposed order. The workspace does not apply a scenario. + +# Inspecting A Contribution + +Select a scene card to open its inspector. The Contribution section keeps the canonical event and thread role primary. When a canonical event came from an imported narrative candidate and has an exact source-and-scene match, the Evidence section shows the imported title, description and evidence as supporting detail. + +The Scene section shows scene context and loads manuscript text only when requested. Other Lines shows every canonical plot line represented in the scene. + +# Pending And Unattributed Scenes + +Pending suggestions are off by default and remain separate from canonical contributions. Turn them on when you want review context; their presence does not mean the scene belongs to that plot line. + +Open **Unattributed scenes** to distinguish: + +- **Proposed only**: no canonical contribution, but at least one pending suggestion. +- **No known attribution**: neither a canonical contribution nor a pending suggestion. + +# Related Guides + +- [Plot Lines](/Help/Article/plotLines.index) +- [Plot Threads](/Help/Article/plotThreads.index) +- [Scene Inspector Threads](/Help/Article/sceneInspector.threads) +- [Timeline Plot Lines](/Help/Article/timeline.plotLines) diff --git a/PlotLine/Help/Articles/SceneInspector/Characters.md b/PlotLine/Help/Articles/SceneInspector/Characters.md index d3231072..bb37fbb6 100644 --- a/PlotLine/Help/Articles/SceneInspector/Characters.md +++ b/PlotLine/Help/Articles/SceneInspector/Characters.md @@ -11,13 +11,13 @@ screenshot: # Overview -The Characters section records who appears in the scene, how they participate and where they are. This supports Timeline appearance lanes, character-focused views and continuity checks. +The Characters section records who appears in the scene, how they participate, where they are, their appearance and outfit, physical and emotional state, and what they know. This supports character-focused Timeline filters, scene cards, Story Point and continuity checks. Role tells you whether a character is the point of view, a main participant, a supporting presence or only mentioned. Presence and location details help the story remember who was actually there. # Why Adding Characters Matters -Characters drive many PlotDirector systems. Once a character is attached to a scene, they can appear in Timeline lanes, character-focused filters, relationship review, knowledge tracking, attribute history and continuity checks. +Characters drive many PlotDirector systems. Once a character is attached to a scene, they can appear in Timeline filters and search, relationship review, knowledge tracking, attribute history and continuity checks. Open the Scene Inspector when you need the detailed appearance and state record; the general Timeline no longer displays a separate lane for every character. You do not need to fill every character field every time. Add the details that matter: POV when reader access matters, role when participation matters, location when movement or continuity matters, and notes when the scene changes what future scenes need to remember. @@ -27,5 +27,5 @@ Character location and movement help answer whether someone could witness an eve # Related Guides -- [Character Appearances](/Help/Article/timeline.characterAppearances) +- [Timeline Filters and Focus](/Help/Article/timeline.filtersAndFocus) - [Character Attributes](/Help/Article/sceneInspector.characterAttributes) diff --git a/PlotLine/Help/Articles/SceneInspector/Fields/CharacterRole.md b/PlotLine/Help/Articles/SceneInspector/Fields/CharacterRole.md index 4233bd7b..7007cb9a 100644 --- a/PlotLine/Help/Articles/SceneInspector/Fields/CharacterRole.md +++ b/PlotLine/Help/Articles/SceneInspector/Fields/CharacterRole.md @@ -11,4 +11,4 @@ screenshot: # Overview -Use role to show how actively the character participates. A POV or main participant carries more story weight than a mentioned character, and that difference matters in appearance lanes and character-focused review. +Use role to show how actively the character participates. A POV or main participant carries more story weight than a mentioned character, and that difference matters in scene context and character-focused review. diff --git a/PlotLine/Help/Articles/Timeline/CharacterAppearances.md b/PlotLine/Help/Articles/Timeline/CharacterAppearances.md index e60c1ce2..abe156d7 100644 --- a/PlotLine/Help/Articles/Timeline/CharacterAppearances.md +++ b/PlotLine/Help/Articles/Timeline/CharacterAppearances.md @@ -11,7 +11,9 @@ screenshot: # Overview -Character appearance markers show where a character is present in the story. They help you see who is active, who disappears for long stretches, and whether a character's role matches the arc you intend. +Character appearances remain available through character filters, focus, scene search, scene cards and the Scene Inspector. The general Timeline no longer renders a separate lane for every character; this keeps the planning view centred on scenes, plot lines, assets, metrics and warnings. + +Use a character filter or character focus to narrow the Timeline. Open a scene's inspector to review role, presence, location, entry and exit, appearance, outfit, physical and emotional state, and knowledge notes. Presence can mean more than standing in the room. A character may be a point-of-view character, a main participant, a mentioned person or someone whose absence matters. diff --git a/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md b/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md index 1048b1f1..1bc13964 100644 --- a/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md +++ b/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md @@ -11,4 +11,4 @@ screenshot: # Overview -When dropping a character onto a scene, choose role and presence to record how the scene uses them. This affects character lanes, POV review and continuity. +When dropping a character onto a scene, choose role and presence to record how the scene uses them. This affects character focus and filters, POV review, scene context and continuity. diff --git a/PlotLine/Models/PlotLineWorkspaceModels.cs b/PlotLine/Models/PlotLineWorkspaceModels.cs new file mode 100644 index 00000000..0d4c73b8 --- /dev/null +++ b/PlotLine/Models/PlotLineWorkspaceModels.cs @@ -0,0 +1,146 @@ +namespace PlotLine.Models; + +public sealed class PlotLineWorkspaceData +{ + public IReadOnlyList PlotLines { get; init; } = []; + public IReadOnlyList Threads { get; init; } = []; + public IReadOnlyList Contributions { get; init; } = []; + public IReadOnlyList Targets { get; init; } = []; + public IReadOnlyList Dependencies { get; init; } = []; + public IReadOnlyList AttributionScenes { get; init; } = []; + public IReadOnlyList Suggestions { get; init; } = []; +} + +public sealed class PlotLineWorkspaceLineRow +{ + public int PlotLineID { get; set; } + public int ProjectID { get; set; } + public int? BookID { get; set; } + public string PlotLineName { get; set; } = string.Empty; + public string? Description { get; set; } + public string PlotLineTypeName { get; set; } = string.Empty; + public string PlotImportanceName { get; set; } = string.Empty; + public string Colour { get; set; } = "#2f6f63"; + public int SortOrder { get; set; } + public int ThreadCount { get; set; } + public int ContributionSceneCount { get; set; } +} + +public sealed class PlotLineWorkspaceThreadRow +{ + public int PlotThreadID { get; set; } + public int PlotLineID { get; set; } + public string ThreadTitle { get; set; } = string.Empty; + public string? Summary { get; set; } + public string ThreadTypeName { get; set; } = string.Empty; + public string ThreadStatusName { get; set; } = string.Empty; + public int Importance { get; set; } + public int? IntroducedSceneID { get; set; } + public string? IntroducedSceneLabel { get; set; } + public int? PlannedResolutionSceneID { get; set; } + public string? PlannedResolutionSceneLabel { get; set; } + public int? ActualResolutionSceneID { get; set; } + public string? ActualResolutionSceneLabel { get; set; } + public int ContributionCount { get; set; } +} + +public sealed class PlotLineWorkspaceContributionRow +{ + public int ThreadEventID { get; set; } + public int PlotThreadID { get; set; } + public int PlotLineID { get; set; } + public int SceneID { get; set; } + public int BookID { get; set; } + public int ChapterID { get; set; } + public decimal ChapterNumber { get; set; } + public string ChapterTitle { get; set; } = string.Empty; + public decimal SceneNumber { get; set; } + public string SceneTitle { get; set; } = string.Empty; + public string? SceneSummary { get; set; } + public int NarrativeOrder { get; set; } + public string? PovCharacterName { get; set; } + public string? CharacterNames { get; set; } + public string? LocationName { get; set; } + public DateTime? StartDateTime { get; set; } + public DateTime? EndDateTime { get; set; } + public string? RelativeTimeText { get; set; } + public string TimeModeName { get; set; } = string.Empty; + public string TimeConfidenceName { get; set; } = string.Empty; + public int WarningCount { get; set; } + public int DependencyCount { get; set; } + public bool HasManuscript { get; set; } + public string ThreadTitle { get; set; } = string.Empty; + public string ThreadStatusName { get; set; } = string.Empty; + public int ThreadImportance { get; set; } + public string CanonicalRole { get; set; } = string.Empty; + public string CanonicalMarker { get; set; } = string.Empty; + public string CanonicalStructuralType { get; set; } = string.Empty; + public string CanonicalTitle { get; set; } = string.Empty; + public string? CanonicalDescription { get; set; } + public decimal? CanonicalConfidence { get; set; } + public string Source { get; set; } = string.Empty; + public int? SourceReferenceID { get; set; } + public string? SourceKey { get; set; } + public string CandidateMatchState { get; set; } = "Not applicable"; + public string? CandidateTitle { get; set; } + public string? CandidateDescription { get; set; } + public string? CandidateEvidence { get; set; } + public decimal? CandidateConfidence { get; set; } + public string? CandidateSignificance { get; set; } +} + +public sealed class PlotLineWorkspaceTargetRow +{ + public int ThreadEventID { get; set; } + public int SourcePlotLineID { get; set; } + public int TargetPlotLineID { get; set; } + public string StructuralType { get; set; } = string.Empty; +} + +public sealed class PlotLineWorkspaceDependencyRow +{ + public int SceneDependencyID { get; set; } + public int SourceSceneID { get; set; } + public int TargetSceneID { get; set; } + public string DependencyType { get; set; } = string.Empty; + public string? Description { get; set; } + public bool IsHardDependency { get; set; } +} + +public sealed class PlotLineWorkspaceAttributionRow +{ + public int SceneID { get; set; } + public int BookID { get; set; } + public int ChapterID { get; set; } + public decimal ChapterNumber { get; set; } + public string ChapterTitle { get; set; } = string.Empty; + public decimal SceneNumber { get; set; } + public string SceneTitle { get; set; } = string.Empty; + public string? Summary { get; set; } + public int NarrativeOrder { get; set; } + public string? PovCharacterName { get; set; } + public string? CharacterNames { get; set; } + public string? LocationName { get; set; } + public string? PurposeNames { get; set; } + public string? RelativeTimeText { get; set; } + public DateTime? StartDateTime { get; set; } + public int WarningCount { get; set; } + public int DependencyCount { get; set; } + public bool HasManuscript { get; set; } + public int CanonicalPlotLineCount { get; set; } + public int ProposedCandidateCount { get; set; } + public string? ProposedCandidateNames { get; set; } +} + +public sealed class PlotLineWorkspaceSuggestionRow +{ + public int NarrativeCandidateID { get; set; } + public int SceneID { get; set; } + public string CandidateType { get; set; } = string.Empty; + public string CandidateTitle { get; set; } = string.Empty; + public string Status { get; set; } = string.Empty; + public string? Significance { get; set; } + public decimal? CandidateConfidence { get; set; } + public string? ContributionType { get; set; } + public string? Evidence { get; set; } +} diff --git a/PlotLine/Models/SubscriptionModels.cs b/PlotLine/Models/SubscriptionModels.cs index e52ee26a..727ea02b 100644 --- a/PlotLine/Models/SubscriptionModels.cs +++ b/PlotLine/Models/SubscriptionModels.cs @@ -103,6 +103,95 @@ public sealed class SubscriptionUsageSummary public long StorageMaximumBytes { get; set; } } +public enum EntitlementState +{ + ActivePaid, + ActiveTrial, + ActiveOverride, + ExpiredTrial, + InactiveSubscription, + MissingSubscription +} + +public enum SubscriptionFeature +{ + EditContent, + Import, + StoryIntelligence +} + +public sealed class SubscriptionOverride +{ + public int SubscriptionOverrideID { get; set; } + public int UserID { get; set; } + public int SubscriptionLevelID { get; set; } + public DateTime StartDateUTC { get; set; } + public DateTime? ExpiryDateUTC { get; set; } + public string Reason { get; set; } = string.Empty; + public int CreatedByUserID { get; set; } + public DateTime CreatedDateUTC { get; set; } + public int ModifiedByUserID { get; set; } + public DateTime ModifiedDateUTC { get; set; } + public DateTime? RevokedDateUTC { get; set; } + public int? RevokedByUserID { get; set; } + public string LevelName { get; set; } = string.Empty; + public string LevelDisplayName { get; set; } = string.Empty; +} + +public sealed class EffectiveEntitlement +{ + public int UserID { get; init; } + public UserSubscriptionDetail? UnderlyingSubscription { get; init; } + public SubscriptionLevel? EffectiveLevel { get; init; } + public SubscriptionOverride? ActiveOverride { get; init; } + public EntitlementState State { get; init; } + public DateTime EvaluatedAtUTC { get; init; } + public DateTime? TrialStartDateUTC { get; init; } + public DateTime? TrialExpiryDateUTC { get; init; } + public string Reason { get; init; } = string.Empty; + public bool IsActive => State is EntitlementState.ActivePaid or EntitlementState.ActiveTrial or EntitlementState.ActiveOverride; + public bool IsReadOnly => !IsActive; + public bool IsTrial => State is EntitlementState.ActiveTrial or EntitlementState.ExpiredTrial; + public bool IsTrialExpired => State == EntitlementState.ExpiredTrial; + public bool UsesAdministrativeOverride => State == EntitlementState.ActiveOverride; +} + +public sealed class EntitlementDecision +{ + public bool Allowed { get; init; } + public string Code { get; init; } = string.Empty; + public string Message { get; init; } = string.Empty; + public EffectiveEntitlement Entitlement { get; init; } = new(); +} + +public sealed class BookSlotReservation +{ + public bool Allowed { get; init; } + public Guid? ReservationID { get; init; } + public int CurrentUsage { get; init; } + public int MaximumAllowed { get; init; } + public string Message { get; init; } = string.Empty; +} + +public sealed class SubscriptionResourceRequest +{ + public int AdditionalBooks { get; init; } + public IReadOnlyList FinalChapterCounts { get; init; } = []; + public IReadOnlyList FinalSceneCounts { get; init; } = []; + public int? FinalCharacterCount { get; init; } +} + +public sealed class SubscriptionAdminUserSummary +{ + public int UserID { get; set; } + public string Email { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public string? UnderlyingPlanName { get; set; } + public bool? IsTrial { get; set; } + public DateTime? TrialExpiryDateUTC { get; set; } + public string? StripeStatus { get; set; } +} + public sealed class StripeSubscriptionSyncState { public int? UserID { get; set; } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index bc18e179..ff22bc64 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -23,6 +23,7 @@ public class Program builder.Services.AddControllersWithViews(options => { options.Filters.Add(); + options.Filters.Add(); }); builder.Services.AddSignalR(options => { @@ -125,6 +126,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -184,6 +186,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -264,6 +267,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/ApplicationNavigation.cs b/PlotLine/Services/ApplicationNavigation.cs index 6adbc203..ff459330 100644 --- a/PlotLine/Services/ApplicationNavigation.cs +++ b/PlotLine/Services/ApplicationNavigation.cs @@ -18,7 +18,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo "Projects" or "Books" or "Chapters" or "Scenes" => "Overview", "StoryCalendar" => "Calendar", "StoryPoint" => "At This Point", "RelationshipMap" => "Relationships", "StoryAssets" => "Assets", - "FloorPlans" => "Floor Plans", "PlotThreads" => "Threads", + "FloorPlans" => "Floor Plans", "PlotThreads" => "Threads", "PlotLineWorkspace" => "Plot Lines", "ProjectMetrics" => "Metrics", "StoryBible" => "Story Bible", "ContinuityExplorer" => "Continuity Explorer", "Analytics" or "Dynamics" => "Health", "Archives" => "Archive", _ => controller diff --git a/PlotLine/Services/ApplicationRibbon.cs b/PlotLine/Services/ApplicationRibbon.cs index 0d2c143f..08892e2a 100644 --- a/PlotLine/Services/ApplicationRibbon.cs +++ b/PlotLine/Services/ApplicationRibbon.cs @@ -31,7 +31,7 @@ public static class ApplicationRibbon new("book", "Book", new("Selected book", new("Book overview", "bible", "Books", "Details", "book"), new("Edit book", "writer", "Books", "Edit", "book"), new("Add chapter", "threads", "Chapters", "Create", "chapter")), new("Manuscript review", S("review")), new("Library", S("overview"), new("Add book", "bible", "Books", "Create"))), - new("story", "Story", new("Story structure", S("timeline"), S("calendar"), S("threads"), S("point")), new("Analysis & planning", S("review"), S("scenarios"), S("continuity")), new("Writing", S("writer"))), + new("story", "Story", new("Story structure", S("timeline"), S("calendar"), S("plotlines"), S("threads"), S("point")), new("Analysis & planning", S("review"), S("scenarios"), S("continuity")), new("Writing", S("writer"))), new("characters", "Characters", new("Cast", S("characters"), S("names")), new("Connections", S("relationships"))), new("world", "World", new("Setting", S("locations"), S("floorplans")), new("Story world", S("assets"))), new("tools", "Tools", new("Reference", S("bible")), new("Insights", S("metrics"), S("health"), S("warnings")), new("Organisation", S("archive"))), @@ -43,7 +43,7 @@ public static class ApplicationRibbon "Onboarding" => "story", _ => section switch { - "Timeline" or "Calendar" or "At This Point" or "Threads" or "Scenarios" or "Continuity Explorer" => "story", + "Timeline" or "Calendar" or "At This Point" or "Plot Lines" or "Threads" or "Scenarios" or "Continuity Explorer" => "story", "Characters" or "Names" or "Relationships" => "characters", "Locations" or "Assets" or "Floor Plans" => "world", "Story Bible" or "Metrics" or "Health" or "Warnings" or "Archive" => "tools", _ => "project" diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index f8193436..92c5cfba 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -1532,9 +1532,21 @@ public sealed class BookService( public async Task SaveAsync(BookEditViewModel model) { + Guid? bookReservationId = null; if (model.BookID == 0) { - await SubscriptionLimitGuards.EnsureAllowedAsync(subscriptions.CanCreateBookAsync, currentUser.UserId); + if (currentUser.UserId is not int userId) + { + throw new SubscriptionLimitException("Sign in before creating new content."); + } + + var reservation = await subscriptions.ReserveBookSlotsAsync(userId); + if (!reservation.Allowed) + { + throw new SubscriptionLimitException(reservation.Message); + } + + bookReservationId = reservation.ReservationID; } if (!BookStatuses.IsValid(model.Status)) @@ -1543,25 +1555,36 @@ public sealed class BookService( } var isNew = model.BookID == 0; - var bookId = await books.SaveAsync(new Book + int bookId; + try { - BookID = model.BookID, - ProjectID = model.ProjectID, - BookTitle = model.BookTitle, - Subtitle = model.Subtitle, - Tagline = model.Tagline, - ShortDescription = model.ShortDescription, - Status = model.Status, - BookNumber = model.BookNumber, - Description = model.Description, - TargetWordCount = model.TargetWordCount, - StoryEra = TrimOptional(model.StoryEra), - PrimaryLocaleCode = TrimOptional(model.PrimaryLocaleCode), - WritingStartDate = model.WritingStartDate, - TargetCompletionDate = model.TargetCompletionDate, - PublicationDate = model.PublicationDate, - UsesExplicitScenes = model.UsesExplicitScenes - }); + bookId = await books.SaveAsync(new Book + { + BookID = model.BookID, + ProjectID = model.ProjectID, + BookTitle = model.BookTitle, + Subtitle = model.Subtitle, + Tagline = model.Tagline, + ShortDescription = model.ShortDescription, + Status = model.Status, + BookNumber = model.BookNumber, + Description = model.Description, + TargetWordCount = model.TargetWordCount, + StoryEra = TrimOptional(model.StoryEra), + PrimaryLocaleCode = TrimOptional(model.PrimaryLocaleCode), + WritingStartDate = model.WritingStartDate, + TargetCompletionDate = model.TargetCompletionDate, + PublicationDate = model.PublicationDate, + UsesExplicitScenes = model.UsesExplicitScenes + }); + } + finally + { + if (bookReservationId.HasValue) + { + await subscriptions.ReleaseBookSlotReservationAsync(bookReservationId.Value); + } + } await activity.RecordAsync(model.ProjectID, isNew ? "Created" : "Updated", "Book", bookId, model.BookTitle); if (model.CoverUpload is { Length: > 0 }) @@ -2548,7 +2571,9 @@ public sealed class TimelineService( var needsPlotTimelineData = settings.ShowPlotLines || filter.PlotLineID.HasValue || filter.PlotThreadID.HasValue || filter.FocusType is "plotline" or "plotthread"; var needsMetricTimelineData = settings.ShowMetricShape && selectedMetricIds.Any(); var needsAssetTimelineData = settings.ShowStoryAssets || filter.StoryAssetID.HasValue || filter.FocusType == "asset"; - var needsCharacterTimelineData = settings.ShowCharacterAppearances || filter.CharacterID.HasValue || filter.FocusType == "character"; + // Character data remains available for filters, POV chips, quick-add and inspector behaviour, + // but character appearance lanes no longer belong to the general Timeline presentation. + var needsCharacterTimelineData = filter.CharacterID.HasValue || filter.FocusType == "character"; var needsWarnings = settings.ShowWarnings || filter.WarningSeverityID.HasValue || filter.WarningTypeID.HasValue || filter.ShowWarningsOnly; var timeline = await TimeTimelineLoadAsync( @@ -2635,9 +2660,6 @@ public sealed class TimelineService( var assetLanes = settings.ShowStoryAssets ? await TimeTimelineLoadAsync("TimelineService.BuildAssetLanes", () => Task.FromResult(BuildAssetLanes(assetTimeline.Assets, assetTimeline.Events, orderedScenes)), projectId, bookId) : []; - var characterLanes = settings.ShowCharacterAppearances - ? await TimeTimelineLoadAsync("TimelineService.BuildCharacterLanes", () => Task.FromResult(BuildCharacterLanes(characterTimeline.Characters, characterTimeline.Appearances, orderedScenes)), projectId, bookId) - : []; var selectedContext = selectedSceneId.HasValue ? await TimeTimelineLoadAsync("StoryContextService.GetForSceneAsync", () => storyContext.GetForSceneAsync(selectedSceneId.Value, projectId, bookId), projectId, bookId) : null; @@ -2716,7 +2738,7 @@ public sealed class TimelineService( MetricGraphs = metricGraphs, PlotLanes = plotLanes, AssetLanes = assetLanes, - CharacterLanes = characterLanes, + CharacterLanes = [], SceneOverviews = sceneOverviews, WarningsByScene = warningsByScene, MatchingSceneIDs = matchingSceneIds, @@ -2750,7 +2772,6 @@ public sealed class TimelineService( ShowMetricShape = settings.ShowMetricShape, ShowPlotLines = settings.ShowPlotLines, ShowStoryAssets = settings.ShowStoryAssets, - ShowCharacterAppearances = settings.ShowCharacterAppearances, ShowWarnings = settings.ShowWarnings, SelectedMetricTypeIDs = selectedMetricIds.ToList(), MetricOptions = metricTypes @@ -2782,7 +2803,7 @@ public sealed class TimelineService( ShowMetricShape = model.ShowMetricShape, ShowPlotLines = model.ShowPlotLines, ShowStoryAssets = model.ShowStoryAssets, - ShowCharacterAppearances = model.ShowCharacterAppearances, + ShowCharacterAppearances = false, ShowWarnings = model.ShowWarnings }, model.SelectedMetricTypeIDs); } diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 9e062482..d0b059c4 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -14,7 +14,7 @@ public interface IImportService Task BuildValidationReportAsync(ImportIndexViewModel model); } -public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ILogger logger) : IImportService +public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ISubscriptionService subscriptions, ILogger logger) : IImportService { private const int TitleMaxLength = 200; private const int RelativeTimeMaxLength = 200; @@ -136,6 +136,18 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService return BuildDryRunResult(preview); } + var resourceDecision = await subscriptions.CanUseResourcesAsync(userId.Value, ToResourceRequest(preview)); + if (!resourceDecision.Allowed) + { + return new ImportResult { Succeeded = false, Message = resourceDecision.Message }; + } + + var reservation = await subscriptions.ReserveBookSlotsAsync(userId.Value, preview.BookCount); + if (!reservation.Allowed) + { + return new ImportResult { Succeeded = false, Message = reservation.Message }; + } + try { var timer = Stopwatch.StartNew(); @@ -167,6 +179,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService TechnicalDetail = ex.Message }; } + finally + { + if (reservation.ReservationID.HasValue) + { + await subscriptions.ReleaseBookSlotReservationAsync(reservation.ReservationID.Value); + } + } } public async Task BuildValidationReportAsync(ImportIndexViewModel model) @@ -381,6 +400,18 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService return BuildBackupDryRunResult(preview); } + var resourceDecision = await subscriptions.CanUseResourcesAsync(userId, ToResourceRequest(preview)); + if (!resourceDecision.Allowed) + { + return new ImportResult { Succeeded = false, Message = resourceDecision.Message }; + } + + var reservation = await subscriptions.ReserveBookSlotsAsync(userId, backup.Data.Books.Count); + if (!reservation.Allowed) + { + return new ImportResult { Succeeded = false, Message = reservation.Message }; + } + try { var projectName = preview.HasDuplicateProjectTitle @@ -455,6 +486,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService TechnicalDetail = ex.Message }; } + finally + { + if (reservation.ReservationID.HasValue) + { + await subscriptions.ReleaseBookSlotReservationAsync(reservation.ReservationID.Value); + } + } } private static ImportResult BuildBackupDryRunResult(ImportPreview preview) @@ -481,6 +519,14 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService Message = "Dry run complete. No data was saved." }; + private static SubscriptionResourceRequest ToResourceRequest(ImportPreview preview) => new() + { + AdditionalBooks = preview.BookCount, + FinalChapterCounts = preview.BookPreviews.Select(book => book.ChapterCount).ToList(), + FinalSceneCounts = preview.BookPreviews.Select(book => book.SceneCount).ToList(), + FinalCharacterCount = preview.CharacterCount + }; + private static bool TryReadProjectBackup(string jsonText, out ProjectBackupExport? backup, out ImportValidationResult validation) { backup = null; diff --git a/PlotLine/Services/PlotLineWorkspaceService.cs b/PlotLine/Services/PlotLineWorkspaceService.cs new file mode 100644 index 00000000..02723ea0 --- /dev/null +++ b/PlotLine/Services/PlotLineWorkspaceService.cs @@ -0,0 +1,217 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; + +namespace PlotLine.Services; + +public interface IPlotLineWorkspaceService +{ + Task GetAsync(int projectId, int? bookId, IEnumerable? plotLineIds, IEnumerable? threadIds, int? scenarioId, bool showSuggestions, bool unattributed); + Task GetInspectorAsync(int projectId, int? bookId, int sceneId, int? scenarioId); + Task GetManuscriptAsync(int projectId, int? bookId, int sceneId); +} + +public sealed class PlotLineWorkspaceService( + IPlotLineWorkspaceRepository workspace, + IProjectRepository projects, + IBookRepository books, + IScenarioRepository scenarios, + IStoryContextService storyContext, + IManuscriptTextStatisticsRepository manuscriptSources) : IPlotLineWorkspaceService +{ + public async Task GetAsync( + int projectId, + int? bookId, + IEnumerable? plotLineIds, + IEnumerable? threadIds, + int? scenarioId, + bool showSuggestions, + bool unattributed) + { + var project = await projects.GetAsync(projectId); + if (project is null) + { + return null; + } + + var projectBooks = (await books.ListByProjectAsync(projectId)).Where(x => !x.IsArchived).ToList(); + if (bookId.HasValue && projectBooks.All(x => x.BookID != bookId.Value)) + { + return null; + } + + var projectScenarios = (await scenarios.ListAsync(projectId)).Where(x => !x.IsArchived).ToList(); + var selectedScenario = scenarioId.HasValue + ? projectScenarios.FirstOrDefault(x => x.ScenarioID == scenarioId.Value && (!bookId.HasValue || !x.BookID.HasValue || x.BookID == bookId)) + : null; + if (scenarioId.HasValue && selectedScenario is null) + { + return null; + } + + var data = await workspace.GetAsync(projectId, bookId, selectedScenario?.ScenarioID); + var availableIds = data.PlotLines.Select(x => x.PlotLineID).ToHashSet(); + var selectedLineIds = (plotLineIds ?? []).Where(availableIds.Contains).Distinct().ToList(); + if (!unattributed && selectedLineIds.Count == 0 && data.PlotLines.Count > 0) + { + selectedLineIds.Add(data.PlotLines.OrderByDescending(x => x.ContributionSceneCount).ThenBy(x => x.SortOrder).First().PlotLineID); + } + + var selectedThreads = (threadIds ?? []).Where(id => data.Threads.Any(x => x.PlotThreadID == id && selectedLineIds.Contains(x.PlotLineID))).Distinct().ToList(); + var composedScenes = unattributed ? [] : PlotLineWorkspaceComposer.Compose(data, selectedLineIds, selectedThreads); + var suggestionsByScene = showSuggestions + ? data.Suggestions.GroupBy(x => x.SceneID).ToDictionary(x => x.Key, x => (IReadOnlyList)x + .GroupBy(y => new { y.NarrativeCandidateID, y.ContributionType, y.Evidence }) + .Select(y => y.First()).ToList()) + : []; + + return new PlotLineWorkspaceViewModel + { + Project = project, + SelectedBookID = bookId, + SelectedScenarioID = selectedScenario?.ScenarioID, + SelectedScenarioName = selectedScenario?.ScenarioName, + Mode = unattributed ? "Unattributed" : selectedLineIds.Count > 1 ? "Weave" : "Focus", + ShowSuggestions = showSuggestions, + Books = projectBooks, + Scenarios = projectScenarios.Where(x => !bookId.HasValue || !x.BookID.HasValue || x.BookID == bookId).ToList(), + PlotLines = data.PlotLines.Select(line => new PlotLineWorkspaceLineViewModel + { + Line = line, + IsSelected = selectedLineIds.Contains(line.PlotLineID), + Threads = data.Threads.Where(x => x.PlotLineID == line.PlotLineID).ToList() + }).ToList(), + SelectedPlotLineIDs = selectedLineIds, + SelectedThreadIDs = selectedThreads, + Scenes = composedScenes, + SuggestedScenes = showSuggestions + ? data.AttributionScenes.Where(x => suggestionsByScene.ContainsKey(x.SceneID)).Select(x => new PlotLineWorkspaceSuggestionSceneViewModel + { + Scene = x, + Suggestions = suggestionsByScene[x.SceneID] + }).ToList() + : [], + ProposedOnlyScenes = unattributed ? data.AttributionScenes.Where(x => x.CanonicalPlotLineCount == 0 && x.ProposedCandidateCount > 0).ToList() : [], + NoKnownAttributionScenes = unattributed ? data.AttributionScenes.Where(x => x.CanonicalPlotLineCount == 0 && x.ProposedCandidateCount == 0).ToList() : [] + }; + } + + public async Task GetInspectorAsync(int projectId, int? bookId, int sceneId, int? scenarioId) + { + var context = await storyContext.GetForSceneAsync(sceneId, projectId, bookId); + if (context?.Scene is null) + { + return null; + } + + var data = await workspace.GetAsync(projectId, bookId, scenarioId); + if (data.AttributionScenes.All(x => x.SceneID != sceneId)) + { + return null; + } + + var memberships = PlotLineWorkspaceComposer.ComposeMemberships(data, data.Contributions.Where(x => x.SceneID == sceneId)); + var sceneEventIds = memberships.SelectMany(x => x.Contributions).Select(x => x.ThreadEventID).ToHashSet(); + var lineNames = data.PlotLines.ToDictionary(x => x.PlotLineID, x => x.PlotLineName); + return new PlotLineWorkspaceInspectorViewModel + { + ProjectID = projectId, + BookID = bookId, + Scene = context.Scene, + Memberships = memberships, + Threads = data.Threads.Where(x => memberships.Any(m => m.Contributions.Any(c => c.PlotThreadID == x.PlotThreadID))).ToList(), + Dependencies = data.Dependencies.Where(x => x.SourceSceneID == sceneId || x.TargetSceneID == sceneId).ToList(), + Targets = data.Targets.Where(x => sceneEventIds.Contains(x.ThreadEventID)).Select(x => new PlotLineWorkspaceTargetViewModel + { + SourcePlotLineName = lineNames.GetValueOrDefault(x.SourcePlotLineID, "Plot line"), + TargetPlotLineName = lineNames.GetValueOrDefault(x.TargetPlotLineID, "Plot line"), + StructuralType = x.StructuralType + }).ToList(), + Suggestions = data.Suggestions.Where(x => x.SceneID == sceneId) + .GroupBy(x => new { x.NarrativeCandidateID, x.ContributionType, x.Evidence }).Select(x => x.First()).ToList() + }; + } + + public async Task GetManuscriptAsync(int projectId, int? bookId, int sceneId) + { + var source = await manuscriptSources.GetSourceBySceneAsync(sceneId); + if (source is null || source.ProjectID != projectId || (bookId.HasValue && source.BookID != bookId.Value)) + { + return null; + } + + return new PlotLineWorkspaceManuscriptViewModel + { + SceneID = sceneId, + SceneTitle = string.IsNullOrWhiteSpace(source.SceneTitle) ? $"Scene {source.SceneNumber:0.##}" : source.SceneTitle, + SourceText = source.SourceText, + SourceWordCount = source.SourceWordCount + }; + } +} + +public static class PlotLineWorkspaceComposer +{ + public static IReadOnlyList Compose( + PlotLineWorkspaceData data, + IReadOnlyCollection selectedLineIds, + IReadOnlyCollection? selectedThreadIds = null) + { + var selectedThreads = selectedThreadIds?.ToHashSet() ?? []; + var contributions = data.Contributions + .Where(x => selectedLineIds.Contains(x.PlotLineID) && (selectedThreads.Count == 0 || selectedThreads.Contains(x.PlotThreadID))) + .GroupBy(x => x.SceneID) + .Select(x => x.OrderBy(y => y.NarrativeOrder).ThenBy(y => y.ThreadEventID).ToList()) + .OrderBy(x => x[0].NarrativeOrder) + .ToList(); + + var scenes = new List(); + PlotLineWorkspaceContributionRow? previous = null; + foreach (var sceneContributions in contributions) + { + var first = sceneContributions[0]; + scenes.Add(new PlotLineWorkspaceSceneViewModel + { + SceneID = first.SceneID, + NarrativeOrder = first.NarrativeOrder, + GapBefore = previous is null ? 0 : Math.Max(0, first.NarrativeOrder - previous.NarrativeOrder - 1), + ChapterGapBefore = previous is null ? 0 : Math.Max(0, (int)Math.Floor(first.ChapterNumber) - (int)Math.Floor(previous.ChapterNumber) - 1), + ChapterNumber = first.ChapterNumber, + ChapterTitle = first.ChapterTitle, + SceneNumber = first.SceneNumber, + SceneTitle = first.SceneTitle, + Summary = first.SceneSummary, + PovCharacterName = first.PovCharacterName, + LocationName = first.LocationName, + TimeLabel = first.StartDateTime?.ToString("g") ?? first.RelativeTimeText, + WarningCount = first.WarningCount, + DependencyCount = first.DependencyCount, + HasManuscript = first.HasManuscript, + StructuralTargetCount = data.Targets.Count(x => sceneContributions.Any(c => c.ThreadEventID == x.ThreadEventID)), + Memberships = ComposeMemberships(data, sceneContributions), + Connections = data.Dependencies.Where(x => x.SourceSceneID == first.SceneID || x.TargetSceneID == first.SceneID).ToList() + }); + previous = first; + } + + return scenes; + } + + public static IReadOnlyList ComposeMemberships( + PlotLineWorkspaceData data, + IEnumerable contributions) + { + var lineLookup = data.PlotLines.ToDictionary(x => x.PlotLineID); + return contributions.GroupBy(x => x.PlotLineID).Select(group => + { + lineLookup.TryGetValue(group.Key, out var line); + return new PlotLineWorkspaceSceneMembershipViewModel + { + PlotLineID = group.Key, + PlotLineName = line?.PlotLineName ?? "Plot line", + Colour = line?.Colour ?? "#2f6f63", + Contributions = group.OrderByDescending(x => x.ThreadImportance).ThenBy(x => x.ThreadTitle).ThenBy(x => x.ThreadEventID).ToList() + }; + }).OrderBy(x => lineLookup.TryGetValue(x.PlotLineID, out var line) ? line.SortOrder : int.MaxValue).ToList(); + } +} diff --git a/PlotLine/Services/ProjectAccessFilter.cs b/PlotLine/Services/ProjectAccessFilter.cs index f8ec3c0b..bb476411 100644 --- a/PlotLine/Services/ProjectAccessFilter.cs +++ b/PlotLine/Services/ProjectAccessFilter.cs @@ -77,6 +77,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs ["FloorPlans"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "FloorPlan", ["floorPlanId"] = "FloorPlan", ["floorPlanFloorId"] = "FloorPlanFloor", ["floorPlanBlockId"] = "FloorPlanBlock", ["projectId"] = "Project" }, ["PlotLines"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "PlotLine", ["plotLineId"] = "PlotLine", ["projectId"] = "Project" }, ["PlotThreads"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "PlotThread", ["plotThreadId"] = "PlotThread", ["plotLineId"] = "PlotLine", ["projectId"] = "Project" }, + ["PlotLineWorkspace"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["scenarioId"] = "Scenario" }, ["ProjectMetrics"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project" }, ["ProjectRestorePoints"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["id"] = "ProjectRestorePoint" }, ["RelationshipMap"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene", ["focusCharacterId"] = "Character" }, diff --git a/PlotLine/Services/StoryIntelligenceOperationalServices.cs b/PlotLine/Services/StoryIntelligenceOperationalServices.cs index e8d04201..619a64fb 100644 --- a/PlotLine/Services/StoryIntelligenceOperationalServices.cs +++ b/PlotLine/Services/StoryIntelligenceOperationalServices.cs @@ -17,35 +17,12 @@ public sealed class StoryIntelligenceEntitlementService(ISubscriptionService sub private async Task EnsureAllowedAsync(int userId) { - var subscription = await subscriptions.GetCurrentSubscriptionAsync(userId); - if (!IsActive(subscription, DateTime.UtcNow)) + var decision = await subscriptions.CanUseFeatureAsync(userId, SubscriptionFeature.StoryIntelligence); + if (!decision.Allowed) { - throw new SubscriptionLimitException("Story Intelligence requires an active subscription before paid AI work can be queued or processed."); + throw new SubscriptionLimitException($"{decision.Message} Story Intelligence requires active access before paid AI work can be queued or processed."); } } - - private static bool IsActive(UserSubscriptionDetail? subscription, DateTime utcNow) - { - if (subscription is null || !subscription.IsActive || !subscription.SubscriptionLevelIsActive) - { - return false; - } - - if (subscription.EndDateUTC.HasValue && subscription.EndDateUTC.Value <= utcNow) - { - return false; - } - - if (subscription.CurrentPeriodEndUTC.HasValue - && subscription.CurrentPeriodEndUTC.Value <= utcNow - && !string.IsNullOrWhiteSpace(subscription.StripeSubscriptionId)) - { - return false; - } - - var status = (subscription.StripeStatus ?? string.Empty).Trim().ToLowerInvariant(); - return status is not ("canceled" or "cancelled" or "incomplete_expired" or "ended" or "expired" or "inactive"); - } } public interface IStoryIntelligenceCompletionNotificationService diff --git a/PlotLine/Services/SubscriptionEnforcementFilter.cs b/PlotLine/Services/SubscriptionEnforcementFilter.cs new file mode 100644 index 00000000..0ca7c722 --- /dev/null +++ b/PlotLine/Services/SubscriptionEnforcementFilter.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace PlotLine.Services; + +public sealed class SubscriptionEnforcementFilter( + ICurrentUserService currentUser, + ISubscriptionService subscriptions) : IAsyncActionFilter +{ + private static readonly HashSet ReadOnlySafeControllers = new(StringComparer.OrdinalIgnoreCase) + { + "Account", "ManageAccount", "Pricing", "Exports", "Admin", "StripeWebhook" + }; + + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + if (HttpMethods.IsGet(context.HttpContext.Request.Method) + || HttpMethods.IsHead(context.HttpContext.Request.Method) + || HttpMethods.IsOptions(context.HttpContext.Request.Method) + || currentUser.UserId is not int userId + || ReadOnlySafeControllers.Contains(context.Controller.GetType().Name.Replace("Controller", string.Empty, StringComparison.Ordinal))) + { + await next(); + return; + } + + var decision = await subscriptions.CanUseFeatureAsync(userId, Models.SubscriptionFeature.EditContent); + if (decision.Allowed) + { + await next(); + return; + } + + if (context.HttpContext.Request.Path.StartsWithSegments("/api")) + { + context.Result = new ObjectResult(new ProblemDetails + { + Status = StatusCodes.Status403Forbidden, + Title = "Subscription access required", + Detail = decision.Message + }) { StatusCode = StatusCodes.Status403Forbidden }; + return; + } + + if (context.Controller is Controller controller) + { + controller.TempData["SubscriptionMessage"] = decision.Message; + } + + context.Result = new RedirectToActionResult("Subscription", "ManageAccount", null); + } +} diff --git a/PlotLine/Services/SubscriptionServices.cs b/PlotLine/Services/SubscriptionServices.cs index 8d792f83..d034d721 100644 --- a/PlotLine/Services/SubscriptionServices.cs +++ b/PlotLine/Services/SubscriptionServices.cs @@ -13,10 +13,16 @@ public interface ISubscriptionService Task CanCreateChapterAsync(int bookId, int userId); Task CanCreateSceneAsync(int bookId, int userId); Task CanCreateCharacterAsync(int projectId, int userId); + Task CanCreateCharactersAsync(int projectId, int userId, int additionalCount); Task CanInviteCollaboratorAsync(int userId); Task GetStorageUsageAsync(int userId); Task GetUsageSummaryAsync(int userId); Task CanUploadFileAsync(int userId, long fileSizeBytes); + Task GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null); + Task CanUseFeatureAsync(int userId, SubscriptionFeature feature, DateTime? utcNow = null); + Task ReserveBookSlotsAsync(int userId, int requestedSlots = 1, DateTime? utcNow = null); + Task ReleaseBookSlotReservationAsync(Guid reservationId); + Task CanUseResourcesAsync(int userId, SubscriptionResourceRequest request, DateTime? utcNow = null); } public sealed class SubscriptionService(ISubscriptionRepository subscriptions, IUserFileRepository userFiles) : ISubscriptionService @@ -40,42 +46,52 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I public async Task CanCreateBookAsync(int userId) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); var currentUsage = await subscriptions.GetOwnedBookCountAsync(userId); return Evaluate(subscription, currentUsage, subscription.MaxBooks, "books"); } public async Task CanCreateChapterAsync(int bookId, int userId) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); var currentUsage = await subscriptions.GetChapterCountForBookAsync(bookId); return Evaluate(subscription, currentUsage, subscription.MaxChaptersPerBook, "chapters per book"); } public async Task CanCreateSceneAsync(int bookId, int userId) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); var currentUsage = await subscriptions.GetSceneCountForBookAsync(bookId); return Evaluate(subscription, currentUsage, subscription.MaxScenesPerBook, "scenes per book"); } public async Task CanCreateCharacterAsync(int projectId, int userId) + => await CanCreateCharactersAsync(projectId, userId, 1); + + public async Task CanCreateCharactersAsync(int projectId, int userId, int additionalCount) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); var currentUsage = await subscriptions.GetCharacterCountForProjectAsync(projectId); - return Evaluate(subscription, currentUsage, subscription.MaxCharactersPerProject, "characters per project"); + 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 CanInviteCollaboratorAsync(int userId) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); var currentUsage = await subscriptions.GetCollaboratorCountForOwnerAsync(userId); return Evaluate(subscription, currentUsage, subscription.MaxCollaborators, "collaborators"); } public async Task GetStorageUsageAsync(int userId) { - var subscription = await GetRequiredSubscriptionAsync(userId); + var subscription = await GetRequiredEffectiveLevelAsync(userId); return new StorageUsage { UsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId), @@ -85,7 +101,9 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I public async Task GetUsageSummaryAsync(int userId) { - var subscription = await GetRequiredSubscriptionAsync(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); @@ -103,18 +121,143 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I return StorageLimitResult.Blocked(usage.UsedBytes, usage.MaximumBytes, fileSizeBytes); } - private async Task GetRequiredSubscriptionAsync(int userId) + public async Task GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null) { - var subscription = await subscriptions.GetCurrentSubscriptionAsync(userId); - if (subscription is null) + var now = utcNow ?? DateTime.UtcNow; + var subscription = await subscriptions.GetSubscriptionForEntitlementAsync(userId); + var activeOverride = await subscriptions.GetActiveOverrideAsync(userId, now); + if (activeOverride is not null) { - throw new SubscriptionLimitException("No active subscription is assigned to your account."); + 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." + }; + } } - return subscription; + 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." + }; } - private static SubscriptionLimitResult Evaluate(UserSubscriptionDetail subscription, int currentUsage, int maximumAllowed, string limitName) + public async Task 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 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 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 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) { @@ -127,6 +270,42 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I $"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) diff --git a/PlotLine/Services/ToolbarCommands.cs b/PlotLine/Services/ToolbarCommands.cs index 091ea634..037caf09 100644 --- a/PlotLine/Services/ToolbarCommands.cs +++ b/PlotLine/Services/ToolbarCommands.cs @@ -28,6 +28,7 @@ public static class ToolbarCommands new("calendar", "Calendar", "M4 5h16v16H4z M4 10h16 M8 3v4 M16 3v4 M8 14h2 M14 14h2 M8 18h2", "StoryCalendar", "Index", "Calendar", true), new("characters", "Characters", "M9 3a3 3 0 1 0 0 6 3 3 0 0 0 0-6 M3 21v-4a6 6 0 0 1 12 0v4 M17 4a3 3 0 0 1 0 6 M18 13a5 5 0 0 1 3 5v3", "Characters", "Index", "Characters", true), new("threads", "Threads", "M4 3v18 M4 7h8l6 10h3 M4 17h8l6-10h3", "PlotThreads", "Index", "Threads", true), + new("plotlines", "Plot Lines", "M3 5h6l3 4 3-4h6 M3 12h5l4 4 4-4h5 M3 19h8l3-3 3 3h4", "PlotLineWorkspace", "Index", "Plot Lines", true), new("relationships", "Relationships", "M4 4h5v5H4z M15 15h5v5h-5z M15 4h5v5h-5z M9 6h6 M6 9v8h9", "RelationshipMap", "Index", "Relationships", true), new("review", "Review Centre", "M5 3h14v18H5z M8 8l2 2 5-5 M8 14h8 M8 18h6", "Onboarding", "StoryIntelligenceBookReviewCentre", "Review", true, RequiresBook: true), new("locations", "Locations", "M12 21s7-7 7-12a7 7 0 0 0-14 0c0 5 7 12 7 12 M12 6a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "Locations", "Index", "Locations"), diff --git a/PlotLine/Services/WordCompanionService.cs b/PlotLine/Services/WordCompanionService.cs index 98baa4c1..31e92af6 100644 --- a/PlotLine/Services/WordCompanionService.cs +++ b/PlotLine/Services/WordCompanionService.cs @@ -41,7 +41,8 @@ public sealed class WordCompanionService( IWordCompanionRepository repository, IManuscriptDocumentRepository manuscriptDocuments, ICurrentUserService currentUser, - INameIntelligenceService nameIntelligence) : IWordCompanionService + INameIntelligenceService nameIntelligence, + ISubscriptionService subscriptions) : IWordCompanionService { private const int CharacterDiscoveryMinimumMentions = 2; private const int CharacterCreationSelectionLimit = 250; @@ -133,15 +134,32 @@ public sealed class WordCompanionService( return new WordCompanionBooksResponse { Books = books }; } - public Task CreateBookAsync(int projectId, WordCompanionCreateBookRequest request) + public async Task CreateBookAsync(int projectId, WordCompanionCreateBookRequest request) { if (projectId <= 0 || string.IsNullOrWhiteSpace(request.Title)) { - return Task.FromResult(null); + return null; } request.Title = request.Title.Trim(); - return repository.CreateBookAsync(projectId, RequireUserId(), request); + var userId = RequireUserId(); + var reservation = await subscriptions.ReserveBookSlotsAsync(userId); + if (!reservation.Allowed) + { + throw new SubscriptionLimitException(reservation.Message); + } + + try + { + return await repository.CreateBookAsync(projectId, userId, request); + } + finally + { + if (reservation.ReservationID.HasValue) + { + await subscriptions.ReleaseBookSlotReservationAsync(reservation.ReservationID.Value); + } + } } public Task GetBookStructureAsync(int bookId) @@ -183,7 +201,7 @@ public sealed class WordCompanionService( } request.Title = request.Title.Trim(); - return repository.CreateChapterAsync(bookId, RequireUserId(), request); + return CreateChapterWithEntitlementAsync(bookId, request); } public Task CreateSceneAsync(int bookId, int chapterId, WordCompanionCreateSceneRequest request) @@ -194,10 +212,24 @@ public sealed class WordCompanionService( } request.SceneTitle = request.SceneTitle.Trim(); - return repository.CreateSceneAsync(bookId, chapterId, RequireUserId(), request); + return CreateSceneWithEntitlementAsync(bookId, chapterId, request); } - public Task SyncSceneAsync(int bookId, WordCompanionSyncSceneRequest request) + private async Task CreateChapterWithEntitlementAsync(int bookId, WordCompanionCreateChapterRequest request) + { + var userId = RequireUserId(); + await SubscriptionLimitGuards.EnsureAllowedAsync(id => subscriptions.CanCreateChapterAsync(bookId, id), userId); + return await repository.CreateChapterAsync(bookId, userId, request); + } + + private async Task CreateSceneWithEntitlementAsync(int bookId, int chapterId, WordCompanionCreateSceneRequest request) + { + var userId = RequireUserId(); + await SubscriptionLimitGuards.EnsureAllowedAsync(id => subscriptions.CanCreateSceneAsync(bookId, id), userId); + return await repository.CreateSceneAsync(bookId, chapterId, userId, request); + } + + public async Task SyncSceneAsync(int bookId, WordCompanionSyncSceneRequest request) { if (bookId <= 0 || string.IsNullOrWhiteSpace(request.ChapterTitle) @@ -206,15 +238,24 @@ public sealed class WordCompanionService( || request.ChapterSortOrder is <= 0 || request.SceneSortOrder is <= 0) { - return Task.FromResult(null); + return null; } request.ChapterTitle = request.ChapterTitle.Trim(); request.SceneTitle = request.SceneTitle.Trim(); - return repository.SyncSceneAsync(bookId, RequireUserId(), request); + await EnsureSyncResourcesAsync(bookId, + [ + new WordCompanionSyncChapterRequest + { + Title = request.ChapterTitle, + SortOrder = request.ChapterSortOrder, + Scenes = [new WordCompanionSyncManuscriptSceneRequest { Title = request.SceneTitle, SortOrder = request.SceneSortOrder }] + } + ]); + return await repository.SyncSceneAsync(bookId, RequireUserId(), request); } - public Task SyncManuscriptAsync(int bookId, WordCompanionSyncManuscriptRequest request) + public async Task SyncManuscriptAsync(int bookId, WordCompanionSyncManuscriptRequest request) { if (bookId <= 0 || request.Chapters.Any(chapter => string.IsNullOrWhiteSpace(chapter.Title) @@ -222,7 +263,7 @@ public sealed class WordCompanionService( || chapter.SortOrder is <= 0 || chapter.Scenes.Any(scene => string.IsNullOrWhiteSpace(scene.Title) || scene.WordCount < 0 || scene.SortOrder is <= 0))) { - return Task.FromResult(null); + return null; } foreach (var chapter in request.Chapters) @@ -234,7 +275,8 @@ public sealed class WordCompanionService( } } - return repository.SyncManuscriptAsync(bookId, RequireUserId(), request); + await EnsureSyncResourcesAsync(bookId, request.Chapters); + return await repository.SyncManuscriptAsync(bookId, RequireUserId(), request); } public Task UpdateSceneLinksAsync(int sceneId, WordCompanionUpdateSceneLinksRequest request) @@ -593,11 +635,11 @@ public sealed class WordCompanionService( private static string FirstName(string? value) => (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty; - public Task CreateDiscoveredCharactersAsync(WordCompanionCreateDiscoveredCharactersRequest request) + public async Task CreateDiscoveredCharactersAsync(WordCompanionCreateDiscoveredCharactersRequest request) { if (request.ProjectId <= 0 || request.CandidateNames.Count == 0) { - return Task.FromResult(null); + return null; } request.CandidateNames = request.CandidateNames @@ -607,9 +649,14 @@ public sealed class WordCompanionService( .Take(CharacterCreationSelectionLimit) .ToList(); - return request.CandidateNames.Count == 0 - ? Task.FromResult(null) - : repository.CreateDiscoveredCharactersAsync(RequireUserId(), request); + if (request.CandidateNames.Count == 0) + { + return null; + } + + var userId = RequireUserId(); + await SubscriptionLimitGuards.EnsureAllowedAsync(id => subscriptions.CanCreateCharactersAsync(request.ProjectId, id, request.CandidateNames.Count), userId); + return await repository.CreateDiscoveredCharactersAsync(userId, request); } private async Task ResolveSceneCoreAsync(int bookId, WordCompanionResolveSceneRequest request) @@ -617,6 +664,49 @@ public sealed class WordCompanionService( return await repository.ResolveSceneAsync(bookId, RequireUserId(), request.ChapterTitle!.Trim(), request.SceneTitle!.Trim()); } + private async Task EnsureSyncResourcesAsync(int bookId, IReadOnlyList requestedChapters) + { + var structure = await repository.GetBookStructureAsync(bookId, RequireUserId()); + if (structure is null) + { + return; + } + + var existingByTitle = structure.Chapters + .GroupBy(chapter => chapter.Title, StringComparer.OrdinalIgnoreCase) + .ToDictionary(group => group.Key, group => group.First(), StringComparer.OrdinalIgnoreCase); + var newChapterTitles = requestedChapters + .Select(chapter => chapter.Title?.Trim() ?? string.Empty) + .Where(title => !existingByTitle.ContainsKey(title)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + var projectedScenes = structure.Chapters.Sum(chapter => chapter.Scenes.Count); + foreach (var requested in requestedChapters) + { + var title = requested.Title?.Trim() ?? string.Empty; + if (!existingByTitle.TryGetValue(title, out var existing)) + { + projectedScenes += requested.Scenes.Select(scene => scene.Title?.Trim()).Where(scene => !string.IsNullOrWhiteSpace(scene)).Distinct(StringComparer.OrdinalIgnoreCase).Count(); + continue; + } + + var existingSceneTitles = existing.Scenes.Select(scene => scene.Title).ToHashSet(StringComparer.OrdinalIgnoreCase); + projectedScenes += requested.Scenes.Select(scene => scene.Title?.Trim()) + .Where(scene => !string.IsNullOrWhiteSpace(scene) && !existingSceneTitles.Contains(scene!)) + .Distinct(StringComparer.OrdinalIgnoreCase).Count(); + } + + var decision = await subscriptions.CanUseResourcesAsync(RequireUserId(), new SubscriptionResourceRequest + { + FinalChapterCounts = [structure.Chapters.Count + newChapterTitles.Count], + FinalSceneCounts = [projectedScenes] + }); + if (!decision.Allowed) + { + throw new SubscriptionLimitException(decision.Message); + } + } + private int RequireUserId() { return currentUser.UserId ?? throw new InvalidOperationException("An authenticated user is required."); diff --git a/PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql b/PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql new file mode 100644 index 00000000..855ef47e --- /dev/null +++ b/PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql @@ -0,0 +1,449 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO + +IF OBJECT_ID(N'dbo.SubscriptionOverride', N'U') IS NULL +BEGIN + CREATE TABLE dbo.SubscriptionOverride + ( + SubscriptionOverrideID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_SubscriptionOverride PRIMARY KEY, + UserID int NOT NULL, + SubscriptionLevelID int NOT NULL, + StartDateUTC datetime2 NOT NULL, + ExpiryDateUTC datetime2 NULL, + Reason nvarchar(1000) NOT NULL, + CreatedByUserID int NOT NULL, + CreatedDateUTC datetime2 NOT NULL CONSTRAINT DF_SubscriptionOverride_Created DEFAULT SYSUTCDATETIME(), + ModifiedByUserID int NOT NULL, + ModifiedDateUTC datetime2 NOT NULL CONSTRAINT DF_SubscriptionOverride_Modified DEFAULT SYSUTCDATETIME(), + RevokedDateUTC datetime2 NULL, + RevokedByUserID int NULL, + CONSTRAINT FK_SubscriptionOverride_User FOREIGN KEY (UserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT FK_SubscriptionOverride_Level FOREIGN KEY (SubscriptionLevelID) REFERENCES dbo.SubscriptionLevel(SubscriptionLevelID), + CONSTRAINT FK_SubscriptionOverride_CreatedBy FOREIGN KEY (CreatedByUserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT FK_SubscriptionOverride_ModifiedBy FOREIGN KEY (ModifiedByUserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT FK_SubscriptionOverride_RevokedBy FOREIGN KEY (RevokedByUserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT CK_SubscriptionOverride_Dates CHECK (ExpiryDateUTC IS NULL OR ExpiryDateUTC > StartDateUTC) + ); +END; +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo.SubscriptionOverride') AND name = N'IX_SubscriptionOverride_UserDates') + CREATE INDEX IX_SubscriptionOverride_UserDates ON dbo.SubscriptionOverride(UserID, RevokedDateUTC, StartDateUTC, ExpiryDateUTC); +GO + +IF OBJECT_ID(N'dbo.SubscriptionAdministrationAudit', N'U') IS NULL +BEGIN + CREATE TABLE dbo.SubscriptionAdministrationAudit + ( + SubscriptionAdministrationAuditID bigint IDENTITY(1,1) NOT NULL CONSTRAINT PK_SubscriptionAdministrationAudit PRIMARY KEY, + UserID int NOT NULL, + AdministratorUserID int NOT NULL, + ActionName nvarchar(100) NOT NULL, + PreviousState nvarchar(max) NULL, + NewState nvarchar(max) NULL, + Reason nvarchar(1000) NOT NULL, + CreatedDateUTC datetime2 NOT NULL CONSTRAINT DF_SubscriptionAdministrationAudit_Created DEFAULT SYSUTCDATETIME(), + CONSTRAINT FK_SubscriptionAdministrationAudit_User FOREIGN KEY (UserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT FK_SubscriptionAdministrationAudit_Admin FOREIGN KEY (AdministratorUserID) REFERENCES dbo.AppUser(UserID) + ); +END; +GO + +IF OBJECT_ID(N'dbo.SubscriptionBookSlotReservation', N'U') IS NULL +BEGIN + CREATE TABLE dbo.SubscriptionBookSlotReservation + ( + ReservationID uniqueidentifier NOT NULL CONSTRAINT PK_SubscriptionBookSlotReservation PRIMARY KEY, + UserID int NOT NULL, + SlotCount int NOT NULL, + CreatedDateUTC datetime2 NOT NULL, + ExpiresDateUTC datetime2 NOT NULL, + CONSTRAINT FK_SubscriptionBookSlotReservation_User FOREIGN KEY (UserID) REFERENCES dbo.AppUser(UserID), + CONSTRAINT CK_SubscriptionBookSlotReservation_Count CHECK (SlotCount > 0) + ); + CREATE INDEX IX_SubscriptionBookSlotReservation_UserExpiry ON dbo.SubscriptionBookSlotReservation(UserID, ExpiresDateUTC); +END; +GO + +-- Historical Draft Desk rows were presented as 30-day trials but were stored as permanent non-trials. +-- Materialise the already-advertised expiry without deleting or hiding any user data. +UPDATE us +SET IsTrial = 1, + TrialExpiryDateUTC = DATEADD(day, 30, us.StartDateUTC), + ModifiedDateUTC = SYSUTCDATETIME() +FROM dbo.UserSubscription us +INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID +WHERE sl.Name = N'DraftDesk' + AND us.StripeSubscriptionId IS NULL + AND us.TrialExpiryDateUTC IS NULL; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionOverride_GetActive + @UserID int, + @UtcNow datetime2 +AS +BEGIN + SET NOCOUNT ON; + SELECT TOP (1) so.SubscriptionOverrideID, so.UserID, so.SubscriptionLevelID, so.StartDateUTC, + so.ExpiryDateUTC, so.Reason, so.CreatedByUserID, so.CreatedDateUTC, so.ModifiedByUserID, + so.ModifiedDateUTC, so.RevokedDateUTC, so.RevokedByUserID, + sl.Name AS LevelName, sl.DisplayName AS LevelDisplayName + FROM dbo.SubscriptionOverride so + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = so.SubscriptionLevelID + WHERE so.UserID = @UserID + AND so.RevokedDateUTC IS NULL + AND so.StartDateUTC <= @UtcNow + AND (so.ExpiryDateUTC IS NULL OR so.ExpiryDateUTC > @UtcNow) + AND sl.IsActive = 1 + ORDER BY so.StartDateUTC DESC, so.SubscriptionOverrideID DESC; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.UserSubscription_GetForEntitlement + @UserID int +AS +BEGIN + SET NOCOUNT ON; + SELECT TOP (1) us.UserSubscriptionID, us.UserID, us.SubscriptionLevelID, us.StartDateUTC, us.EndDateUTC, + us.IsActive, us.IsTrial, us.TrialExpiryDateUTC, us.CreatedDateUTC, us.ModifiedDateUTC, + us.StripeCustomerId, us.StripeSubscriptionId, us.StripePriceId, us.BillingInterval, us.StripeStatus, + us.CurrentPeriodStartUTC, us.CurrentPeriodEndUTC, us.CancelAtPeriodEnd, us.CancelledDateUTC, + us.LastPaymentFailureDateUTC, us.LastStripeEventId, + sl.Name, sl.DisplayName, sl.Description, sl.MaxBooks, sl.MaxChaptersPerBook, + sl.MaxScenesPerBook, sl.MaxCharactersPerProject, sl.MaxStorageMB, sl.MaxCollaborators, + sl.IsActive AS SubscriptionLevelIsActive, sl.SortOrder, sl.StripeMonthlyPriceId, + sl.StripeAnnualPriceId, sl.RequiresStripeSubscription, sl.MonthlyPricePence, + sl.AnnualPricePence, sl.CurrencyCode + FROM dbo.UserSubscription us + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID + WHERE us.UserID = @UserID + ORDER BY us.IsActive DESC, us.UserSubscriptionID DESC; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionEntitlement_TryReserveBookSlots + @UserID int, + @RequestedSlots int, + @UtcNow datetime2 +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + IF @RequestedSlots <= 0 + BEGIN + SELECT CAST(1 AS bit) Allowed, CAST(NULL AS uniqueidentifier) ReservationID, 0 CurrentUsage, 0 MaximumAllowed, N'' Message; + RETURN; + END; + + BEGIN TRANSACTION; + DECLARE @LockResult int; + DECLARE @LockResource nvarchar(255) = CONCAT(N'PlotDirector:BookSlots:', @UserID); + EXEC @LockResult = sys.sp_getapplock @Resource = @LockResource, @LockMode = N'Exclusive', @LockOwner = N'Transaction', @LockTimeout = 10000; + IF @LockResult < 0 + BEGIN + ROLLBACK; + THROW 51040, 'Book entitlement could not be checked safely. Please try again.', 1; + END; + + DELETE FROM dbo.SubscriptionBookSlotReservation WHERE ExpiresDateUTC <= @UtcNow; + + DECLARE @LevelID int, @MaxBooks int, @PlanName nvarchar(100), @Active bit = 0; + SELECT TOP (1) @LevelID = so.SubscriptionLevelID, @MaxBooks = sl.MaxBooks, @PlanName = sl.DisplayName, @Active = 1 + FROM dbo.SubscriptionOverride so + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = so.SubscriptionLevelID AND sl.IsActive = 1 + WHERE so.UserID = @UserID AND so.RevokedDateUTC IS NULL AND so.StartDateUTC <= @UtcNow + AND (so.ExpiryDateUTC IS NULL OR so.ExpiryDateUTC > @UtcNow) + ORDER BY so.StartDateUTC DESC, so.SubscriptionOverrideID DESC; + + IF @LevelID IS NULL + BEGIN + SELECT TOP (1) @LevelID = us.SubscriptionLevelID, @MaxBooks = sl.MaxBooks, @PlanName = sl.DisplayName, + @Active = CASE + WHEN us.IsActive = 0 OR sl.IsActive = 0 OR us.StartDateUTC > @UtcNow OR (us.EndDateUTC IS NOT NULL AND us.EndDateUTC <= @UtcNow) THEN 0 + WHEN (us.IsTrial = 1 OR (sl.RequiresStripeSubscription = 0 AND us.StripeSubscriptionId IS NULL)) + THEN CASE WHEN COALESCE(us.TrialExpiryDateUTC, DATEADD(day, 30, us.StartDateUTC)) > @UtcNow THEN 1 ELSE 0 END + WHEN LOWER(COALESCE(us.StripeStatus, N'')) IN (N'canceled', N'cancelled', N'incomplete_expired', N'ended', N'expired', N'inactive', N'unpaid') + AND us.CurrentPeriodEndUTC IS NOT NULL AND us.CurrentPeriodEndUTC <= @UtcNow THEN 0 + ELSE 1 END + FROM dbo.UserSubscription us + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID + WHERE us.UserID = @UserID AND us.IsActive = 1 + ORDER BY us.UserSubscriptionID DESC; + END; + + DECLARE @CurrentUsage int = + ( + SELECT COUNT(DISTINCT b.BookID) + FROM dbo.Books b + INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID + WHERE pua.UserID = @UserID AND pua.AccessRole = N'Owner' AND pua.IsActive = 1 + AND p.IsArchived = 0 AND b.IsArchived = 0 + ); + DECLARE @Reserved int = COALESCE((SELECT SUM(SlotCount) FROM dbo.SubscriptionBookSlotReservation WHERE UserID = @UserID AND ExpiresDateUTC > @UtcNow), 0); + + IF @Active = 0 OR @LevelID IS NULL + BEGIN + COMMIT; + SELECT CAST(0 AS bit) Allowed, CAST(NULL AS uniqueidentifier) ReservationID, @CurrentUsage CurrentUsage, + COALESCE(@MaxBooks, 0) MaximumAllowed, + N'Your trial or subscription is inactive. Existing work remains available to read and export.' Message; + RETURN; + END; + + IF @MaxBooks < 999999 AND @CurrentUsage + @Reserved + @RequestedSlots > @MaxBooks + BEGIN + COMMIT; + SELECT CAST(0 AS bit) Allowed, CAST(NULL AS uniqueidentifier) ReservationID, @CurrentUsage CurrentUsage, @MaxBooks MaximumAllowed, + CONCAT(N'You have reached the maximum number of books allowed by your ', @PlanName, N' subscription (', @MaxBooks, N'). Upgrade your subscription to add more.') Message; + RETURN; + END; + + DECLARE @ReservationID uniqueidentifier = NEWID(); + INSERT dbo.SubscriptionBookSlotReservation (ReservationID, UserID, SlotCount, CreatedDateUTC, ExpiresDateUTC) + VALUES (@ReservationID, @UserID, @RequestedSlots, @UtcNow, DATEADD(minute, 15, @UtcNow)); + COMMIT; + SELECT CAST(1 AS bit) Allowed, @ReservationID ReservationID, @CurrentUsage CurrentUsage, @MaxBooks MaximumAllowed, N'' Message; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionEntitlement_ReleaseBookSlots + @ReservationID uniqueidentifier +AS +BEGIN + SET NOCOUNT ON; + DELETE FROM dbo.SubscriptionBookSlotReservation WHERE ReservationID = @ReservationID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionAdmin_SearchUsers + @Search nvarchar(256) = NULL, + @MaximumRows int = 50 +AS +BEGIN + SET NOCOUNT ON; + SET @Search = NULLIF(LTRIM(RTRIM(@Search)), N''); + SELECT TOP (@MaximumRows) u.UserID, u.Email, u.DisplayName, sl.DisplayName AS UnderlyingPlanName, + us.IsTrial, us.TrialExpiryDateUTC, us.StripeStatus + FROM dbo.AppUser u + LEFT JOIN dbo.UserSubscription us ON us.UserID = u.UserID AND us.IsActive = 1 + LEFT JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID + WHERE @Search IS NULL OR u.Email LIKE N'%' + @Search + N'%' OR u.DisplayName LIKE N'%' + @Search + N'%' + ORDER BY u.Email; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionAdmin_ExtendTrial + @UserID int, + @TrialExpiryDateUTC datetime2, + @AdministratorUserID int, + @Reason nvarchar(1000) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + IF NULLIF(LTRIM(RTRIM(@Reason)), N'') IS NULL THROW 51041, 'A reason is required.', 1; + DECLARE @Previous nvarchar(max) = (SELECT UserSubscriptionID, IsTrial, TrialExpiryDateUTC FROM dbo.UserSubscription WHERE UserID = @UserID AND IsActive = 1 FOR JSON PATH, WITHOUT_ARRAY_WRAPPER); + UPDATE us SET IsTrial = 1, TrialExpiryDateUTC = @TrialExpiryDateUTC, ModifiedDateUTC = SYSUTCDATETIME() + FROM dbo.UserSubscription us + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID + WHERE us.UserID = @UserID AND us.IsActive = 1 AND sl.RequiresStripeSubscription = 0 AND us.StripeSubscriptionId IS NULL; + IF @@ROWCOUNT = 0 THROW 51042, 'The selected account does not have an application-managed trial.', 1; + DECLARE @New nvarchar(max) = (SELECT UserSubscriptionID, IsTrial, TrialExpiryDateUTC FROM dbo.UserSubscription WHERE UserID = @UserID AND IsActive = 1 FOR JSON PATH, WITHOUT_ARRAY_WRAPPER); + INSERT dbo.SubscriptionAdministrationAudit (UserID, AdministratorUserID, ActionName, PreviousState, NewState, Reason) + VALUES (@UserID, @AdministratorUserID, N'Trial expiry changed', @Previous, @New, @Reason); +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionAdmin_SaveOverride + @UserID int, + @SubscriptionLevelID int, + @StartDateUTC datetime2, + @ExpiryDateUTC datetime2 = NULL, + @Reason nvarchar(1000), + @AdministratorUserID int +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + IF NULLIF(LTRIM(RTRIM(@Reason)), N'') IS NULL THROW 51041, 'A reason is required.', 1; + IF @ExpiryDateUTC IS NOT NULL AND @ExpiryDateUTC <= @StartDateUTC THROW 51043, 'Override expiry must be after its start.', 1; + IF NOT EXISTS (SELECT 1 FROM dbo.SubscriptionLevel WHERE SubscriptionLevelID = @SubscriptionLevelID AND IsActive = 1) THROW 51044, 'Select an active subscription level.', 1; + DECLARE @Previous nvarchar(max) = (SELECT * FROM dbo.SubscriptionOverride WHERE UserID = @UserID AND RevokedDateUTC IS NULL FOR JSON PATH); + UPDATE dbo.SubscriptionOverride SET RevokedDateUTC = SYSUTCDATETIME(), RevokedByUserID = @AdministratorUserID, + ModifiedDateUTC = SYSUTCDATETIME(), ModifiedByUserID = @AdministratorUserID + WHERE UserID = @UserID AND RevokedDateUTC IS NULL; + INSERT dbo.SubscriptionOverride (UserID, SubscriptionLevelID, StartDateUTC, ExpiryDateUTC, Reason, CreatedByUserID, ModifiedByUserID) + VALUES (@UserID, @SubscriptionLevelID, @StartDateUTC, @ExpiryDateUTC, @Reason, @AdministratorUserID, @AdministratorUserID); + DECLARE @New nvarchar(max) = (SELECT TOP (1) * FROM dbo.SubscriptionOverride WHERE UserID = @UserID ORDER BY SubscriptionOverrideID DESC FOR JSON PATH, WITHOUT_ARRAY_WRAPPER); + INSERT dbo.SubscriptionAdministrationAudit (UserID, AdministratorUserID, ActionName, PreviousState, NewState, Reason) + VALUES (@UserID, @AdministratorUserID, N'Entitlement override granted', @Previous, @New, @Reason); +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SubscriptionAdmin_RevokeOverride + @UserID int, + @AdministratorUserID int, + @Reason nvarchar(1000) +AS +BEGIN + SET NOCOUNT ON; + IF NULLIF(LTRIM(RTRIM(@Reason)), N'') IS NULL THROW 51041, 'A reason is required.', 1; + DECLARE @Previous nvarchar(max) = (SELECT * FROM dbo.SubscriptionOverride WHERE UserID = @UserID AND RevokedDateUTC IS NULL FOR JSON PATH); + UPDATE dbo.SubscriptionOverride SET RevokedDateUTC = SYSUTCDATETIME(), RevokedByUserID = @AdministratorUserID, + ModifiedDateUTC = SYSUTCDATETIME(), ModifiedByUserID = @AdministratorUserID + WHERE UserID = @UserID AND RevokedDateUTC IS NULL; + INSERT dbo.SubscriptionAdministrationAudit (UserID, AdministratorUserID, ActionName, PreviousState, NewState, Reason) + VALUES (@UserID, @AdministratorUserID, N'Entitlement override revoked', @Previous, N'{}', @Reason); +END; +GO + +CREATE OR ALTER PROCEDURE dbo.User_Create + @Email nvarchar(256), + @DisplayName nvarchar(200), + @PasswordHash nvarchar(max), + @EmailConfirmed bit = 0 +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + INSERT dbo.AppUser (Email, DisplayName, PasswordHash, EmailConfirmed) + VALUES (@Email, @DisplayName, @PasswordHash, @EmailConfirmed); + DECLARE @UserID int = SCOPE_IDENTITY(); + DECLARE @DraftDeskID int = (SELECT SubscriptionLevelID FROM dbo.SubscriptionLevel WHERE Name = N'DraftDesk' AND IsActive = 1); + IF @DraftDeskID IS NULL THROW 51045, 'The trial subscription level is not configured.', 1; + INSERT dbo.UserSubscription (UserID, SubscriptionLevelID, StartDateUTC, IsActive, IsTrial, TrialExpiryDateUTC) + VALUES (@UserID, @DraftDeskID, SYSUTCDATETIME(), 1, 1, DATEADD(day, 30, SYSUTCDATETIME())); + COMMIT; + EXEC dbo.User_GetById @UserID = @UserID; +END; +GO + +CREATE OR ALTER FUNCTION dbo.SubscriptionEntitlement_ResourceLimits +( + @UserID int, + @UtcNow datetime2 +) +RETURNS @Result TABLE +( + IsActive bit NOT NULL, + MaxBooks int NOT NULL, + MaxChaptersPerBook int NOT NULL, + MaxScenesPerBook int NOT NULL, + MaxCharactersPerProject int NOT NULL +) +AS +BEGIN + INSERT @Result + SELECT TOP (1) CAST(1 AS bit), sl.MaxBooks, sl.MaxChaptersPerBook, sl.MaxScenesPerBook, sl.MaxCharactersPerProject + FROM dbo.SubscriptionOverride so + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = so.SubscriptionLevelID AND sl.IsActive = 1 + WHERE so.UserID = @UserID AND so.RevokedDateUTC IS NULL AND so.StartDateUTC <= @UtcNow + AND (so.ExpiryDateUTC IS NULL OR so.ExpiryDateUTC > @UtcNow) + ORDER BY so.StartDateUTC DESC, so.SubscriptionOverrideID DESC; + + IF NOT EXISTS (SELECT 1 FROM @Result) + BEGIN + INSERT @Result + SELECT TOP (1) + CAST(CASE + WHEN us.IsActive = 0 OR sl.IsActive = 0 OR us.StartDateUTC > @UtcNow OR (us.EndDateUTC IS NOT NULL AND us.EndDateUTC <= @UtcNow) THEN 0 + WHEN (us.IsTrial = 1 OR (sl.RequiresStripeSubscription = 0 AND us.StripeSubscriptionId IS NULL)) + THEN CASE WHEN COALESCE(us.TrialExpiryDateUTC, DATEADD(day, 30, us.StartDateUTC)) > @UtcNow THEN 1 ELSE 0 END + WHEN LOWER(COALESCE(us.StripeStatus, N'')) IN (N'canceled', N'cancelled', N'incomplete_expired', N'ended', N'expired', N'inactive', N'unpaid') + AND us.CurrentPeriodEndUTC IS NOT NULL AND us.CurrentPeriodEndUTC <= @UtcNow THEN 0 + ELSE 1 END AS bit), + sl.MaxBooks, sl.MaxChaptersPerBook, sl.MaxScenesPerBook, sl.MaxCharactersPerProject + FROM dbo.UserSubscription us + INNER JOIN dbo.SubscriptionLevel sl ON sl.SubscriptionLevelID = us.SubscriptionLevelID + WHERE us.UserID = @UserID AND us.IsActive = 1 + ORDER BY us.UserSubscriptionID DESC; + END; + RETURN; +END; +GO + +CREATE OR ALTER TRIGGER dbo.TR_Books_EnforceSubscriptionInsert +ON dbo.Books +AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + DECLARE @UserID int, @Max int, @Active bit, @LockResult int, @Resource nvarchar(255); + DECLARE owners CURSOR LOCAL FAST_FORWARD FOR + SELECT DISTINCT pua.UserID FROM inserted i + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=i.ProjectID AND pua.AccessRole=N'Owner' AND pua.IsActive=1; + OPEN owners; FETCH NEXT FROM owners INTO @UserID; + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @Resource = CONCAT(N'PlotDirector:BookSlots:', @UserID); + EXEC @LockResult=sys.sp_getapplock @Resource=@Resource,@LockMode=N'Exclusive',@LockOwner=N'Transaction',@LockTimeout=10000; + IF @LockResult < 0 THROW 51040, 'Book entitlement could not be checked safely. Please try again.', 1; + SELECT @Active=IsActive,@Max=MaxBooks FROM dbo.SubscriptionEntitlement_ResourceLimits(@UserID,SYSUTCDATETIME()); + IF COALESCE(@Active,0)=0 THROW 51046, 'An active trial or subscription is required to create a book.', 1; + IF (SELECT COUNT(DISTINCT b.BookID) FROM dbo.Books b INNER JOIN dbo.Projects p ON p.ProjectID=b.ProjectID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=p.ProjectID AND pua.UserID=@UserID AND pua.AccessRole=N'Owner' AND pua.IsActive=1 + WHERE p.IsArchived=0 AND b.IsArchived=0) > @Max + THROW 51047, 'The subscription book limit has been reached.', 1; + FETCH NEXT FROM owners INTO @UserID; + END; + CLOSE owners; DEALLOCATE owners; +END; +GO + +CREATE OR ALTER TRIGGER dbo.TR_Chapters_EnforceSubscriptionInsert +ON dbo.Chapters +AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + IF EXISTS + ( + SELECT 1 FROM (SELECT DISTINCT BookID FROM inserted) i + INNER JOIN dbo.Books b ON b.BookID=i.BookID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=b.ProjectID AND pua.AccessRole=N'Owner' AND pua.IsActive=1 + OUTER APPLY dbo.SubscriptionEntitlement_ResourceLimits(pua.UserID,SYSUTCDATETIME()) limits + WHERE COALESCE(limits.IsActive,0)=0 OR + (SELECT COUNT(*) FROM dbo.Chapters c WHERE c.BookID=i.BookID AND c.IsArchived=0) > limits.MaxChaptersPerBook + ) THROW 51048, 'An active entitlement and available chapter allowance are required.', 1; +END; +GO + +CREATE OR ALTER TRIGGER dbo.TR_Scenes_EnforceSubscriptionInsert +ON dbo.Scenes +AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + IF EXISTS + ( + SELECT 1 FROM (SELECT DISTINCT c.BookID FROM inserted i INNER JOIN dbo.Chapters c ON c.ChapterID=i.ChapterID) affected + INNER JOIN dbo.Books b ON b.BookID=affected.BookID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=b.ProjectID AND pua.AccessRole=N'Owner' AND pua.IsActive=1 + OUTER APPLY dbo.SubscriptionEntitlement_ResourceLimits(pua.UserID,SYSUTCDATETIME()) limits + WHERE COALESCE(limits.IsActive,0)=0 OR + (SELECT COUNT(*) FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID + WHERE c.BookID=affected.BookID AND c.IsArchived=0 AND s.IsArchived=0) > limits.MaxScenesPerBook + ) THROW 51049, 'An active entitlement and available scene allowance are required.', 1; +END; +GO + +CREATE OR ALTER TRIGGER dbo.TR_Characters_EnforceSubscriptionInsert +ON dbo.Characters +AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + IF EXISTS + ( + SELECT 1 FROM (SELECT DISTINCT ProjectID FROM inserted) i + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=i.ProjectID AND pua.AccessRole=N'Owner' AND pua.IsActive=1 + OUTER APPLY dbo.SubscriptionEntitlement_ResourceLimits(pua.UserID,SYSUTCDATETIME()) limits + WHERE COALESCE(limits.IsActive,0)=0 OR + (SELECT COUNT(*) FROM dbo.Characters c WHERE c.ProjectID=i.ProjectID AND c.IsArchived=0) > limits.MaxCharactersPerProject + ) THROW 51050, 'An active entitlement and available character allowance are required.', 1; +END; +GO diff --git a/PlotLine/Sql/204_PlotLineWorkspaceV1.sql b/PlotLine/Sql/204_PlotLineWorkspaceV1.sql new file mode 100644 index 00000000..28464bdf --- /dev/null +++ b/PlotLine/Sql/204_PlotLineWorkspaceV1.sql @@ -0,0 +1,294 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO + +CREATE OR ALTER PROCEDURE dbo.PlotLineWorkspace_Get + @ProjectID int, + @BookID int = NULL, + @ScenarioID int = NULL +AS +BEGIN + SET NOCOUNT ON; + + IF @ScenarioID IS NOT NULL AND NOT EXISTS + ( + SELECT 1 + FROM dbo.Scenarios + WHERE ScenarioID = @ScenarioID + AND ProjectID = @ProjectID + AND IsArchived = 0 + AND (@BookID IS NULL OR BookID IS NULL OR BookID = @BookID) + ) + SET @ScenarioID = NULL; + + CREATE TABLE #SceneOrder + ( + SceneID int NOT NULL PRIMARY KEY, + BookID int NOT NULL, + ChapterID int NOT NULL, + ChapterNumber decimal(10,2) NOT NULL, + ChapterTitle nvarchar(300) NULL, + SceneNumber decimal(10,2) NOT NULL, + SceneTitle nvarchar(300) NULL, + NarrativeOrder int NOT NULL + ); + + IF @ScenarioID IS NULL + BEGIN + INSERT #SceneOrder (SceneID, BookID, ChapterID, ChapterNumber, ChapterTitle, SceneNumber, SceneTitle, NarrativeOrder) + SELECT nso.SceneID, nso.BookID, nso.ChapterID, nso.ChapterNumber, nso.ChapterTitle, + nso.SceneNumber, nso.SceneTitle, + CASE WHEN @BookID IS NULL THEN CONVERT(int, nso.GlobalSceneIndex) ELSE CONVERT(int, nso.BookSceneIndex) END + FROM dbo.NarrativeSceneOrder nso + WHERE nso.ProjectID = @ProjectID AND (@BookID IS NULL OR nso.BookID = @BookID); + END + ELSE + BEGIN + INSERT #SceneOrder (SceneID, BookID, ChapterID, ChapterNumber, ChapterTitle, SceneNumber, SceneTitle, NarrativeOrder) + SELECT s.SceneID, b.BookID, c.ChapterID, c.ChapterNumber, c.ChapterTitle, s.SceneNumber, s.SceneTitle, + CONVERT(int, ROW_NUMBER() OVER + ( + ORDER BY b.SortOrder, b.BookNumber, c.SortOrder, c.ChapterNumber, + sso.ProposedSortOrder, s.SceneNumber, s.SceneID + )) + FROM dbo.ScenarioSceneOrder sso + INNER JOIN dbo.Scenes s ON s.SceneID = sso.SceneID AND s.IsArchived = 0 + INNER JOIN dbo.Chapters c ON c.ChapterID = ISNULL(sso.ProposedChapterID, s.ChapterID) AND c.IsArchived = 0 + INNER JOIN dbo.Books b ON b.BookID = c.BookID AND b.IsArchived = 0 + WHERE sso.ScenarioID = @ScenarioID + AND b.ProjectID = @ProjectID + AND (@BookID IS NULL OR b.BookID = @BookID); + END; + + SELECT pl.PlotLineID, pl.ProjectID, pl.BookID, pl.PlotLineName, pl.Description, + plt.TypeName AS PlotLineTypeName, pi.ImportanceName AS PlotImportanceName, + pl.Colour, pl.SortOrder, + COUNT(DISTINCT pt.PlotThreadID) AS ThreadCount, + COUNT(DISTINCT CASE WHEN so.SceneID IS NOT NULL THEN te.SceneID END) AS ContributionSceneCount + FROM dbo.PlotLines pl + INNER JOIN dbo.PlotLineTypes plt ON plt.PlotLineTypeID = pl.PlotLineTypeID + INNER JOIN dbo.PlotImportance pi ON pi.PlotImportanceID = pl.PlotImportanceID + LEFT JOIN dbo.PlotThreads pt ON pt.PlotLineID = pl.PlotLineID AND pt.IsArchived = 0 + LEFT JOIN dbo.ThreadEvents te ON te.PlotThreadID = pt.PlotThreadID + LEFT JOIN #SceneOrder so ON so.SceneID = te.SceneID + WHERE pl.ProjectID = @ProjectID + AND pl.IsArchived = 0 + AND (@BookID IS NULL OR pl.BookID IS NULL OR pl.BookID = @BookID) + GROUP BY pl.PlotLineID, pl.ProjectID, pl.BookID, pl.PlotLineName, pl.Description, + plt.TypeName, pi.ImportanceName, pl.Colour, pl.SortOrder + ORDER BY pl.SortOrder, pl.PlotLineName, pl.PlotLineID; + + SELECT pt.PlotThreadID, pt.PlotLineID, pt.ThreadTitle, pt.Summary, + tt.TypeName AS ThreadTypeName, ts.StatusName AS ThreadStatusName, pt.Importance, + pt.IntroducedSceneID, + CASE WHEN intro.SceneID IS NULL THEN NULL ELSE CONCAT(N'Ch ', intro.ChapterNumber, N' · Scene ', intro.SceneNumber, N' · ', intro.SceneTitle) END AS IntroducedSceneLabel, + pt.PlannedResolutionSceneID, + CASE WHEN planned.SceneID IS NULL THEN NULL ELSE CONCAT(N'Ch ', planned.ChapterNumber, N' · Scene ', planned.SceneNumber, N' · ', planned.SceneTitle) END AS PlannedResolutionSceneLabel, + pt.ActualResolutionSceneID, + CASE WHEN actual.SceneID IS NULL THEN NULL ELSE CONCAT(N'Ch ', actual.ChapterNumber, N' · Scene ', actual.SceneNumber, N' · ', actual.SceneTitle) END AS ActualResolutionSceneLabel, + COUNT(CASE WHEN eventOrder.SceneID IS NOT NULL THEN te.ThreadEventID END) AS ContributionCount + FROM dbo.PlotThreads pt + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID AND pl.IsArchived = 0 + INNER JOIN dbo.ThreadTypes tt ON tt.ThreadTypeID = pt.ThreadTypeID + INNER JOIN dbo.ThreadStatuses ts ON ts.ThreadStatusID = pt.ThreadStatusID + LEFT JOIN #SceneOrder intro ON intro.SceneID = pt.IntroducedSceneID + LEFT JOIN #SceneOrder planned ON planned.SceneID = pt.PlannedResolutionSceneID + LEFT JOIN #SceneOrder actual ON actual.SceneID = pt.ActualResolutionSceneID + LEFT JOIN dbo.ThreadEvents te ON te.PlotThreadID = pt.PlotThreadID + LEFT JOIN #SceneOrder eventOrder ON eventOrder.SceneID = te.SceneID + WHERE pl.ProjectID = @ProjectID + AND pt.IsArchived = 0 + AND (@BookID IS NULL OR pl.BookID IS NULL OR pl.BookID = @BookID) + GROUP BY pt.PlotThreadID, pt.PlotLineID, pt.ThreadTitle, pt.Summary, tt.TypeName, + ts.StatusName, pt.Importance, pt.IntroducedSceneID, intro.SceneID, + intro.ChapterNumber, intro.SceneNumber, intro.SceneTitle, + pt.PlannedResolutionSceneID, planned.SceneID, planned.ChapterNumber, + planned.SceneNumber, planned.SceneTitle, pt.ActualResolutionSceneID, + actual.SceneID, actual.ChapterNumber, actual.SceneNumber, actual.SceneTitle + ORDER BY pt.PlotLineID, pt.Importance DESC, pt.ThreadTitle, pt.PlotThreadID; + + ;WITH CandidateMatches AS + ( + SELECT ev.NarrativeCandidateID, ev.SceneID, + MAX(ev.EventTitle) AS EventTitle, + MAX(ev.EventDescription) AS EventDescription, + MAX(ev.Evidence) AS Evidence, + MAX(ev.Confidence) AS Confidence, + MAX(nc.Significance) AS Significance, + COUNT(*) AS MatchCount + FROM dbo.StoryIntelligenceNarrativeCandidateEvents ev + INNER JOIN dbo.StoryIntelligenceNarrativeCandidates nc + ON nc.NarrativeCandidateID = ev.NarrativeCandidateID + WHERE nc.ProjectID = @ProjectID AND (@BookID IS NULL OR nc.BookID = @BookID) + GROUP BY ev.NarrativeCandidateID, ev.SceneID + ) + SELECT te.ThreadEventID, pt.PlotThreadID, pl.PlotLineID, s.SceneID, + so.BookID, so.ChapterID, so.ChapterNumber, ISNULL(so.ChapterTitle, N'') AS ChapterTitle, + so.SceneNumber, ISNULL(so.SceneTitle, N'Untitled scene') AS SceneTitle, + s.Summary AS SceneSummary, so.NarrativeOrder, + pov.CharacterName AS PovCharacterName, characterData.CharacterNames, + loc.LocationPath AS LocationName, s.StartDateTime, s.EndDateTime, + s.RelativeTimeText, tm.TimeModeName, tc.TimeConfidenceName, + warningData.WarningCount, dependencyData.DependencyCount, + CONVERT(bit, CASE WHEN sms.SceneID IS NULL OR NULLIF(sms.SourceText, N'') IS NULL THEN 0 ELSE 1 END) AS HasManuscript, + pt.ThreadTitle, ts.StatusName AS ThreadStatusName, pt.Importance AS ThreadImportance, + tet.TypeName AS CanonicalRole, tet.MarkerText AS CanonicalMarker, + pet.TypeName AS CanonicalStructuralType, te.EventTitle AS CanonicalTitle, + te.EventDescription AS CanonicalDescription, te.Confidence AS CanonicalConfidence, + te.Source, te.SourceReferenceID, te.SourceKey, + CASE + WHEN te.Source <> N'WholeBookPlotSynthesis' OR te.SourceReferenceID IS NULL THEN N'Not applicable' + WHEN cm.MatchCount = 1 THEN N'SourceReferenceID + SceneID' + WHEN cm.MatchCount > 1 THEN N'Ambiguous' + ELSE N'Not found' + END AS CandidateMatchState, + CASE WHEN cm.MatchCount = 1 THEN cm.EventTitle END AS CandidateTitle, + CASE WHEN cm.MatchCount = 1 THEN cm.EventDescription END AS CandidateDescription, + CASE WHEN cm.MatchCount = 1 THEN cm.Evidence END AS CandidateEvidence, + CASE WHEN cm.MatchCount = 1 THEN cm.Confidence END AS CandidateConfidence, + CASE WHEN cm.MatchCount = 1 THEN cm.Significance END AS CandidateSignificance + FROM dbo.ThreadEvents te + INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID AND pt.IsArchived = 0 + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID AND pl.IsArchived = 0 + INNER JOIN #SceneOrder so ON so.SceneID = te.SceneID + INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID AND s.IsArchived = 0 + INNER JOIN dbo.ThreadEventTypes tet ON tet.ThreadEventTypeID = te.EventTypeID + INNER JOIN dbo.PlotEventTypes pet ON pet.PlotEventTypeID = te.PlotEventTypeID + INNER JOIN dbo.ThreadStatuses ts ON ts.ThreadStatusID = pt.ThreadStatusID + INNER JOIN dbo.TimeModes tm ON tm.TimeModeID = s.TimeModeID + INNER JOIN dbo.TimeConfidences tc ON tc.TimeConfidenceID = s.TimeConfidenceID + LEFT JOIN dbo.Characters pov ON pov.CharacterID = s.POVCharacterID AND pov.IsArchived = 0 + LEFT JOIN dbo.LocationPaths loc ON loc.LocationID = s.PrimaryLocationID + LEFT JOIN dbo.SceneManuscriptSources sms ON sms.SceneID = s.SceneID + LEFT JOIN CandidateMatches cm ON cm.NarrativeCandidateID = te.SourceReferenceID AND cm.SceneID = te.SceneID + OUTER APPLY + ( + SELECT STRING_AGG(CONVERT(nvarchar(max), c.CharacterName), N', ') AS CharacterNames + FROM dbo.SceneCharacters sc + INNER JOIN dbo.Characters c ON c.CharacterID = sc.CharacterID AND c.IsArchived = 0 + WHERE sc.SceneID = s.SceneID + ) characterData + OUTER APPLY + ( + SELECT COUNT(*) AS WarningCount + FROM dbo.ContinuityWarnings cw + WHERE cw.SceneID = s.SceneID AND cw.IsDismissed = 0 + ) warningData + OUTER APPLY + ( + SELECT COUNT(*) AS DependencyCount + FROM dbo.SceneDependencies sd + WHERE sd.IsArchived = 0 AND (sd.SourceSceneID = s.SceneID OR sd.TargetSceneID = s.SceneID) + ) dependencyData + WHERE pl.ProjectID = @ProjectID + AND (@BookID IS NULL OR pl.BookID IS NULL OR pl.BookID = @BookID) + ORDER BY so.NarrativeOrder, pl.SortOrder, pl.PlotLineName, pt.PlotThreadID, te.ThreadEventID; + + SELECT DISTINCT te.ThreadEventID, pt.PlotLineID AS SourcePlotLineID, + target.PlotLineID AS TargetPlotLineID, pet.TypeName AS StructuralType + FROM dbo.ThreadEvents te + INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID AND pt.IsArchived = 0 + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID AND pl.IsArchived = 0 + INNER JOIN #SceneOrder so ON so.SceneID = te.SceneID + INNER JOIN dbo.PlotEventTypes pet ON pet.PlotEventTypeID = te.PlotEventTypeID + CROSS APPLY + ( + SELECT te.TargetPlotLineID AS PlotLineID WHERE te.TargetPlotLineID IS NOT NULL + UNION + SELECT petp.PlotLineID FROM dbo.PlotEventTargetPlotLines petp WHERE petp.PlotEventID = te.ThreadEventID + ) target + WHERE pl.ProjectID = @ProjectID; + + SELECT sd.SceneDependencyID, sd.SourceSceneID, sd.TargetSceneID, + sdt.TypeName AS DependencyType, sd.Description, sd.IsHardDependency + FROM dbo.SceneDependencies sd + INNER JOIN dbo.SceneDependencyTypes sdt ON sdt.SceneDependencyTypeID = sd.SceneDependencyTypeID + INNER JOIN #SceneOrder sourceOrder ON sourceOrder.SceneID = sd.SourceSceneID + INNER JOIN #SceneOrder targetOrder ON targetOrder.SceneID = sd.TargetSceneID + WHERE sd.IsArchived = 0 + ORDER BY sourceOrder.NarrativeOrder, targetOrder.NarrativeOrder, sd.SceneDependencyID; + + SELECT s.SceneID, so.BookID, so.ChapterID, so.ChapterNumber, + ISNULL(so.ChapterTitle, N'') AS ChapterTitle, so.SceneNumber, + ISNULL(so.SceneTitle, N'Untitled scene') AS SceneTitle, s.Summary, + so.NarrativeOrder, pov.CharacterName AS PovCharacterName, + characterData.CharacterNames, loc.LocationPath AS LocationName, + purposeData.PurposeNames, s.RelativeTimeText, s.StartDateTime, + warningData.WarningCount, dependencyData.DependencyCount, + CONVERT(bit, CASE WHEN sms.SceneID IS NULL OR NULLIF(sms.SourceText, N'') IS NULL THEN 0 ELSE 1 END) AS HasManuscript, + canonicalData.CanonicalPlotLineCount, proposedData.ProposedCandidateCount, + proposedData.ProposedCandidateNames + FROM #SceneOrder so + INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID + LEFT JOIN dbo.Characters pov ON pov.CharacterID = s.POVCharacterID AND pov.IsArchived = 0 + LEFT JOIN dbo.LocationPaths loc ON loc.LocationID = s.PrimaryLocationID + LEFT JOIN dbo.SceneManuscriptSources sms ON sms.SceneID = s.SceneID + OUTER APPLY + ( + SELECT STRING_AGG(CONVERT(nvarchar(max), c.CharacterName), N', ') AS CharacterNames + FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters c ON c.CharacterID = sc.CharacterID AND c.IsArchived = 0 + WHERE sc.SceneID = s.SceneID + ) characterData + OUTER APPLY + ( + SELECT STRING_AGG(CONVERT(nvarchar(max), spt.PurposeName), N', ') AS PurposeNames + FROM dbo.ScenePurposes sp INNER JOIN dbo.ScenePurposeTypes spt ON spt.ScenePurposeTypeID = sp.ScenePurposeTypeID + WHERE sp.SceneID = s.SceneID + ) purposeData + OUTER APPLY + ( + SELECT COUNT(DISTINCT pl.PlotLineID) AS CanonicalPlotLineCount + FROM dbo.ThreadEvents te + INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID AND pt.IsArchived = 0 + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID AND pl.IsArchived = 0 + WHERE te.SceneID = s.SceneID AND pl.ProjectID = @ProjectID + ) canonicalData + OUTER APPLY + ( + SELECT COUNT(DISTINCT candidate.NarrativeCandidateID) AS ProposedCandidateCount, + STRING_AGG(CONVERT(nvarchar(max), candidate.ProposedTitle), N'; ') AS ProposedCandidateNames + FROM + ( + SELECT DISTINCT nc.NarrativeCandidateID, nc.ProposedTitle + FROM dbo.StoryIntelligenceNarrativeCandidates nc + LEFT JOIN dbo.StoryIntelligenceNarrativeCandidateEvidence e ON e.NarrativeCandidateID = nc.NarrativeCandidateID + LEFT JOIN dbo.StoryIntelligenceNarrativeCandidateEvents ev ON ev.NarrativeCandidateID = nc.NarrativeCandidateID + WHERE nc.ProjectID = @ProjectID + AND nc.BookID = so.BookID + AND nc.Status = N'Pending' + AND (e.SceneID = s.SceneID OR ev.SceneID = s.SceneID) + ) candidate + ) proposedData + OUTER APPLY + ( + SELECT COUNT(*) AS WarningCount FROM dbo.ContinuityWarnings cw WHERE cw.SceneID = s.SceneID AND cw.IsDismissed = 0 + ) warningData + OUTER APPLY + ( + SELECT COUNT(*) AS DependencyCount FROM dbo.SceneDependencies sd + WHERE sd.IsArchived = 0 AND (sd.SourceSceneID = s.SceneID OR sd.TargetSceneID = s.SceneID) + ) dependencyData + ORDER BY so.NarrativeOrder; + + SELECT nc.NarrativeCandidateID, evidence.SceneID, nc.CandidateType, + nc.ProposedTitle AS CandidateTitle, nc.Status, nc.Significance, + nc.Confidence AS CandidateConfidence, evidence.ContributionType, evidence.Evidence + FROM dbo.StoryIntelligenceNarrativeCandidates nc + CROSS APPLY + ( + SELECT e.SceneID, e.ContributionType, e.Evidence + FROM dbo.StoryIntelligenceNarrativeCandidateEvidence e + WHERE e.NarrativeCandidateID = nc.NarrativeCandidateID + UNION ALL + SELECT ev.SceneID, ev.EventType, COALESCE(ev.Evidence, ev.EventDescription) + FROM dbo.StoryIntelligenceNarrativeCandidateEvents ev + WHERE ev.NarrativeCandidateID = nc.NarrativeCandidateID + ) evidence + INNER JOIN #SceneOrder so ON so.SceneID = evidence.SceneID + WHERE nc.ProjectID = @ProjectID + AND nc.Status = N'Pending' + AND (@BookID IS NULL OR nc.BookID = @BookID) + ORDER BY so.NarrativeOrder, nc.CandidateType, nc.ProposedTitle, nc.NarrativeCandidateID; +END; +GO diff --git a/PlotLine/ViewComponents/EntitlementBannerViewComponent.cs b/PlotLine/ViewComponents/EntitlementBannerViewComponent.cs new file mode 100644 index 00000000..3b92887f --- /dev/null +++ b/PlotLine/ViewComponents/EntitlementBannerViewComponent.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Mvc; +using PlotLine.Services; + +namespace PlotLine.ViewComponents; + +public sealed class EntitlementBannerViewComponent( + ICurrentUserService currentUser, + ISubscriptionService subscriptions) : ViewComponent +{ + public async Task InvokeAsync() + { + if (currentUser.UserId is not int userId) + { + return Content(string.Empty); + } + + var entitlement = await subscriptions.GetEffectiveEntitlementAsync(userId); + return entitlement.IsReadOnly ? View(entitlement) : Content(string.Empty); + } +} diff --git a/PlotLine/ViewModels/AuthViewModels.cs b/PlotLine/ViewModels/AuthViewModels.cs index 9132c92d..c93bf05a 100644 --- a/PlotLine/ViewModels/AuthViewModels.cs +++ b/PlotLine/ViewModels/AuthViewModels.cs @@ -9,6 +9,7 @@ public sealed class ManageAccountViewModel public UserSubscriptionDetail? Subscription { get; set; } public TrialVisibilityViewModel? Trial { get; set; } public bool HasPaidBillingRisk { get; set; } + public EffectiveEntitlement? Entitlement { get; set; } } public sealed class ManageSubscriptionViewModel @@ -18,6 +19,7 @@ public sealed class ManageSubscriptionViewModel public TrialVisibilityViewModel? Trial { get; set; } public SubscriptionUsageSummary? Usage { get; set; } public IReadOnlyList AvailableLevels { get; set; } = []; + public EffectiveEntitlement? Entitlement { get; set; } } public sealed class TrialVisibilityViewModel @@ -93,6 +95,47 @@ public sealed class PricingViewModel public bool IsSignedIn { get; set; } } +public sealed class AdminSubscriptionsViewModel +{ + public string? Search { get; set; } + public IReadOnlyList Users { get; set; } = []; + public AppUser? SelectedUser { get; set; } + public EffectiveEntitlement? Entitlement { get; set; } + public SubscriptionUsageSummary? Usage { get; set; } + public IReadOnlyList Levels { get; set; } = []; +} + +public sealed class AdminTrialExtensionForm +{ + [Range(1, int.MaxValue)] + public int UserID { get; set; } + [Required] + public DateTime TrialExpiryDateUTC { get; set; } + [Required, StringLength(1000)] + public string Reason { get; set; } = string.Empty; +} + +public sealed class AdminSubscriptionOverrideForm +{ + [Range(1, int.MaxValue)] + public int UserID { get; set; } + [Range(1, int.MaxValue)] + public int SubscriptionLevelID { get; set; } + [Required] + public DateTime StartDateUTC { get; set; } + public DateTime? ExpiryDateUTC { get; set; } + [Required, StringLength(1000)] + public string Reason { get; set; } = string.Empty; +} + +public sealed class AdminOverrideRevokeForm +{ + [Range(1, int.MaxValue)] + public int UserID { get; set; } + [Required, StringLength(1000)] + public string Reason { get; set; } = string.Empty; +} + public sealed class PublicPageViewModel { public string SupportEmail { get; set; } = "support@plotdirector.com"; diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 2b8462d0..3a333540 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -653,6 +653,7 @@ public sealed class SceneCharacterParticipationInputViewModel public string? OutfitDescription { get; set; } public string? PhysicalCondition { get; set; } public string? EmotionalState { get; set; } + public string? KnowledgeNotes { get; set; } } public sealed class StoryStateViewModel @@ -1361,7 +1362,6 @@ public sealed class TimelineSettingsViewModel public bool ShowMetricShape { get; set; } = true; public bool ShowPlotLines { get; set; } = true; public bool ShowStoryAssets { get; set; } - public bool ShowCharacterAppearances { get; set; } public bool ShowWarnings { get; set; } = true; public List SelectedMetricTypeIDs { get; set; } = []; public IReadOnlyList MetricOptions { get; set; } = []; diff --git a/PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs b/PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs new file mode 100644 index 00000000..761899e7 --- /dev/null +++ b/PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs @@ -0,0 +1,95 @@ +using PlotLine.Models; + +namespace PlotLine.ViewModels; + +public sealed class PlotLineWorkspaceViewModel +{ + public Project Project { get; set; } = new(); + public int? SelectedBookID { get; set; } + public int? SelectedScenarioID { get; set; } + public string? SelectedScenarioName { get; set; } + public string Mode { get; set; } = "Focus"; + public bool ShowSuggestions { get; set; } + public IReadOnlyList Books { get; set; } = []; + public IReadOnlyList Scenarios { get; set; } = []; + public IReadOnlyList PlotLines { get; set; } = []; + public IReadOnlyList SelectedPlotLineIDs { get; set; } = []; + public IReadOnlyList SelectedThreadIDs { get; set; } = []; + public IReadOnlyList Scenes { get; set; } = []; + public IReadOnlyList SuggestedScenes { get; set; } = []; + public IReadOnlyList ProposedOnlyScenes { get; set; } = []; + public IReadOnlyList NoKnownAttributionScenes { get; set; } = []; + public bool IsUnattributedMode => string.Equals(Mode, "Unattributed", StringComparison.OrdinalIgnoreCase); + public bool IsWeaveMode => SelectedPlotLineIDs.Count > 1; +} + +public sealed class PlotLineWorkspaceLineViewModel +{ + public PlotLineWorkspaceLineRow Line { get; set; } = new(); + public bool IsSelected { get; set; } + public IReadOnlyList Threads { get; set; } = []; +} + +public sealed class PlotLineWorkspaceSceneViewModel +{ + public int SceneID { get; set; } + public int NarrativeOrder { get; set; } + public int GapBefore { get; set; } + public int ChapterGapBefore { get; set; } + public decimal ChapterNumber { get; set; } + public string ChapterTitle { get; set; } = string.Empty; + public decimal SceneNumber { get; set; } + public string SceneTitle { get; set; } = string.Empty; + public string? Summary { get; set; } + public string? PovCharacterName { get; set; } + public string? LocationName { get; set; } + public string? TimeLabel { get; set; } + public int WarningCount { get; set; } + public int DependencyCount { get; set; } + public bool HasManuscript { get; set; } + public int StructuralTargetCount { get; set; } + public IReadOnlyList Memberships { get; set; } = []; + public IReadOnlyList Connections { get; set; } = []; + public bool IsShared => Memberships.Select(x => x.PlotLineID).Distinct().Count() > 1; +} + +public sealed class PlotLineWorkspaceSceneMembershipViewModel +{ + public int PlotLineID { get; set; } + public string PlotLineName { get; set; } = string.Empty; + public string Colour { get; set; } = "#2f6f63"; + public IReadOnlyList Contributions { get; set; } = []; +} + +public sealed class PlotLineWorkspaceSuggestionSceneViewModel +{ + public PlotLineWorkspaceAttributionRow Scene { get; set; } = new(); + public IReadOnlyList Suggestions { get; set; } = []; +} + +public sealed class PlotLineWorkspaceInspectorViewModel +{ + public int ProjectID { get; set; } + public int? BookID { get; set; } + public SceneEditViewModel Scene { get; set; } = new(); + public IReadOnlyList Memberships { get; set; } = []; + public IReadOnlyList Threads { get; set; } = []; + public IReadOnlyList Dependencies { get; set; } = []; + public IReadOnlyList Targets { get; set; } = []; + public IReadOnlyList Suggestions { get; set; } = []; +} + +public sealed class PlotLineWorkspaceTargetViewModel +{ + public string SourcePlotLineName { get; set; } = string.Empty; + public string TargetPlotLineName { get; set; } = string.Empty; + public string StructuralType { get; set; } = string.Empty; +} + +public sealed class PlotLineWorkspaceManuscriptViewModel +{ + public int SceneID { get; set; } + public string SceneTitle { get; set; } = string.Empty; + public string SourceText { get; set; } = string.Empty; + public int SourceWordCount { get; set; } +} diff --git a/PlotLine/Views/Admin/Index.cshtml b/PlotLine/Views/Admin/Index.cshtml index d7033157..b3ded7ee 100644 --- a/PlotLine/Views/Admin/Index.cshtml +++ b/PlotLine/Views/Admin/Index.cshtml @@ -4,76 +4,74 @@ var summary = Model.FeatureRequestSummary; } -
-
-

Admin

-

Dashboard

-

Operational tools for PlotDirector administrators.

+
+
+
+

Admin

+

Dashboard

+

Operational tools for PlotDirector administrators.

+
-
- + -@if (TempData["AdminMessage"] is string adminMessage) -{ -
@adminMessage
-} -@if (TempData["AdminError"] is string adminError) -{ -
@adminError
-} + @if (TempData["AdminMessage"] is string adminMessage) + { +
@adminMessage
+ } + @if (TempData["AdminError"] is string adminError) + { +
@adminError
+ } -
-
-
-
+
+

User feedback

Feature Requests

@@ -83,7 +81,7 @@ Open
-
+ -
+

Reference data

Name Intelligence

@@ -119,11 +117,13 @@
-
+
-

Placeholder

+

Administration

Subscriptions

-

Subscription management tools will be added later.

+

Inspect billing and trial state, extend trials, and grant audited access overrides.

+
-
+
+
diff --git a/PlotLine/Views/Admin/Subscriptions.cshtml b/PlotLine/Views/Admin/Subscriptions.cshtml new file mode 100644 index 00000000..111008c6 --- /dev/null +++ b/PlotLine/Views/Admin/Subscriptions.cshtml @@ -0,0 +1,52 @@ +@model AdminSubscriptionsViewModel +@{ + ViewData["Title"] = "Subscription administration"; + var entitlement = Model.Entitlement; + var underlying = entitlement?.UnderlyingSubscription; +} + +

Administration

Subscription access

Billing state and PlotDirector access are shown separately.

+@if (TempData["AdminMessage"] is string message) {
@message
} +@if (TempData["AdminError"] is string error) {
@error
} + +
+
+
+
+
+ @if (Model.Users.Count > 0) + { + + } +
+ +@if (Model.SelectedUser is not null && entitlement is not null) +{ +
+

@Model.SelectedUser.Email

+
+

Paid / underlying plan

@(underlying?.DisplayName ?? "None")

+

Billing status

@(underlying?.StripeStatus ?? (underlying?.IsTrial == true ? "Application trial" : "Not supplied"))

+

Effective access

@(entitlement.EffectiveLevel?.DisplayName ?? "Read only") — @entitlement.State

+

Trial start

@(underlying?.StartDateUTC.ToString("d MMMM yyyy 'UTC'") ?? "Not set")

+

Trial expiry

@(entitlement.TrialExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "Not set")

+

Books

@(Model.Usage?.BooksUsed ?? 0) / @(entitlement.EffectiveLevel?.MaxBooks.ToString("N0") ?? "0")

+
+ @if (entitlement.ActiveOverride is not null) + { +
Administrative override active. @entitlement.ActiveOverride.LevelDisplayName; expires @(entitlement.ActiveOverride.ExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "never"). This is not a paid subscription.
+
+ } +
+
+

Change trial expiry

+

Administrative access override

This changes effective access only. Stripe billing is not modified.

+
+} diff --git a/PlotLine/Views/ManageAccount/Index.cshtml b/PlotLine/Views/ManageAccount/Index.cshtml index 87a9c79e..5d6ea450 100644 --- a/PlotLine/Views/ManageAccount/Index.cshtml +++ b/PlotLine/Views/ManageAccount/Index.cshtml @@ -59,6 +59,10 @@

Subscription

+ @if (Model.Entitlement is not null && Model.Entitlement.IsReadOnly) + { +
@Model.Entitlement.Reason
+ } @if (subscription is null) {

No active subscription is assigned.

diff --git a/PlotLine/Views/ManageAccount/Subscription.cshtml b/PlotLine/Views/ManageAccount/Subscription.cshtml index 07b8f6a5..77820120 100644 --- a/PlotLine/Views/ManageAccount/Subscription.cshtml +++ b/PlotLine/Views/ManageAccount/Subscription.cshtml @@ -29,6 +29,16 @@

Current subscription

+ @if (Model.Entitlement is not null) + { +
+ Current access: @(Model.Entitlement.EffectiveLevel?.DisplayName ?? "Read only") — @Model.Entitlement.Reason + @if (Model.Entitlement.UsesAdministrativeOverride) + { + Access ends @(Model.Entitlement.ActiveOverride?.ExpiryDateUTC?.ToString("d MMMM yyyy") ?? "only when removed"). + } +
+ } @if (subscription is null) {

No active subscription is assigned.

@@ -45,11 +55,11 @@
Upgrade -

Your 30-day @trial.PlanName trial started on @FormatDate(trial.StartDateUtc) and expires on @FormatDate(trial.ExpiryDateUtc).

+

Your 30-day @trial.PlanName trial started on @FormatDate(trial.StartDateUtc) and @(trial.IsExpired ? "ended" : "expires") on @FormatDate(trial.ExpiryDateUtc).

-

@trial.DaysElapsed days used, @trial.DaysRemaining days remaining.

+

@(trial.IsExpired ? "Your existing work remains available to read and export." : $"{trial.DaysElapsed} days used, {trial.DaysRemaining} days remaining.")

}
diff --git a/PlotLine/Views/PlotLineWorkspace/Index.cshtml b/PlotLine/Views/PlotLineWorkspace/Index.cshtml new file mode 100644 index 00000000..3c1c62ab --- /dev/null +++ b/PlotLine/Views/PlotLineWorkspace/Index.cshtml @@ -0,0 +1,177 @@ +@model PlotLineWorkspaceViewModel +@{ + ViewData["Title"] = "Plot Lines"; + ViewData["ProjectSection"] = "Plot Lines"; + var selectedThreads = Model.PlotLines.Where(x => x.IsSelected).SelectMany(x => x.Threads).ToList(); +} + + + +
+
+

Story map · @Model.Mode mode

+

Plot Lines

+

Follow one line in Focus mode or select several to inspect the weave.

+
+ +
+ +
+ +
+ + + + +
+ +
+ Plot lines + @foreach (var item in Model.PlotLines) + { + + } + Unattributed scenes +
+ + @if (!Model.IsUnattributedMode && selectedThreads.Count > 0) + { +
+ Thread filter @(Model.SelectedThreadIDs.Count > 0 ? $"({Model.SelectedThreadIDs.Count})" : "") +
+ @foreach (var thread in selectedThreads) + { + + } +
+
+ } +
+ +@if (Model.IsUnattributedMode) +{ +
+
+

Proposed only @Model.ProposedOnlyScenes.Count

+

No canonical plot-line contribution; one or more pending suggestions exist.

+ @foreach (var scene in Model.ProposedOnlyScenes) + { + + } +
+
+

No known attribution @Model.NoKnownAttributionScenes.Count

+

Neither a canonical contribution nor a pending suggestion is known.

+ @foreach (var scene in Model.NoKnownAttributionScenes) + { + + } +
+
+} +else if (Model.Scenes.Count == 0) +{ +

No contributions in this view

Choose another plot line, book, scenario, or thread filter.

+} +else +{ +
+ @foreach (var scene in Model.Scenes) + { + if (scene.GapBefore > 0) + { +
+ @scene.GapBefore scene@(scene.GapBefore == 1 ? "" : "s") between contributions + @if (scene.ChapterGapBefore > 0) { @scene.ChapterGapBefore whole chapter@(scene.ChapterGapBefore == 1 ? "" : "s") } +
+ } +
+ +
+ @foreach (var membership in scene.Memberships) + { +
+ +
@membership.PlotLineName + @foreach (var contribution in membership.Contributions) + { + @contribution.CanonicalRole · @contribution.ThreadTitle + } +
+
+ } +
+
+ @if (scene.IsShared) { Shared junction } + @if (!string.IsNullOrWhiteSpace(scene.PovCharacterName)) { POV @scene.PovCharacterName } + @if (!string.IsNullOrWhiteSpace(scene.LocationName)) { @scene.LocationName } + @if (scene.WarningCount > 0) { @scene.WarningCount warning@(scene.WarningCount == 1 ? "" : "s") } + @if (scene.DependencyCount > 0) { @scene.DependencyCount connection@(scene.DependencyCount == 1 ? "" : "s") } + @if (scene.StructuralTargetCount > 0) { @scene.StructuralTargetCount cross-line connection@(scene.StructuralTargetCount == 1 ? "" : "s") } +
+
+ } +
+} + +@if (Model.ShowSuggestions && Model.SuggestedScenes.Count > 0) +{ +
+

Pending suggestions @Model.SuggestedScenes.Count scenes

+

Suggestions are review context, not canonical plot-line contributions.

+ @foreach (var item in Model.SuggestedScenes.Take(60)) + { + + } + @if (Model.SuggestedScenes.Count > 60) {

Showing the first 60 scenes. Narrow to a book for a smaller review set.

} +
+} + + + + +@section Scripts { + +} diff --git a/PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml b/PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml new file mode 100644 index 00000000..a91ccf20 --- /dev/null +++ b/PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml @@ -0,0 +1,102 @@ +@model PlotLineWorkspaceInspectorViewModel +
+

Scene contribution

@Model.Scene.SceneTitle

+ +
+

Scene @Model.Scene.SceneNumber.ToString("0.##") · @Model.Scene.TimeModeName

+ + +
+ @if (Model.Memberships.Count == 0) {

This scene has no canonical plot-line contribution.

} + @foreach (var membership in Model.Memberships) + { +
+

@membership.PlotLineName

+ @foreach (var contribution in membership.Contributions) + { +
@contribution.CanonicalRole · @contribution.ThreadTitle +

@(string.IsNullOrWhiteSpace(contribution.CanonicalDescription) ? contribution.CanonicalTitle : contribution.CanonicalDescription)

+ @contribution.CanonicalStructuralType · @contribution.ThreadStatusName +
+ } + @foreach (var thread in Model.Threads.Where(x => x.PlotLineID == membership.PlotLineID)) + { +
+ @thread.ThreadTitle boundaries +
+
Introduced
@(thread.IntroducedSceneLabel ?? "Not recorded")
+
Planned resolution
@(thread.PlannedResolutionSceneLabel ?? "Not recorded")
+
Actual resolution
@(thread.ActualResolutionSceneLabel ?? "Not recorded")
+
+
+ } +
+ } +
+ + + diff --git a/PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml b/PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml new file mode 100644 index 00000000..d7bea10b --- /dev/null +++ b/PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml @@ -0,0 +1,2 @@ +@model PlotLineWorkspaceManuscriptViewModel +

@Model.SourceWordCount.ToString("N0") words · manuscript source

@Model.SourceText
diff --git a/PlotLine/Views/Projects/Index.cshtml b/PlotLine/Views/Projects/Index.cshtml index 06a1c5bc..65ef3230 100644 --- a/PlotLine/Views/Projects/Index.cshtml +++ b/PlotLine/Views/Projects/Index.cshtml @@ -25,7 +25,14 @@

Free trial status

@trial.StatusLabel on @trial.PlanName

-

Your 30-day trial expires on @FormatDate(trial.ExpiryDateUtc). Upgrade whenever you are ready.

+ @if (trial.IsExpired) + { +

Your trial ended on @FormatDate(trial.ExpiryDateUtc). Your books remain available to read and export; upgrade to continue editing or creating books.

+ } + else + { +

Your 30-day trial expires on @FormatDate(trial.ExpiryDateUtc). Upgrade whenever you are ready.

+ }
Upgrade diff --git a/PlotLine/Views/Shared/Components/EntitlementBanner/Default.cshtml b/PlotLine/Views/Shared/Components/EntitlementBanner/Default.cshtml new file mode 100644 index 00000000..572b81bb --- /dev/null +++ b/PlotLine/Views/Shared/Components/EntitlementBanner/Default.cshtml @@ -0,0 +1,7 @@ +@model EffectiveEntitlement +
+ @(Model.IsTrialExpired ? "Your trial has ended." : "Your subscription is inactive.") + Your existing books remain available to read and export. + View subscription options + to continue editing, importing, using Story Intelligence, or creating new books. +
diff --git a/PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml b/PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml index bf80d809..c90a7744 100644 --- a/PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml +++ b/PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml @@ -139,6 +139,10 @@
+
+ + +
} @@ -183,6 +187,10 @@ +
+ + +
diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index 7b234672..dbd63297 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -132,6 +132,7 @@ + @@ -159,6 +160,7 @@ @if (isApplication) { + @await Component.InvokeAsync("EntitlementBanner") } else { diff --git a/PlotLine/Views/Timeline/Index.cshtml b/PlotLine/Views/Timeline/Index.cshtml index 419c301b..a3cf4edb 100644 --- a/PlotLine/Views/Timeline/Index.cshtml +++ b/PlotLine/Views/Timeline/Index.cshtml @@ -55,7 +55,6 @@ int ChapterSceneColumns(ChapterTimelineViewModel chapter) => Math.Max(chapter.Scenes.Count, 1); int BookSceneColumns(BookTimelineViewModel book) => Math.Max(book.Chapters.Any() ? book.Chapters.Sum(ChapterSceneColumns) : 1, 1); var hasSelectedScene = Model.SelectedScene is not null; - int CharacterAppearanceCount(CharacterLaneViewModel lane) => lane.SceneSlots.Sum(slot => slot.Appearances.Count); int HiddenCount(IReadOnlyList items, int visibleCount) => Math.Max(0, items.Count - visibleCount); string PlotMarkerKind(string? plotEventTypeName) => (plotEventTypeName ?? "Progress").Trim().ToLowerInvariant() switch { @@ -163,10 +162,6 @@ .ThenBy(warning => warning.WarningTypeName) .ToList() : []; - bool HasStoryState(SceneCharacter appearance) - => !string.IsNullOrWhiteSpace(appearance.EmotionalState) - || !string.IsNullOrWhiteSpace(appearance.PhysicalCondition) - || !string.IsNullOrWhiteSpace(appearance.KnowledgeNotes); string AssetMarkerLabel(AssetEvent assetEvent) { var typeName = assetEvent.AssetEventTypeName?.Trim() ?? string.Empty; @@ -282,203 +277,6 @@ } return string.Join(Environment.NewLine, lines); } - string CharacterMarkerLabel(SceneCharacter appearance, SceneCharacter? firstAppearance, SceneCharacter? lastAppearance) - { - if (firstAppearance?.SceneCharacterID == appearance.SceneCharacterID) - { - return "Intro"; - } - if (lastAppearance?.SceneCharacterID == appearance.SceneCharacterID - && string.Equals(appearance.PresenceTypeName, "Leaves", StringComparison.OrdinalIgnoreCase)) - { - return "Exit"; - } - if (string.Equals(appearance.RoleInSceneTypeName, "POV Character", StringComparison.OrdinalIgnoreCase)) - { - return "POV"; - } - if (!string.IsNullOrWhiteSpace(appearance.KnowledgeNotes)) - { - return "Know"; - } - if (HasStoryState(appearance)) - { - return "State"; - } - var presence = appearance.PresenceTypeName?.Trim() ?? string.Empty; - return presence.ToLowerInvariant() switch - { - "present" => "In", - "arrives" => "In+", - "leaves" => "Out", - "nearby" => "Near", - "hidden" => "Hide", - "overhearing" => "Hear", - "mentioned only" => "Ref", - "background" => "Bg", - "off-screen" => "Off", - _ => "Char" - }; - } - string CharacterMarkerMeaning(SceneCharacter appearance, SceneCharacter? firstAppearance, SceneCharacter? lastAppearance) - { - if (firstAppearance?.SceneCharacterID == appearance.SceneCharacterID) - { - return $"{appearance.CharacterName} enters this story lane in this scene."; - } - if (lastAppearance?.SceneCharacterID == appearance.SceneCharacterID - && string.Equals(appearance.PresenceTypeName, "Leaves", StringComparison.OrdinalIgnoreCase)) - { - return $"{appearance.CharacterName} exits this story lane in this scene."; - } - if (!string.IsNullOrWhiteSpace(appearance.KnowledgeNotes)) - { - return $"{appearance.CharacterName}'s knowledge changes in this scene."; - } - if (!string.IsNullOrWhiteSpace(appearance.EmotionalState) || !string.IsNullOrWhiteSpace(appearance.PhysicalCondition)) - { - return $"{appearance.CharacterName}'s story state changes in this scene."; - } - var presence = appearance.PresenceTypeName?.Trim() ?? string.Empty; - return presence.ToLowerInvariant() switch - { - "present" => "Character appears in this scene.", - "arrives" => "Character arrives in this scene.", - "leaves" => "Character leaves in this scene.", - "nearby" => "Character is nearby in this scene.", - "hidden" => "Character is hidden in this scene.", - "overhearing" => "Character overhears this scene.", - "mentioned only" => "Character is mentioned in this scene.", - "background" => "Character is in the background of this scene.", - "off-screen" => "Character is off-screen in this scene.", - _ => "Character appears in this scene." - }; - } - string CharacterMarkerClass(SceneCharacter appearance, SceneCharacter? firstAppearance, SceneCharacter? lastAppearance, IReadOnlyList characterWarnings) - { - var classes = new List(); - if (characterWarnings.Any()) - { - classes.Add("timeline-marker-has-warning"); - } - if (firstAppearance?.SceneCharacterID == appearance.SceneCharacterID) - { - classes.Add("timeline-marker-story-turn"); - } - if (lastAppearance?.SceneCharacterID == appearance.SceneCharacterID - && string.Equals(appearance.PresenceTypeName, "Leaves", StringComparison.OrdinalIgnoreCase)) - { - classes.Add("timeline-marker-exit"); - } - if (string.Equals(appearance.RoleInSceneTypeName, "POV Character", StringComparison.OrdinalIgnoreCase) - || string.Equals(appearance.RoleInSceneTypeName, "Main Participant", StringComparison.OrdinalIgnoreCase)) - { - classes.Add("timeline-marker-important"); - } - if (HasStoryState(appearance)) - { - classes.Add("timeline-marker-state-change"); - } - return string.Join(' ', classes); - } - string CharacterMarkerTooltip(SceneCharacter appearance, Scene scene, SceneCharacter? firstAppearance, SceneCharacter? lastAppearance, IReadOnlyList characterWarnings) - { - var lines = new List - { - CharacterMarkerMeaning(appearance, firstAppearance, lastAppearance), - $"Character: {appearance.CharacterName}", - $"Role: {(string.IsNullOrWhiteSpace(appearance.RoleInSceneTypeName) ? "Not set" : appearance.RoleInSceneTypeName)}", - $"Presence: {(string.IsNullOrWhiteSpace(appearance.PresenceTypeName) ? "Not set" : appearance.PresenceTypeName)}", - $"Scene: {scene.SceneNumber:g}: {scene.SceneTitle}" - }; - if (!string.IsNullOrWhiteSpace(appearance.LocationPath) || !string.IsNullOrWhiteSpace(appearance.LocationName)) - { - lines.Add($"Location: {appearance.LocationPath ?? appearance.LocationName}"); - } - if (!string.IsNullOrWhiteSpace(appearance.EntryLocationName)) - { - lines.Add($"Entry: {appearance.EntryLocationName}"); - } - if (!string.IsNullOrWhiteSpace(appearance.ExitLocationName)) - { - lines.Add($"Exit: {appearance.ExitLocationName}"); - } - if (!string.IsNullOrWhiteSpace(appearance.EmotionalState)) - { - lines.Add($"Emotional state: {appearance.EmotionalState}"); - } - if (!string.IsNullOrWhiteSpace(appearance.PhysicalCondition)) - { - lines.Add($"Physical condition: {appearance.PhysicalCondition}"); - } - if (!string.IsNullOrWhiteSpace(appearance.KnowledgeNotes)) - { - lines.Add($"Knowledge: {appearance.KnowledgeNotes}"); - } - if (!string.IsNullOrWhiteSpace(appearance.AppearanceNotes)) - { - lines.Add($"Summary: {appearance.AppearanceNotes}"); - } - foreach (var warning in characterWarnings.Take(2)) - { - lines.Add($"Continuity: {warning.WarningTypeName} - {(string.IsNullOrWhiteSpace(warning.Details) ? warning.Message : warning.Details)}"); - } - return string.Join(Environment.NewLine, lines); - } - bool HasLeadSceneRole(CharacterLaneViewModel lane) => lane.SceneSlots - .SelectMany(slot => slot.Appearances) - .Any(appearance => - string.Equals(appearance.RoleInSceneTypeName, "POV Character", StringComparison.OrdinalIgnoreCase) || - string.Equals(appearance.RoleInSceneTypeName, "Main Participant", StringComparison.OrdinalIgnoreCase)); - string CharacterGroupName(CharacterLaneViewModel lane) - { - var description = lane.Character.DefaultDescription ?? string.Empty; - - // Timeline grouping prefers the editable CharacterImportance field; imported - // classification metadata remains a fallback for older imported projects. - if (lane.Character.CharacterImportance >= 8) - { - return "Major characters"; - } - - if (lane.Character.CharacterImportance >= 4) - { - return "Secondary / supporting characters"; - } - - if (lane.Character.CharacterImportance.HasValue) - { - return "Minor / mentioned characters"; - } - - if (description.Contains("Imported character classification: Major", StringComparison.OrdinalIgnoreCase)) - { - return "Major characters"; - } - - if (description.Contains("Imported character classification: Supporting", StringComparison.OrdinalIgnoreCase)) - { - return "Secondary / supporting characters"; - } - - if (description.Contains("Imported character classification: Minor", StringComparison.OrdinalIgnoreCase)) - { - return "Minor / mentioned characters"; - } - - if (HasLeadSceneRole(lane) || CharacterAppearanceCount(lane) >= 6) - { - return "Major characters"; - } - - return CharacterAppearanceCount(lane) <= 1 ? "Minor / mentioned characters" : "Secondary / supporting characters"; - } - int CharacterGroupOrder(string groupName) => groupName switch - { - "Major characters" => 0, - "Secondary / supporting characters" => 1, - _ => 2 - }; }