Add Plot Lines workspace and subscription enforcement
This commit is contained in:
parent
b7a17b8945
commit
45b6b2b537
115
PlotLine.Tests/PlotLineWorkspaceTests.cs
Normal file
115
PlotLine.Tests/PlotLineWorkspaceTests.cs
Normal file
@ -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<PlotLineWorkspaceContributionRow>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -25,6 +25,11 @@ if (args.Contains("--toolbar-browser-host"))
|
|||||||
|
|
||||||
var tests = new (string Name, Action Test)[]
|
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 review uses evidence, identity, consequence and directional conflicts", ExceptionReviewTests.DomainPolicy),
|
||||||
("Exception assessment preserves author decisions and scene history", ExceptionReviewTests.PreserveDecisionsAndObservations),
|
("Exception assessment preserves author decisions and scene history", ExceptionReviewTests.PreserveDecisionsAndObservations),
|
||||||
("Character card widths reflect displayed text without changing character data", CharacterCardLayoutTests.DisplayedContent),
|
("Character card widths reflect displayed text without changing character data", CharacterCardLayoutTests.DisplayedContent),
|
||||||
|
|||||||
193
PlotLine.Tests/SubscriptionEntitlementTests.cs
Normal file
193
PlotLine.Tests/SubscriptionEntitlementTests.cs
Normal file
@ -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<int, SubscriptionLevel>
|
||||||
|
{
|
||||||
|
[1] = Level(1, "DraftDesk", "Draft Desk", 2, false),
|
||||||
|
[2] = Level(2, "WritingRoom", "Writing Room", 10, true),
|
||||||
|
[3] = Level(3, "StoryForge", "Story Forge", 30, true),
|
||||||
|
[4] = Level(4, "AuthorStudio", "Author Studio", 999999, true)
|
||||||
|
};
|
||||||
|
|
||||||
|
var repository = Proxy<ISubscriptionRepository>((method, args) => method switch
|
||||||
|
{
|
||||||
|
nameof(ISubscriptionRepository.GetCurrentSubscriptionAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
|
||||||
|
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
|
||||||
|
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(activeOverride),
|
||||||
|
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
|
||||||
|
nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks),
|
||||||
|
_ => DefaultTask(method)
|
||||||
|
});
|
||||||
|
var service = new SubscriptionService(repository, Proxy<IUserFileRepository>((method, _) => DefaultTask(method)));
|
||||||
|
|
||||||
|
var active = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
|
||||||
|
Check(active.State == EntitlementState.ActiveTrial, "A trial immediately before expiry must remain active.");
|
||||||
|
Check(service.CanUseFeatureAsync(7, SubscriptionFeature.StoryIntelligence, now).GetAwaiter().GetResult().Allowed,
|
||||||
|
"An active trial must be able to use entitled features.");
|
||||||
|
|
||||||
|
var boundary = service.GetEffectiveEntitlementAsync(7, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult();
|
||||||
|
Check(boundary.State == EntitlementState.ExpiredTrial && boundary.IsReadOnly,
|
||||||
|
"The exact trial expiry boundary must be read-only.");
|
||||||
|
Check(!service.CanUseFeatureAsync(7, SubscriptionFeature.Import, subscription.TrialExpiryDateUTC).GetAwaiter().GetResult().Allowed,
|
||||||
|
"An expired trial must not be able to import.");
|
||||||
|
|
||||||
|
subscription.TrialExpiryDateUTC = now.AddDays(30);
|
||||||
|
var extended = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
|
||||||
|
Check(extended.State == EntitlementState.ActiveTrial, "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<AuthorizeAttribute>();
|
||||||
|
Check(authorize?.Policy == "AdminOnly", "Subscription administration must remain under the existing AdminOnly policy.");
|
||||||
|
Check(typeof(SubscriptionEnforcementFilter).GetInterfaces().Any(x => x.Name == "IAsyncActionFilter"),
|
||||||
|
"Unsafe requests must have a server-side entitlement filter.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UserSubscriptionDetail Trial(DateTime start, DateTime expiry) => new()
|
||||||
|
{
|
||||||
|
UserID = 7, SubscriptionLevelID = 1, StartDateUTC = start, TrialExpiryDateUTC = expiry,
|
||||||
|
IsActive = true, IsTrial = true, SubscriptionLevelIsActive = true, Name = "DraftDesk", DisplayName = "Draft Desk",
|
||||||
|
MaxBooks = 2, MaxChaptersPerBook = 75, MaxScenesPerBook = 300, MaxCharactersPerProject = 75,
|
||||||
|
MaxStorageMB = 100, MaxCollaborators = 0, RequiresStripeSubscription = false
|
||||||
|
};
|
||||||
|
|
||||||
|
private static UserSubscriptionDetail Paid(DateTime now, string status) => new()
|
||||||
|
{
|
||||||
|
UserID = 7, SubscriptionLevelID = 3, StartDateUTC = now.AddMonths(-1), IsActive = true,
|
||||||
|
SubscriptionLevelIsActive = true, Name = "StoryForge", DisplayName = "Story Forge", RequiresStripeSubscription = true,
|
||||||
|
StripeSubscriptionId = "sub_test", StripeStatus = status, CurrentPeriodEndUTC = now.AddMonths(1),
|
||||||
|
MaxBooks = 30, MaxChaptersPerBook = 200, MaxScenesPerBook = 2000, MaxCharactersPerProject = 500,
|
||||||
|
MaxStorageMB = 5120, MaxCollaborators = 3
|
||||||
|
};
|
||||||
|
|
||||||
|
private static SubscriptionLevel Level(int id, string name, string display, int maxBooks, bool stripe) => new()
|
||||||
|
{
|
||||||
|
SubscriptionLevelID = id, Name = name, DisplayName = display, MaxBooks = maxBooks,
|
||||||
|
MaxChaptersPerBook = id == 1 ? 75 : 200, MaxScenesPerBook = id == 1 ? 300 : 2000,
|
||||||
|
MaxCharactersPerProject = id == 1 ? 75 : 500, MaxStorageMB = id == 1 ? 100 : 5120,
|
||||||
|
MaxCollaborators = id == 1 ? 0 : 3, RequiresStripeSubscription = stripe, IsActive = true
|
||||||
|
};
|
||||||
|
|
||||||
|
private static object DefaultTask(string method) => method switch
|
||||||
|
{
|
||||||
|
nameof(IUserFileRepository.GetStorageUsageForOwnerAsync) => Task.FromResult(0L),
|
||||||
|
_ => Task.CompletedTask
|
||||||
|
};
|
||||||
|
|
||||||
|
private static T Proxy<T>(Func<string, object?[]?, object> handler) where T : class
|
||||||
|
{
|
||||||
|
var proxy = DispatchProxy.Create<T, EntitlementProxy>();
|
||||||
|
((EntitlementProxy)(object)proxy).Handler = handler;
|
||||||
|
return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FindRepositoryRoot()
|
||||||
|
{
|
||||||
|
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "PlotLine.slnx"))) directory = directory.Parent;
|
||||||
|
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(bool condition, string message)
|
||||||
|
{
|
||||||
|
if (!condition) throw new InvalidOperationException(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class EntitlementProxy : DispatchProxy
|
||||||
|
{
|
||||||
|
public Func<string, object?[]?, object> Handler { get; set; } = null!;
|
||||||
|
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) => Handler(targetMethod!.Name, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -29,6 +29,9 @@ public sealed class AdminController(
|
|||||||
IBookRepository books,
|
IBookRepository books,
|
||||||
IOnboardingBuildRepository onboardingBuilds,
|
IOnboardingBuildRepository onboardingBuilds,
|
||||||
ICoreImportBasicLocationService coreImportBasicLocations,
|
ICoreImportBasicLocationService coreImportBasicLocations,
|
||||||
|
ISubscriptionRepository subscriptionRepository,
|
||||||
|
ISubscriptionService subscriptions,
|
||||||
|
IUserRepository users,
|
||||||
IWebHostEnvironment environment,
|
IWebHostEnvironment environment,
|
||||||
ILogger<AdminController> logger) : Controller
|
ILogger<AdminController> logger) : Controller
|
||||||
{
|
{
|
||||||
@ -46,6 +49,95 @@ public sealed class AdminController(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("subscriptions")]
|
||||||
|
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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")]
|
[HttpGet("theme-audit")]
|
||||||
public IActionResult ThemeAudit()
|
public IActionResult ThemeAudit()
|
||||||
{
|
{
|
||||||
|
|||||||
@ -30,13 +30,15 @@ public sealed class ManageAccountController(
|
|||||||
return RedirectToAction("Login", "Account");
|
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
|
return View(new ManageAccountViewModel
|
||||||
{
|
{
|
||||||
User = user,
|
User = user,
|
||||||
Subscription = subscription,
|
Subscription = subscription,
|
||||||
Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow),
|
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");
|
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
|
return View(new ManageSubscriptionViewModel
|
||||||
{
|
{
|
||||||
User = user,
|
User = user,
|
||||||
CurrentSubscription = subscription,
|
CurrentSubscription = subscription,
|
||||||
Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow),
|
Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow),
|
||||||
Usage = subscription is null ? null : await subscriptions.GetUsageSummaryAsync(user.UserID),
|
Usage = subscription is null ? null : await subscriptions.GetUsageSummaryAsync(user.UserID),
|
||||||
AvailableLevels = await subscriptions.GetActiveSubscriptionLevelsAsync()
|
AvailableLevels = await subscriptions.GetActiveSubscriptionLevelsAsync(),
|
||||||
|
Entitlement = entitlement
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
39
PlotLine/Controllers/PlotLineWorkspaceController.cs
Normal file
39
PlotLine/Controllers/PlotLineWorkspaceController.cs
Normal file
@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> Manuscript(int projectId, int? bookId, int sceneId)
|
||||||
|
{
|
||||||
|
var model = await workspace.GetManuscriptAsync(projectId, bookId, sceneId);
|
||||||
|
return model is null ? NotFound() : PartialView("_Manuscript", model);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -416,7 +416,8 @@ public sealed class ScenesController(
|
|||||||
AppearanceNotes = row.AppearanceNotes,
|
AppearanceNotes = row.AppearanceNotes,
|
||||||
OutfitDescription = row.OutfitDescription,
|
OutfitDescription = row.OutfitDescription,
|
||||||
PhysicalCondition = row.PhysicalCondition,
|
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.SceneID = model.SceneID;
|
||||||
model.NewCharacter.NewCharacterName = null;
|
model.NewCharacter.NewCharacterName = null;
|
||||||
model.NewCharacter.KnowledgeNotes = null;
|
|
||||||
model.NewCharacter.ReturnProjectID = current.ReturnProjectID;
|
model.NewCharacter.ReturnProjectID = current.ReturnProjectID;
|
||||||
model.NewCharacter.ReturnBookID = current.ReturnBookID;
|
model.NewCharacter.ReturnBookID = current.ReturnBookID;
|
||||||
await characters.AddSceneCharacterAsync(model.NewCharacter);
|
await characters.AddSceneCharacterAsync(model.NewCharacter);
|
||||||
|
|||||||
@ -47,7 +47,6 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
|
|||||||
current.ShowMetricShape = model.ShowMetricShape;
|
current.ShowMetricShape = model.ShowMetricShape;
|
||||||
current.ShowPlotLines = model.ShowPlotLines;
|
current.ShowPlotLines = model.ShowPlotLines;
|
||||||
current.ShowStoryAssets = model.ShowStoryAssets;
|
current.ShowStoryAssets = model.ShowStoryAssets;
|
||||||
current.ShowCharacterAppearances = model.ShowCharacterAppearances;
|
|
||||||
current.ShowWarnings = model.ShowWarnings;
|
current.ShowWarnings = model.ShowWarnings;
|
||||||
current.SelectedMetricTypeIDs = model.SelectedMetricTypeIDs;
|
current.SelectedMetricTypeIDs = model.SelectedMetricTypeIDs;
|
||||||
current.MetricOptions = current.MetricOptions
|
current.MetricOptions = current.MetricOptions
|
||||||
|
|||||||
33
PlotLine/Data/PlotLineWorkspaceRepository.cs
Normal file
33
PlotLine/Data/PlotLineWorkspaceRepository.cs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
using System.Data;
|
||||||
|
using Dapper;
|
||||||
|
using PlotLine.Models;
|
||||||
|
|
||||||
|
namespace PlotLine.Data;
|
||||||
|
|
||||||
|
public interface IPlotLineWorkspaceRepository
|
||||||
|
{
|
||||||
|
Task<PlotLineWorkspaceData> GetAsync(int projectId, int? bookId, int? scenarioId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PlotLineWorkspaceRepository(ISqlConnectionFactory connectionFactory) : IPlotLineWorkspaceRepository
|
||||||
|
{
|
||||||
|
public async Task<PlotLineWorkspaceData> 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<PlotLineWorkspaceLineRow>()).AsList(),
|
||||||
|
Threads = (await results.ReadAsync<PlotLineWorkspaceThreadRow>()).AsList(),
|
||||||
|
Contributions = (await results.ReadAsync<PlotLineWorkspaceContributionRow>()).AsList(),
|
||||||
|
Targets = (await results.ReadAsync<PlotLineWorkspaceTargetRow>()).AsList(),
|
||||||
|
Dependencies = (await results.ReadAsync<PlotLineWorkspaceDependencyRow>()).AsList(),
|
||||||
|
AttributionScenes = (await results.ReadAsync<PlotLineWorkspaceAttributionRow>()).AsList(),
|
||||||
|
Suggestions = (await results.ReadAsync<PlotLineWorkspaceSuggestionRow>()).AsList()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -7,6 +7,7 @@ namespace PlotLine.Data;
|
|||||||
public interface ISubscriptionRepository
|
public interface ISubscriptionRepository
|
||||||
{
|
{
|
||||||
Task<UserSubscriptionDetail?> GetCurrentSubscriptionAsync(int userId);
|
Task<UserSubscriptionDetail?> GetCurrentSubscriptionAsync(int userId);
|
||||||
|
Task<UserSubscriptionDetail?> GetSubscriptionForEntitlementAsync(int userId);
|
||||||
Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId);
|
Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId);
|
||||||
Task<IReadOnlyList<SubscriptionLevel>> GetActiveSubscriptionLevelsAsync();
|
Task<IReadOnlyList<SubscriptionLevel>> GetActiveSubscriptionLevelsAsync();
|
||||||
Task<int> GetOwnedBookCountAsync(int userId);
|
Task<int> GetOwnedBookCountAsync(int userId);
|
||||||
@ -23,6 +24,13 @@ public interface ISubscriptionRepository
|
|||||||
Task DowngradeToDraftDeskAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
Task DowngradeToDraftDeskAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
||||||
Task RecordPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
Task RecordPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
||||||
Task ClearPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
Task ClearPaymentFailureAsync(string? stripeCustomerId, string? stripeSubscriptionId, string? lastStripeEventId);
|
||||||
|
Task<SubscriptionOverride?> GetActiveOverrideAsync(int userId, DateTime utcNow);
|
||||||
|
Task<BookSlotReservation> TryReserveBookSlotsAsync(int userId, int requestedSlots, DateTime utcNow);
|
||||||
|
Task ReleaseBookSlotReservationAsync(Guid reservationId);
|
||||||
|
Task<IReadOnlyList<SubscriptionAdminUserSummary>> 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
|
public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFactory) : ISubscriptionRepository
|
||||||
@ -36,6 +44,15 @@ public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFacto
|
|||||||
commandType: CommandType.StoredProcedure);
|
commandType: CommandType.StoredProcedure);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<UserSubscriptionDetail?> GetSubscriptionForEntitlementAsync(int userId)
|
||||||
|
{
|
||||||
|
using var connection = connectionFactory.CreateConnection();
|
||||||
|
return await connection.QuerySingleOrDefaultAsync<UserSubscriptionDetail>(
|
||||||
|
"dbo.UserSubscription_GetForEntitlement",
|
||||||
|
new { UserID = userId },
|
||||||
|
commandType: CommandType.StoredProcedure);
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId)
|
public async Task<SubscriptionLevel?> GetSubscriptionLevelAsync(int subscriptionLevelId)
|
||||||
{
|
{
|
||||||
using var connection = connectionFactory.CreateConnection();
|
using var connection = connectionFactory.CreateConnection();
|
||||||
@ -179,4 +196,65 @@ public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFacto
|
|||||||
new { StripeCustomerId = stripeCustomerId, StripeSubscriptionId = stripeSubscriptionId, LastStripeEventId = lastStripeEventId },
|
new { StripeCustomerId = stripeCustomerId, StripeSubscriptionId = stripeSubscriptionId, LastStripeEventId = lastStripeEventId },
|
||||||
commandType: CommandType.StoredProcedure);
|
commandType: CommandType.StoredProcedure);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<SubscriptionOverride?> GetActiveOverrideAsync(int userId, DateTime utcNow)
|
||||||
|
{
|
||||||
|
using var connection = connectionFactory.CreateConnection();
|
||||||
|
return await connection.QuerySingleOrDefaultAsync<SubscriptionOverride>(
|
||||||
|
"dbo.SubscriptionOverride_GetActive",
|
||||||
|
new { UserID = userId, UtcNow = utcNow },
|
||||||
|
commandType: CommandType.StoredProcedure);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<BookSlotReservation> TryReserveBookSlotsAsync(int userId, int requestedSlots, DateTime utcNow)
|
||||||
|
{
|
||||||
|
using var connection = connectionFactory.CreateConnection();
|
||||||
|
return await connection.QuerySingleAsync<BookSlotReservation>(
|
||||||
|
"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<IReadOnlyList<SubscriptionAdminUserSummary>> SearchUsersAsync(string? search, int maximumRows = 50)
|
||||||
|
{
|
||||||
|
using var connection = connectionFactory.CreateConnection();
|
||||||
|
var rows = await connection.QueryAsync<SubscriptionAdminUserSummary>(
|
||||||
|
"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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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.
|
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
|
# 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
|
# Related Guides
|
||||||
|
|
||||||
- [Edit Plot Line](/Help/Article/plotLines.edit)
|
- [Edit Plot Line](/Help/Article/plotLines.edit)
|
||||||
|
- [Plot Lines Workspace](/Help/Article/plotLines.workspace)
|
||||||
- [Plot Threads](/Help/Article/plotThreads.index)
|
- [Plot Threads](/Help/Article/plotThreads.index)
|
||||||
- [Scenes](/Help/Article/scenes.overview)
|
- [Scenes](/Help/Article/scenes.overview)
|
||||||
|
|||||||
42
PlotLine/Help/Articles/PlotLines/Workspace.md
Normal file
42
PlotLine/Help/Articles/PlotLines/Workspace.md
Normal file
@ -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)
|
||||||
@ -11,13 +11,13 @@ screenshot:
|
|||||||
|
|
||||||
# Overview
|
# 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.
|
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
|
# 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.
|
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
|
# Related Guides
|
||||||
|
|
||||||
- [Character Appearances](/Help/Article/timeline.characterAppearances)
|
- [Timeline Filters and Focus](/Help/Article/timeline.filtersAndFocus)
|
||||||
- [Character Attributes](/Help/Article/sceneInspector.characterAttributes)
|
- [Character Attributes](/Help/Article/sceneInspector.characterAttributes)
|
||||||
|
|||||||
@ -11,4 +11,4 @@ screenshot:
|
|||||||
|
|
||||||
# Overview
|
# 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.
|
||||||
|
|||||||
@ -11,7 +11,9 @@ screenshot:
|
|||||||
|
|
||||||
# Overview
|
# 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@ -11,4 +11,4 @@ screenshot:
|
|||||||
|
|
||||||
# Overview
|
# 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.
|
||||||
|
|||||||
146
PlotLine/Models/PlotLineWorkspaceModels.cs
Normal file
146
PlotLine/Models/PlotLineWorkspaceModels.cs
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
namespace PlotLine.Models;
|
||||||
|
|
||||||
|
public sealed class PlotLineWorkspaceData
|
||||||
|
{
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceLineRow> PlotLines { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceThreadRow> Threads { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceContributionRow> Contributions { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceTargetRow> Targets { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceDependencyRow> Dependencies { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceAttributionRow> AttributionScenes { get; init; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceSuggestionRow> 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; }
|
||||||
|
}
|
||||||
@ -103,6 +103,95 @@ public sealed class SubscriptionUsageSummary
|
|||||||
public long StorageMaximumBytes { get; set; }
|
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<int> FinalChapterCounts { get; init; } = [];
|
||||||
|
public IReadOnlyList<int> 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 sealed class StripeSubscriptionSyncState
|
||||||
{
|
{
|
||||||
public int? UserID { get; set; }
|
public int? UserID { get; set; }
|
||||||
|
|||||||
@ -23,6 +23,7 @@ public class Program
|
|||||||
builder.Services.AddControllersWithViews(options =>
|
builder.Services.AddControllersWithViews(options =>
|
||||||
{
|
{
|
||||||
options.Filters.Add<ProjectAccessFilter>();
|
options.Filters.Add<ProjectAccessFilter>();
|
||||||
|
options.Filters.Add<SubscriptionEnforcementFilter>();
|
||||||
});
|
});
|
||||||
builder.Services.AddSignalR(options =>
|
builder.Services.AddSignalR(options =>
|
||||||
{
|
{
|
||||||
@ -125,6 +126,7 @@ public class Program
|
|||||||
builder.Services.AddScoped<ITimelineSettingsRepository, TimelineSettingsRepository>();
|
builder.Services.AddScoped<ITimelineSettingsRepository, TimelineSettingsRepository>();
|
||||||
builder.Services.AddScoped<ISceneMetricTypeRepository, SceneMetricTypeRepository>();
|
builder.Services.AddScoped<ISceneMetricTypeRepository, SceneMetricTypeRepository>();
|
||||||
builder.Services.AddScoped<IPlotRepository, PlotRepository>();
|
builder.Services.AddScoped<IPlotRepository, PlotRepository>();
|
||||||
|
builder.Services.AddScoped<IPlotLineWorkspaceRepository, PlotLineWorkspaceRepository>();
|
||||||
builder.Services.AddScoped<IStoryIntelligenceNarrativeCandidateRepository, StoryIntelligenceNarrativeCandidateRepository>();
|
builder.Services.AddScoped<IStoryIntelligenceNarrativeCandidateRepository, StoryIntelligenceNarrativeCandidateRepository>();
|
||||||
builder.Services.AddScoped<IStoryIntelligenceReviewCandidateRepository, StoryIntelligenceReviewCandidateRepository>();
|
builder.Services.AddScoped<IStoryIntelligenceReviewCandidateRepository, StoryIntelligenceReviewCandidateRepository>();
|
||||||
builder.Services.AddScoped<IAssetRepository, AssetRepository>();
|
builder.Services.AddScoped<IAssetRepository, AssetRepository>();
|
||||||
@ -184,6 +186,7 @@ public class Program
|
|||||||
builder.Services.AddScoped<ISceneMetricTypeService, SceneMetricTypeService>();
|
builder.Services.AddScoped<ISceneMetricTypeService, SceneMetricTypeService>();
|
||||||
builder.Services.AddScoped<ISceneMetricValueService, SceneMetricValueService>();
|
builder.Services.AddScoped<ISceneMetricValueService, SceneMetricValueService>();
|
||||||
builder.Services.AddScoped<IPlotService, PlotService>();
|
builder.Services.AddScoped<IPlotService, PlotService>();
|
||||||
|
builder.Services.AddScoped<IPlotLineWorkspaceService, PlotLineWorkspaceService>();
|
||||||
builder.Services.AddScoped<IAssetService, AssetService>();
|
builder.Services.AddScoped<IAssetService, AssetService>();
|
||||||
builder.Services.AddScoped<ICharacterService, CharacterService>();
|
builder.Services.AddScoped<ICharacterService, CharacterService>();
|
||||||
builder.Services.AddScoped<ILocationService, LocationService>();
|
builder.Services.AddScoped<ILocationService, LocationService>();
|
||||||
@ -264,6 +267,7 @@ public class Program
|
|||||||
builder.Services.AddScoped<IIllustrationLibraryService, IllustrationLibraryService>();
|
builder.Services.AddScoped<IIllustrationLibraryService, IllustrationLibraryService>();
|
||||||
builder.Services.AddScoped<IProjectAccessService, ProjectAccessService>();
|
builder.Services.AddScoped<IProjectAccessService, ProjectAccessService>();
|
||||||
builder.Services.AddScoped<ISubscriptionService, SubscriptionService>();
|
builder.Services.AddScoped<ISubscriptionService, SubscriptionService>();
|
||||||
|
builder.Services.AddScoped<SubscriptionEnforcementFilter>();
|
||||||
builder.Services.AddScoped<IStripeBillingService, StripeBillingService>();
|
builder.Services.AddScoped<IStripeBillingService, StripeBillingService>();
|
||||||
builder.Services.AddSingleton<IHelpService, HelpService>();
|
builder.Services.AddSingleton<IHelpService, HelpService>();
|
||||||
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
|
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
|
||||||
|
|||||||
@ -18,7 +18,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo
|
|||||||
"Projects" or "Books" or "Chapters" or "Scenes" => "Overview",
|
"Projects" or "Books" or "Chapters" or "Scenes" => "Overview",
|
||||||
"StoryCalendar" => "Calendar", "StoryPoint" => "At This Point",
|
"StoryCalendar" => "Calendar", "StoryPoint" => "At This Point",
|
||||||
"RelationshipMap" => "Relationships", "StoryAssets" => "Assets",
|
"RelationshipMap" => "Relationships", "StoryAssets" => "Assets",
|
||||||
"FloorPlans" => "Floor Plans", "PlotThreads" => "Threads",
|
"FloorPlans" => "Floor Plans", "PlotThreads" => "Threads", "PlotLineWorkspace" => "Plot Lines",
|
||||||
"ProjectMetrics" => "Metrics", "StoryBible" => "Story Bible",
|
"ProjectMetrics" => "Metrics", "StoryBible" => "Story Bible",
|
||||||
"ContinuityExplorer" => "Continuity Explorer", "Analytics" or "Dynamics" => "Health",
|
"ContinuityExplorer" => "Continuity Explorer", "Analytics" or "Dynamics" => "Health",
|
||||||
"Archives" => "Archive", _ => controller
|
"Archives" => "Archive", _ => controller
|
||||||
|
|||||||
@ -31,7 +31,7 @@ public static class ApplicationRibbon
|
|||||||
new("book", "Book",
|
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("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("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("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("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"))),
|
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",
|
"Onboarding" => "story",
|
||||||
_ => section switch
|
_ => 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",
|
"Characters" or "Names" or "Relationships" => "characters",
|
||||||
"Locations" or "Assets" or "Floor Plans" => "world",
|
"Locations" or "Assets" or "Floor Plans" => "world",
|
||||||
"Story Bible" or "Metrics" or "Health" or "Warnings" or "Archive" => "tools", _ => "project"
|
"Story Bible" or "Metrics" or "Health" or "Warnings" or "Archive" => "tools", _ => "project"
|
||||||
|
|||||||
@ -1532,9 +1532,21 @@ public sealed class BookService(
|
|||||||
|
|
||||||
public async Task<BookSaveResult> SaveAsync(BookEditViewModel model)
|
public async Task<BookSaveResult> SaveAsync(BookEditViewModel model)
|
||||||
{
|
{
|
||||||
|
Guid? bookReservationId = null;
|
||||||
if (model.BookID == 0)
|
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))
|
if (!BookStatuses.IsValid(model.Status))
|
||||||
@ -1543,25 +1555,36 @@ public sealed class BookService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var isNew = model.BookID == 0;
|
var isNew = model.BookID == 0;
|
||||||
var bookId = await books.SaveAsync(new Book
|
int bookId;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
BookID = model.BookID,
|
bookId = await books.SaveAsync(new Book
|
||||||
ProjectID = model.ProjectID,
|
{
|
||||||
BookTitle = model.BookTitle,
|
BookID = model.BookID,
|
||||||
Subtitle = model.Subtitle,
|
ProjectID = model.ProjectID,
|
||||||
Tagline = model.Tagline,
|
BookTitle = model.BookTitle,
|
||||||
ShortDescription = model.ShortDescription,
|
Subtitle = model.Subtitle,
|
||||||
Status = model.Status,
|
Tagline = model.Tagline,
|
||||||
BookNumber = model.BookNumber,
|
ShortDescription = model.ShortDescription,
|
||||||
Description = model.Description,
|
Status = model.Status,
|
||||||
TargetWordCount = model.TargetWordCount,
|
BookNumber = model.BookNumber,
|
||||||
StoryEra = TrimOptional(model.StoryEra),
|
Description = model.Description,
|
||||||
PrimaryLocaleCode = TrimOptional(model.PrimaryLocaleCode),
|
TargetWordCount = model.TargetWordCount,
|
||||||
WritingStartDate = model.WritingStartDate,
|
StoryEra = TrimOptional(model.StoryEra),
|
||||||
TargetCompletionDate = model.TargetCompletionDate,
|
PrimaryLocaleCode = TrimOptional(model.PrimaryLocaleCode),
|
||||||
PublicationDate = model.PublicationDate,
|
WritingStartDate = model.WritingStartDate,
|
||||||
UsesExplicitScenes = model.UsesExplicitScenes
|
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);
|
await activity.RecordAsync(model.ProjectID, isNew ? "Created" : "Updated", "Book", bookId, model.BookTitle);
|
||||||
|
|
||||||
if (model.CoverUpload is { Length: > 0 })
|
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 needsPlotTimelineData = settings.ShowPlotLines || filter.PlotLineID.HasValue || filter.PlotThreadID.HasValue || filter.FocusType is "plotline" or "plotthread";
|
||||||
var needsMetricTimelineData = settings.ShowMetricShape && selectedMetricIds.Any();
|
var needsMetricTimelineData = settings.ShowMetricShape && selectedMetricIds.Any();
|
||||||
var needsAssetTimelineData = settings.ShowStoryAssets || filter.StoryAssetID.HasValue || filter.FocusType == "asset";
|
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 needsWarnings = settings.ShowWarnings || filter.WarningSeverityID.HasValue || filter.WarningTypeID.HasValue || filter.ShowWarningsOnly;
|
||||||
|
|
||||||
var timeline = await TimeTimelineLoadAsync(
|
var timeline = await TimeTimelineLoadAsync(
|
||||||
@ -2635,9 +2660,6 @@ public sealed class TimelineService(
|
|||||||
var assetLanes = settings.ShowStoryAssets
|
var assetLanes = settings.ShowStoryAssets
|
||||||
? await TimeTimelineLoadAsync("TimelineService.BuildAssetLanes", () => Task.FromResult(BuildAssetLanes(assetTimeline.Assets, assetTimeline.Events, orderedScenes)), projectId, bookId)
|
? 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
|
var selectedContext = selectedSceneId.HasValue
|
||||||
? await TimeTimelineLoadAsync("StoryContextService.GetForSceneAsync", () => storyContext.GetForSceneAsync(selectedSceneId.Value, projectId, bookId), projectId, bookId)
|
? await TimeTimelineLoadAsync("StoryContextService.GetForSceneAsync", () => storyContext.GetForSceneAsync(selectedSceneId.Value, projectId, bookId), projectId, bookId)
|
||||||
: null;
|
: null;
|
||||||
@ -2716,7 +2738,7 @@ public sealed class TimelineService(
|
|||||||
MetricGraphs = metricGraphs,
|
MetricGraphs = metricGraphs,
|
||||||
PlotLanes = plotLanes,
|
PlotLanes = plotLanes,
|
||||||
AssetLanes = assetLanes,
|
AssetLanes = assetLanes,
|
||||||
CharacterLanes = characterLanes,
|
CharacterLanes = [],
|
||||||
SceneOverviews = sceneOverviews,
|
SceneOverviews = sceneOverviews,
|
||||||
WarningsByScene = warningsByScene,
|
WarningsByScene = warningsByScene,
|
||||||
MatchingSceneIDs = matchingSceneIds,
|
MatchingSceneIDs = matchingSceneIds,
|
||||||
@ -2750,7 +2772,6 @@ public sealed class TimelineService(
|
|||||||
ShowMetricShape = settings.ShowMetricShape,
|
ShowMetricShape = settings.ShowMetricShape,
|
||||||
ShowPlotLines = settings.ShowPlotLines,
|
ShowPlotLines = settings.ShowPlotLines,
|
||||||
ShowStoryAssets = settings.ShowStoryAssets,
|
ShowStoryAssets = settings.ShowStoryAssets,
|
||||||
ShowCharacterAppearances = settings.ShowCharacterAppearances,
|
|
||||||
ShowWarnings = settings.ShowWarnings,
|
ShowWarnings = settings.ShowWarnings,
|
||||||
SelectedMetricTypeIDs = selectedMetricIds.ToList(),
|
SelectedMetricTypeIDs = selectedMetricIds.ToList(),
|
||||||
MetricOptions = metricTypes
|
MetricOptions = metricTypes
|
||||||
@ -2782,7 +2803,7 @@ public sealed class TimelineService(
|
|||||||
ShowMetricShape = model.ShowMetricShape,
|
ShowMetricShape = model.ShowMetricShape,
|
||||||
ShowPlotLines = model.ShowPlotLines,
|
ShowPlotLines = model.ShowPlotLines,
|
||||||
ShowStoryAssets = model.ShowStoryAssets,
|
ShowStoryAssets = model.ShowStoryAssets,
|
||||||
ShowCharacterAppearances = model.ShowCharacterAppearances,
|
ShowCharacterAppearances = false,
|
||||||
ShowWarnings = model.ShowWarnings
|
ShowWarnings = model.ShowWarnings
|
||||||
}, model.SelectedMetricTypeIDs);
|
}, model.SelectedMetricTypeIDs);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,7 +14,7 @@ public interface IImportService
|
|||||||
Task<string> BuildValidationReportAsync(ImportIndexViewModel model);
|
Task<string> BuildValidationReportAsync(ImportIndexViewModel model);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ILogger<ImportService> logger) : IImportService
|
public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ISubscriptionService subscriptions, ILogger<ImportService> logger) : IImportService
|
||||||
{
|
{
|
||||||
private const int TitleMaxLength = 200;
|
private const int TitleMaxLength = 200;
|
||||||
private const int RelativeTimeMaxLength = 200;
|
private const int RelativeTimeMaxLength = 200;
|
||||||
@ -136,6 +136,18 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
|||||||
return BuildDryRunResult(preview);
|
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
|
try
|
||||||
{
|
{
|
||||||
var timer = Stopwatch.StartNew();
|
var timer = Stopwatch.StartNew();
|
||||||
@ -167,6 +179,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
|||||||
TechnicalDetail = ex.Message
|
TechnicalDetail = ex.Message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (reservation.ReservationID.HasValue)
|
||||||
|
{
|
||||||
|
await subscriptions.ReleaseBookSlotReservationAsync(reservation.ReservationID.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<string> BuildValidationReportAsync(ImportIndexViewModel model)
|
public async Task<string> BuildValidationReportAsync(ImportIndexViewModel model)
|
||||||
@ -381,6 +400,18 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
|||||||
return BuildBackupDryRunResult(preview);
|
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
|
try
|
||||||
{
|
{
|
||||||
var projectName = preview.HasDuplicateProjectTitle
|
var projectName = preview.HasDuplicateProjectTitle
|
||||||
@ -455,6 +486,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
|||||||
TechnicalDetail = ex.Message
|
TechnicalDetail = ex.Message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (reservation.ReservationID.HasValue)
|
||||||
|
{
|
||||||
|
await subscriptions.ReleaseBookSlotReservationAsync(reservation.ReservationID.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ImportResult BuildBackupDryRunResult(ImportPreview preview)
|
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."
|
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)
|
private static bool TryReadProjectBackup(string jsonText, out ProjectBackupExport? backup, out ImportValidationResult validation)
|
||||||
{
|
{
|
||||||
backup = null;
|
backup = null;
|
||||||
|
|||||||
217
PlotLine/Services/PlotLineWorkspaceService.cs
Normal file
217
PlotLine/Services/PlotLineWorkspaceService.cs
Normal file
@ -0,0 +1,217 @@
|
|||||||
|
using PlotLine.Data;
|
||||||
|
using PlotLine.Models;
|
||||||
|
using PlotLine.ViewModels;
|
||||||
|
|
||||||
|
namespace PlotLine.Services;
|
||||||
|
|
||||||
|
public interface IPlotLineWorkspaceService
|
||||||
|
{
|
||||||
|
Task<PlotLineWorkspaceViewModel?> GetAsync(int projectId, int? bookId, IEnumerable<int>? plotLineIds, IEnumerable<int>? threadIds, int? scenarioId, bool showSuggestions, bool unattributed);
|
||||||
|
Task<PlotLineWorkspaceInspectorViewModel?> GetInspectorAsync(int projectId, int? bookId, int sceneId, int? scenarioId);
|
||||||
|
Task<PlotLineWorkspaceManuscriptViewModel?> 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<PlotLineWorkspaceViewModel?> GetAsync(
|
||||||
|
int projectId,
|
||||||
|
int? bookId,
|
||||||
|
IEnumerable<int>? plotLineIds,
|
||||||
|
IEnumerable<int>? 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<PlotLineWorkspaceSuggestionRow>)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<PlotLineWorkspaceInspectorViewModel?> 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<PlotLineWorkspaceManuscriptViewModel?> 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<PlotLineWorkspaceSceneViewModel> Compose(
|
||||||
|
PlotLineWorkspaceData data,
|
||||||
|
IReadOnlyCollection<int> selectedLineIds,
|
||||||
|
IReadOnlyCollection<int>? 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<PlotLineWorkspaceSceneViewModel>();
|
||||||
|
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<PlotLineWorkspaceSceneMembershipViewModel> ComposeMemberships(
|
||||||
|
PlotLineWorkspaceData data,
|
||||||
|
IEnumerable<PlotLineWorkspaceContributionRow> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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" },
|
["FloorPlans"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "FloorPlan", ["floorPlanId"] = "FloorPlan", ["floorPlanFloorId"] = "FloorPlanFloor", ["floorPlanBlockId"] = "FloorPlanBlock", ["projectId"] = "Project" },
|
||||||
["PlotLines"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "PlotLine", ["plotLineId"] = "PlotLine", ["projectId"] = "Project" },
|
["PlotLines"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "PlotLine", ["plotLineId"] = "PlotLine", ["projectId"] = "Project" },
|
||||||
["PlotThreads"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "PlotThread", ["plotThreadId"] = "PlotThread", ["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" },
|
["ProjectMetrics"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project" },
|
||||||
["ProjectRestorePoints"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["id"] = "ProjectRestorePoint" },
|
["ProjectRestorePoints"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["id"] = "ProjectRestorePoint" },
|
||||||
["RelationshipMap"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene", ["focusCharacterId"] = "Character" },
|
["RelationshipMap"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene", ["focusCharacterId"] = "Character" },
|
||||||
|
|||||||
@ -17,35 +17,12 @@ public sealed class StoryIntelligenceEntitlementService(ISubscriptionService sub
|
|||||||
|
|
||||||
private async Task EnsureAllowedAsync(int userId)
|
private async Task EnsureAllowedAsync(int userId)
|
||||||
{
|
{
|
||||||
var subscription = await subscriptions.GetCurrentSubscriptionAsync(userId);
|
var decision = await subscriptions.CanUseFeatureAsync(userId, SubscriptionFeature.StoryIntelligence);
|
||||||
if (!IsActive(subscription, DateTime.UtcNow))
|
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
|
public interface IStoryIntelligenceCompletionNotificationService
|
||||||
|
|||||||
52
PlotLine/Services/SubscriptionEnforcementFilter.cs
Normal file
52
PlotLine/Services/SubscriptionEnforcementFilter.cs
Normal file
@ -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<string> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -13,10 +13,16 @@ public interface ISubscriptionService
|
|||||||
Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId);
|
Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId);
|
||||||
Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId);
|
Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId);
|
||||||
Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId);
|
Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId);
|
||||||
|
Task<SubscriptionLimitResult> CanCreateCharactersAsync(int projectId, int userId, int additionalCount);
|
||||||
Task<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId);
|
Task<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId);
|
||||||
Task<StorageUsage> GetStorageUsageAsync(int userId);
|
Task<StorageUsage> GetStorageUsageAsync(int userId);
|
||||||
Task<SubscriptionUsageSummary> GetUsageSummaryAsync(int userId);
|
Task<SubscriptionUsageSummary> GetUsageSummaryAsync(int userId);
|
||||||
Task<StorageLimitResult> CanUploadFileAsync(int userId, long fileSizeBytes);
|
Task<StorageLimitResult> CanUploadFileAsync(int userId, long fileSizeBytes);
|
||||||
|
Task<EffectiveEntitlement> GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null);
|
||||||
|
Task<EntitlementDecision> CanUseFeatureAsync(int userId, SubscriptionFeature feature, DateTime? utcNow = null);
|
||||||
|
Task<BookSlotReservation> ReserveBookSlotsAsync(int userId, int requestedSlots = 1, DateTime? utcNow = null);
|
||||||
|
Task ReleaseBookSlotReservationAsync(Guid reservationId);
|
||||||
|
Task<EntitlementDecision> CanUseResourcesAsync(int userId, SubscriptionResourceRequest request, DateTime? utcNow = null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class SubscriptionService(ISubscriptionRepository subscriptions, IUserFileRepository userFiles) : ISubscriptionService
|
public sealed class SubscriptionService(ISubscriptionRepository subscriptions, IUserFileRepository userFiles) : ISubscriptionService
|
||||||
@ -40,42 +46,52 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I
|
|||||||
|
|
||||||
public async Task<SubscriptionLimitResult> CanCreateBookAsync(int userId)
|
public async Task<SubscriptionLimitResult> CanCreateBookAsync(int userId)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
var currentUsage = await subscriptions.GetOwnedBookCountAsync(userId);
|
var currentUsage = await subscriptions.GetOwnedBookCountAsync(userId);
|
||||||
return Evaluate(subscription, currentUsage, subscription.MaxBooks, "books");
|
return Evaluate(subscription, currentUsage, subscription.MaxBooks, "books");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId)
|
public async Task<SubscriptionLimitResult> CanCreateChapterAsync(int bookId, int userId)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
var currentUsage = await subscriptions.GetChapterCountForBookAsync(bookId);
|
var currentUsage = await subscriptions.GetChapterCountForBookAsync(bookId);
|
||||||
return Evaluate(subscription, currentUsage, subscription.MaxChaptersPerBook, "chapters per book");
|
return Evaluate(subscription, currentUsage, subscription.MaxChaptersPerBook, "chapters per book");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId)
|
public async Task<SubscriptionLimitResult> CanCreateSceneAsync(int bookId, int userId)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
var currentUsage = await subscriptions.GetSceneCountForBookAsync(bookId);
|
var currentUsage = await subscriptions.GetSceneCountForBookAsync(bookId);
|
||||||
return Evaluate(subscription, currentUsage, subscription.MaxScenesPerBook, "scenes per book");
|
return Evaluate(subscription, currentUsage, subscription.MaxScenesPerBook, "scenes per book");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId)
|
public async Task<SubscriptionLimitResult> CanCreateCharacterAsync(int projectId, int userId)
|
||||||
|
=> await CanCreateCharactersAsync(projectId, userId, 1);
|
||||||
|
|
||||||
|
public async Task<SubscriptionLimitResult> CanCreateCharactersAsync(int projectId, int userId, int additionalCount)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
var currentUsage = await subscriptions.GetCharacterCountForProjectAsync(projectId);
|
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<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId)
|
public async Task<SubscriptionLimitResult> CanInviteCollaboratorAsync(int userId)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
var currentUsage = await subscriptions.GetCollaboratorCountForOwnerAsync(userId);
|
var currentUsage = await subscriptions.GetCollaboratorCountForOwnerAsync(userId);
|
||||||
return Evaluate(subscription, currentUsage, subscription.MaxCollaborators, "collaborators");
|
return Evaluate(subscription, currentUsage, subscription.MaxCollaborators, "collaborators");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<StorageUsage> GetStorageUsageAsync(int userId)
|
public async Task<StorageUsage> GetStorageUsageAsync(int userId)
|
||||||
{
|
{
|
||||||
var subscription = await GetRequiredSubscriptionAsync(userId);
|
var subscription = await GetRequiredEffectiveLevelAsync(userId);
|
||||||
return new StorageUsage
|
return new StorageUsage
|
||||||
{
|
{
|
||||||
UsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId),
|
UsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId),
|
||||||
@ -85,7 +101,9 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I
|
|||||||
|
|
||||||
public async Task<SubscriptionUsageSummary> GetUsageSummaryAsync(int userId)
|
public async Task<SubscriptionUsageSummary> 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);
|
var usage = await subscriptions.GetUsageSummaryForOwnerAsync(userId);
|
||||||
usage.StorageUsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId);
|
usage.StorageUsedBytes = await userFiles.GetStorageUsageForOwnerAsync(userId);
|
||||||
usage.StorageMaximumBytes = ToBytes(subscription.MaxStorageMB);
|
usage.StorageMaximumBytes = ToBytes(subscription.MaxStorageMB);
|
||||||
@ -103,18 +121,143 @@ public sealed class SubscriptionService(ISubscriptionRepository subscriptions, I
|
|||||||
return StorageLimitResult.Blocked(usage.UsedBytes, usage.MaximumBytes, fileSizeBytes);
|
return StorageLimitResult.Blocked(usage.UsedBytes, usage.MaximumBytes, fileSizeBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<UserSubscriptionDetail> GetRequiredSubscriptionAsync(int userId)
|
public async Task<EffectiveEntitlement> GetEffectiveEntitlementAsync(int userId, DateTime? utcNow = null)
|
||||||
{
|
{
|
||||||
var subscription = await subscriptions.GetCurrentSubscriptionAsync(userId);
|
var now = utcNow ?? DateTime.UtcNow;
|
||||||
if (subscription is null)
|
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<EntitlementDecision> CanUseFeatureAsync(int userId, SubscriptionFeature feature, DateTime? utcNow = null)
|
||||||
|
{
|
||||||
|
var entitlement = await GetEffectiveEntitlementAsync(userId, utcNow);
|
||||||
|
return entitlement.IsActive
|
||||||
|
? new EntitlementDecision { Allowed = true, Code = "allowed", Entitlement = entitlement }
|
||||||
|
: new EntitlementDecision { Allowed = false, Code = entitlement.IsTrialExpired ? "trial_expired" : "subscription_inactive", Message = entitlement.Reason, Entitlement = entitlement };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<BookSlotReservation> ReserveBookSlotsAsync(int userId, int requestedSlots = 1, DateTime? utcNow = null)
|
||||||
|
{
|
||||||
|
if (requestedSlots <= 0)
|
||||||
|
{
|
||||||
|
return new BookSlotReservation { Allowed = true };
|
||||||
|
}
|
||||||
|
|
||||||
|
var decision = await CanUseFeatureAsync(userId, SubscriptionFeature.EditContent, utcNow);
|
||||||
|
if (!decision.Allowed)
|
||||||
|
{
|
||||||
|
return new BookSlotReservation { Allowed = false, Message = decision.Message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return await subscriptions.TryReserveBookSlotsAsync(userId, requestedSlots, utcNow ?? DateTime.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task ReleaseBookSlotReservationAsync(Guid reservationId) => subscriptions.ReleaseBookSlotReservationAsync(reservationId);
|
||||||
|
|
||||||
|
public async Task<EntitlementDecision> CanUseResourcesAsync(int userId, SubscriptionResourceRequest request, DateTime? utcNow = null)
|
||||||
|
{
|
||||||
|
var entitlement = await GetEffectiveEntitlementAsync(userId, utcNow);
|
||||||
|
var level = entitlement.EffectiveLevel;
|
||||||
|
if (!entitlement.IsActive || level is null)
|
||||||
|
{
|
||||||
|
return Denied(entitlement, entitlement.IsTrialExpired ? "trial_expired" : "subscription_inactive", entitlement.Reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
var booksUsed = await subscriptions.GetOwnedBookCountAsync(userId);
|
||||||
|
if (level.MaxBooks < PracticalUnlimited && booksUsed + request.AdditionalBooks > level.MaxBooks)
|
||||||
|
{
|
||||||
|
return Denied(entitlement, "book_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxBooks:N0} books.");
|
||||||
|
}
|
||||||
|
if (level.MaxChaptersPerBook < PracticalUnlimited && request.FinalChapterCounts.Any(count => count > level.MaxChaptersPerBook))
|
||||||
|
{
|
||||||
|
return Denied(entitlement, "chapter_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxChaptersPerBook:N0} chapters per book.");
|
||||||
|
}
|
||||||
|
if (level.MaxScenesPerBook < PracticalUnlimited && request.FinalSceneCounts.Any(count => count > level.MaxScenesPerBook))
|
||||||
|
{
|
||||||
|
return Denied(entitlement, "scene_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxScenesPerBook:N0} scenes per book.");
|
||||||
|
}
|
||||||
|
if (request.FinalCharacterCount.HasValue && level.MaxCharactersPerProject < PracticalUnlimited
|
||||||
|
&& request.FinalCharacterCount.Value > level.MaxCharactersPerProject)
|
||||||
|
{
|
||||||
|
return Denied(entitlement, "character_limit", $"This operation would exceed the {level.DisplayName} limit of {level.MaxCharactersPerProject:N0} characters per project.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EntitlementDecision { Allowed = true, Code = "allowed", Entitlement = entitlement };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<SubscriptionLevel> GetRequiredEffectiveLevelAsync(int userId)
|
||||||
|
{
|
||||||
|
var entitlement = await GetEffectiveEntitlementAsync(userId);
|
||||||
|
if (!entitlement.IsActive || entitlement.EffectiveLevel is null)
|
||||||
|
{
|
||||||
|
throw new SubscriptionLimitException(entitlement.Reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
return entitlement.EffectiveLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SubscriptionLimitResult Evaluate(SubscriptionLevel subscription, int currentUsage, int maximumAllowed, string limitName)
|
||||||
{
|
{
|
||||||
if (maximumAllowed >= PracticalUnlimited || currentUsage < maximumAllowed)
|
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.");
|
$"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;
|
private static long ToBytes(int megabytes) => megabytes * 1024L * 1024L;
|
||||||
|
|
||||||
internal static bool HasPaidBillingRisk(UserSubscriptionDetail? subscription, DateTime utcNow)
|
internal static bool HasPaidBillingRisk(UserSubscriptionDetail? subscription, DateTime utcNow)
|
||||||
|
|||||||
@ -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("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("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("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("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("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"),
|
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"),
|
||||||
|
|||||||
@ -41,7 +41,8 @@ public sealed class WordCompanionService(
|
|||||||
IWordCompanionRepository repository,
|
IWordCompanionRepository repository,
|
||||||
IManuscriptDocumentRepository manuscriptDocuments,
|
IManuscriptDocumentRepository manuscriptDocuments,
|
||||||
ICurrentUserService currentUser,
|
ICurrentUserService currentUser,
|
||||||
INameIntelligenceService nameIntelligence) : IWordCompanionService
|
INameIntelligenceService nameIntelligence,
|
||||||
|
ISubscriptionService subscriptions) : IWordCompanionService
|
||||||
{
|
{
|
||||||
private const int CharacterDiscoveryMinimumMentions = 2;
|
private const int CharacterDiscoveryMinimumMentions = 2;
|
||||||
private const int CharacterCreationSelectionLimit = 250;
|
private const int CharacterCreationSelectionLimit = 250;
|
||||||
@ -133,15 +134,32 @@ public sealed class WordCompanionService(
|
|||||||
return new WordCompanionBooksResponse { Books = books };
|
return new WordCompanionBooksResponse { Books = books };
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<WordCompanionCreateBookResponse?> CreateBookAsync(int projectId, WordCompanionCreateBookRequest request)
|
public async Task<WordCompanionCreateBookResponse?> CreateBookAsync(int projectId, WordCompanionCreateBookRequest request)
|
||||||
{
|
{
|
||||||
if (projectId <= 0 || string.IsNullOrWhiteSpace(request.Title))
|
if (projectId <= 0 || string.IsNullOrWhiteSpace(request.Title))
|
||||||
{
|
{
|
||||||
return Task.FromResult<WordCompanionCreateBookResponse?>(null);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
request.Title = request.Title.Trim();
|
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<WordCompanionBookStructureResponse?> GetBookStructureAsync(int bookId)
|
public Task<WordCompanionBookStructureResponse?> GetBookStructureAsync(int bookId)
|
||||||
@ -183,7 +201,7 @@ public sealed class WordCompanionService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
request.Title = request.Title.Trim();
|
request.Title = request.Title.Trim();
|
||||||
return repository.CreateChapterAsync(bookId, RequireUserId(), request);
|
return CreateChapterWithEntitlementAsync(bookId, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<WordCompanionCreateSceneResponse?> CreateSceneAsync(int bookId, int chapterId, WordCompanionCreateSceneRequest request)
|
public Task<WordCompanionCreateSceneResponse?> CreateSceneAsync(int bookId, int chapterId, WordCompanionCreateSceneRequest request)
|
||||||
@ -194,10 +212,24 @@ public sealed class WordCompanionService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
request.SceneTitle = request.SceneTitle.Trim();
|
request.SceneTitle = request.SceneTitle.Trim();
|
||||||
return repository.CreateSceneAsync(bookId, chapterId, RequireUserId(), request);
|
return CreateSceneWithEntitlementAsync(bookId, chapterId, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<WordCompanionSyncSceneResponse?> SyncSceneAsync(int bookId, WordCompanionSyncSceneRequest request)
|
private async Task<WordCompanionCreateChapterResponse?> 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<WordCompanionCreateSceneResponse?> 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<WordCompanionSyncSceneResponse?> SyncSceneAsync(int bookId, WordCompanionSyncSceneRequest request)
|
||||||
{
|
{
|
||||||
if (bookId <= 0
|
if (bookId <= 0
|
||||||
|| string.IsNullOrWhiteSpace(request.ChapterTitle)
|
|| string.IsNullOrWhiteSpace(request.ChapterTitle)
|
||||||
@ -206,15 +238,24 @@ public sealed class WordCompanionService(
|
|||||||
|| request.ChapterSortOrder is <= 0
|
|| request.ChapterSortOrder is <= 0
|
||||||
|| request.SceneSortOrder is <= 0)
|
|| request.SceneSortOrder is <= 0)
|
||||||
{
|
{
|
||||||
return Task.FromResult<WordCompanionSyncSceneResponse?>(null);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
request.ChapterTitle = request.ChapterTitle.Trim();
|
request.ChapterTitle = request.ChapterTitle.Trim();
|
||||||
request.SceneTitle = request.SceneTitle.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<WordCompanionSyncManuscriptResponse?> SyncManuscriptAsync(int bookId, WordCompanionSyncManuscriptRequest request)
|
public async Task<WordCompanionSyncManuscriptResponse?> SyncManuscriptAsync(int bookId, WordCompanionSyncManuscriptRequest request)
|
||||||
{
|
{
|
||||||
if (bookId <= 0 || request.Chapters.Any(chapter =>
|
if (bookId <= 0 || request.Chapters.Any(chapter =>
|
||||||
string.IsNullOrWhiteSpace(chapter.Title)
|
string.IsNullOrWhiteSpace(chapter.Title)
|
||||||
@ -222,7 +263,7 @@ public sealed class WordCompanionService(
|
|||||||
|| chapter.SortOrder is <= 0
|
|| chapter.SortOrder is <= 0
|
||||||
|| chapter.Scenes.Any(scene => string.IsNullOrWhiteSpace(scene.Title) || scene.WordCount < 0 || scene.SortOrder is <= 0)))
|
|| chapter.Scenes.Any(scene => string.IsNullOrWhiteSpace(scene.Title) || scene.WordCount < 0 || scene.SortOrder is <= 0)))
|
||||||
{
|
{
|
||||||
return Task.FromResult<WordCompanionSyncManuscriptResponse?>(null);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var chapter in request.Chapters)
|
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<WordCompanionUpdateSceneLinksResponse?> UpdateSceneLinksAsync(int sceneId, WordCompanionUpdateSceneLinksRequest request)
|
public Task<WordCompanionUpdateSceneLinksResponse?> UpdateSceneLinksAsync(int sceneId, WordCompanionUpdateSceneLinksRequest request)
|
||||||
@ -593,11 +635,11 @@ public sealed class WordCompanionService(
|
|||||||
private static string FirstName(string? value)
|
private static string FirstName(string? value)
|
||||||
=> (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;
|
=> (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;
|
||||||
|
|
||||||
public Task<WordCompanionCreateDiscoveredCharactersResponse?> CreateDiscoveredCharactersAsync(WordCompanionCreateDiscoveredCharactersRequest request)
|
public async Task<WordCompanionCreateDiscoveredCharactersResponse?> CreateDiscoveredCharactersAsync(WordCompanionCreateDiscoveredCharactersRequest request)
|
||||||
{
|
{
|
||||||
if (request.ProjectId <= 0 || request.CandidateNames.Count == 0)
|
if (request.ProjectId <= 0 || request.CandidateNames.Count == 0)
|
||||||
{
|
{
|
||||||
return Task.FromResult<WordCompanionCreateDiscoveredCharactersResponse?>(null);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
request.CandidateNames = request.CandidateNames
|
request.CandidateNames = request.CandidateNames
|
||||||
@ -607,9 +649,14 @@ public sealed class WordCompanionService(
|
|||||||
.Take(CharacterCreationSelectionLimit)
|
.Take(CharacterCreationSelectionLimit)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
return request.CandidateNames.Count == 0
|
if (request.CandidateNames.Count == 0)
|
||||||
? Task.FromResult<WordCompanionCreateDiscoveredCharactersResponse?>(null)
|
{
|
||||||
: repository.CreateDiscoveredCharactersAsync(RequireUserId(), request);
|
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<WordCompanionResolveSceneResponse?> ResolveSceneCoreAsync(int bookId, WordCompanionResolveSceneRequest request)
|
private async Task<WordCompanionResolveSceneResponse?> 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());
|
return await repository.ResolveSceneAsync(bookId, RequireUserId(), request.ChapterTitle!.Trim(), request.SceneTitle!.Trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task EnsureSyncResourcesAsync(int bookId, IReadOnlyList<WordCompanionSyncChapterRequest> 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()
|
private int RequireUserId()
|
||||||
{
|
{
|
||||||
return currentUser.UserId ?? throw new InvalidOperationException("An authenticated user is required.");
|
return currentUser.UserId ?? throw new InvalidOperationException("An authenticated user is required.");
|
||||||
|
|||||||
449
PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql
Normal file
449
PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql
Normal file
@ -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
|
||||||
294
PlotLine/Sql/204_PlotLineWorkspaceV1.sql
Normal file
294
PlotLine/Sql/204_PlotLineWorkspaceV1.sql
Normal file
@ -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
|
||||||
20
PlotLine/ViewComponents/EntitlementBannerViewComponent.cs
Normal file
20
PlotLine/ViewComponents/EntitlementBannerViewComponent.cs
Normal file
@ -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<IViewComponentResult> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -9,6 +9,7 @@ public sealed class ManageAccountViewModel
|
|||||||
public UserSubscriptionDetail? Subscription { get; set; }
|
public UserSubscriptionDetail? Subscription { get; set; }
|
||||||
public TrialVisibilityViewModel? Trial { get; set; }
|
public TrialVisibilityViewModel? Trial { get; set; }
|
||||||
public bool HasPaidBillingRisk { get; set; }
|
public bool HasPaidBillingRisk { get; set; }
|
||||||
|
public EffectiveEntitlement? Entitlement { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ManageSubscriptionViewModel
|
public sealed class ManageSubscriptionViewModel
|
||||||
@ -18,6 +19,7 @@ public sealed class ManageSubscriptionViewModel
|
|||||||
public TrialVisibilityViewModel? Trial { get; set; }
|
public TrialVisibilityViewModel? Trial { get; set; }
|
||||||
public SubscriptionUsageSummary? Usage { get; set; }
|
public SubscriptionUsageSummary? Usage { get; set; }
|
||||||
public IReadOnlyList<SubscriptionLevel> AvailableLevels { get; set; } = [];
|
public IReadOnlyList<SubscriptionLevel> AvailableLevels { get; set; } = [];
|
||||||
|
public EffectiveEntitlement? Entitlement { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class TrialVisibilityViewModel
|
public sealed class TrialVisibilityViewModel
|
||||||
@ -93,6 +95,47 @@ public sealed class PricingViewModel
|
|||||||
public bool IsSignedIn { get; set; }
|
public bool IsSignedIn { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class AdminSubscriptionsViewModel
|
||||||
|
{
|
||||||
|
public string? Search { get; set; }
|
||||||
|
public IReadOnlyList<SubscriptionAdminUserSummary> Users { get; set; } = [];
|
||||||
|
public AppUser? SelectedUser { get; set; }
|
||||||
|
public EffectiveEntitlement? Entitlement { get; set; }
|
||||||
|
public SubscriptionUsageSummary? Usage { get; set; }
|
||||||
|
public IReadOnlyList<SubscriptionLevel> 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 sealed class PublicPageViewModel
|
||||||
{
|
{
|
||||||
public string SupportEmail { get; set; } = "support@plotdirector.com";
|
public string SupportEmail { get; set; } = "support@plotdirector.com";
|
||||||
|
|||||||
@ -653,6 +653,7 @@ public sealed class SceneCharacterParticipationInputViewModel
|
|||||||
public string? OutfitDescription { get; set; }
|
public string? OutfitDescription { get; set; }
|
||||||
public string? PhysicalCondition { get; set; }
|
public string? PhysicalCondition { get; set; }
|
||||||
public string? EmotionalState { get; set; }
|
public string? EmotionalState { get; set; }
|
||||||
|
public string? KnowledgeNotes { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class StoryStateViewModel
|
public sealed class StoryStateViewModel
|
||||||
@ -1361,7 +1362,6 @@ public sealed class TimelineSettingsViewModel
|
|||||||
public bool ShowMetricShape { get; set; } = true;
|
public bool ShowMetricShape { get; set; } = true;
|
||||||
public bool ShowPlotLines { get; set; } = true;
|
public bool ShowPlotLines { get; set; } = true;
|
||||||
public bool ShowStoryAssets { get; set; }
|
public bool ShowStoryAssets { get; set; }
|
||||||
public bool ShowCharacterAppearances { get; set; }
|
|
||||||
public bool ShowWarnings { get; set; } = true;
|
public bool ShowWarnings { get; set; } = true;
|
||||||
public List<int> SelectedMetricTypeIDs { get; set; } = [];
|
public List<int> SelectedMetricTypeIDs { get; set; } = [];
|
||||||
public IReadOnlyList<TimelineMetricSettingOptionViewModel> MetricOptions { get; set; } = [];
|
public IReadOnlyList<TimelineMetricSettingOptionViewModel> MetricOptions { get; set; } = [];
|
||||||
|
|||||||
95
PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs
Normal file
95
PlotLine/ViewModels/PlotLineWorkspaceViewModels.cs
Normal file
@ -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<Book> Books { get; set; } = [];
|
||||||
|
public IReadOnlyList<Scenario> Scenarios { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceLineViewModel> PlotLines { get; set; } = [];
|
||||||
|
public IReadOnlyList<int> SelectedPlotLineIDs { get; set; } = [];
|
||||||
|
public IReadOnlyList<int> SelectedThreadIDs { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceSceneViewModel> Scenes { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceSuggestionSceneViewModel> SuggestedScenes { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceAttributionRow> ProposedOnlyScenes { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceAttributionRow> 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<PlotLineWorkspaceThreadRow> 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<PlotLineWorkspaceSceneMembershipViewModel> Memberships { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceDependencyRow> 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<PlotLineWorkspaceContributionRow> Contributions { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PlotLineWorkspaceSuggestionSceneViewModel
|
||||||
|
{
|
||||||
|
public PlotLineWorkspaceAttributionRow Scene { get; set; } = new();
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceSuggestionRow> 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<PlotLineWorkspaceSceneMembershipViewModel> Memberships { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceThreadRow> Threads { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceDependencyRow> Dependencies { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceTargetViewModel> Targets { get; set; } = [];
|
||||||
|
public IReadOnlyList<PlotLineWorkspaceSuggestionRow> 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; }
|
||||||
|
}
|
||||||
@ -4,76 +4,74 @@
|
|||||||
var summary = Model.FeatureRequestSummary;
|
var summary = Model.FeatureRequestSummary;
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="page-heading compact">
|
<div class="admin-dashboard">
|
||||||
<div>
|
<div class="page-heading compact admin-dashboard__heading">
|
||||||
<p class="eyebrow">Admin</p>
|
<div>
|
||||||
<h1>Dashboard</h1>
|
<p class="eyebrow">Admin</p>
|
||||||
<p class="lead-text">Operational tools for PlotDirector administrators.</p>
|
<h1>Dashboard</h1>
|
||||||
|
<p class="lead-text">Operational tools for PlotDirector administrators.</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav class="mb-3" aria-label="Breadcrumb">
|
<nav class="mb-3" aria-label="Breadcrumb">
|
||||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||||
<span class="muted"> / Admin</span>
|
<span class="muted"> / Admin</span>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
@if (TempData["AdminMessage"] is string adminMessage)
|
@if (TempData["AdminMessage"] is string adminMessage)
|
||||||
{
|
{
|
||||||
<div class="alert alert-success">@adminMessage</div>
|
<div class="alert alert-success">@adminMessage</div>
|
||||||
}
|
}
|
||||||
@if (TempData["AdminError"] is string adminError)
|
@if (TempData["AdminError"] is string adminError)
|
||||||
{
|
{
|
||||||
<div class="alert alert-danger">@adminError</div>
|
<div class="alert alert-danger">@adminError</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="edit-panel">
|
<section class="edit-panel admin-dashboard__feature-panel">
|
||||||
<div class="row g-3">
|
<div class="admin-dashboard__section-heading">
|
||||||
<div class="col-md-4">
|
<p class="eyebrow">User feedback</p>
|
||||||
<a class="text-decoration-none" asp-action="FeatureRequests">
|
<h2>Feature requests</h2>
|
||||||
<div class="border rounded p-3 h-100">
|
</div>
|
||||||
|
|
||||||
|
<div class="admin-dashboard__summary-grid">
|
||||||
|
<a class="admin-dashboard__metric" asp-action="FeatureRequests">
|
||||||
|
<div>
|
||||||
<p class="eyebrow">Open requests</p>
|
<p class="eyebrow">Open requests</p>
|
||||||
<h2 class="mb-0">@summary.TotalOpenRequests.ToString("N0")</h2>
|
<h2 class="mb-0">@summary.TotalOpenRequests.ToString("N0")</h2>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
<a class="admin-dashboard__metric" asp-action="FeatureRequests">
|
||||||
<div class="col-md-4">
|
<div>
|
||||||
<a class="text-decoration-none" asp-action="FeatureRequests">
|
|
||||||
<div class="border rounded p-3 h-100">
|
|
||||||
<p class="eyebrow">Awaiting admin reply</p>
|
<p class="eyebrow">Awaiting admin reply</p>
|
||||||
<h2 class="mb-0">@summary.AwaitingAdminReply.ToString("N0")</h2>
|
<h2 class="mb-0">@summary.AwaitingAdminReply.ToString("N0")</h2>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
<a class="admin-dashboard__metric" asp-action="FeatureRequests" asp-route-status="@FeatureRequestStatuses.NeedsDetail">
|
||||||
<div class="col-md-4">
|
<div>
|
||||||
<a class="text-decoration-none" asp-action="FeatureRequests" asp-route-status="@FeatureRequestStatuses.NeedsDetail">
|
|
||||||
<div class="border rounded p-3 h-100">
|
|
||||||
<p class="eyebrow">Awaiting user reply</p>
|
<p class="eyebrow">Awaiting user reply</p>
|
||||||
<h2 class="mb-0">@summary.AwaitingUserReply.ToString("N0")</h2>
|
<h2 class="mb-0">@summary.AwaitingUserReply.ToString("N0")</h2>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="edit-panel">
|
<div class="admin-dashboard__status-section">
|
||||||
<h2>Feature request status</h2>
|
<h3>Request status</h3>
|
||||||
<div class="row g-3">
|
<div class="admin-dashboard__status-grid">
|
||||||
@foreach (var status in summary.Statuses)
|
@foreach (var status in summary.Statuses)
|
||||||
{
|
{
|
||||||
<div class="col-sm-6 col-lg-3">
|
<a class="admin-dashboard__status-card" asp-action="FeatureRequests" asp-route-status="@status.Status">
|
||||||
<a class="text-decoration-none" asp-action="FeatureRequests" asp-route-status="@status.Status">
|
<div>
|
||||||
<div class="border rounded p-3 h-100">
|
|
||||||
<p class="eyebrow">@status.Status</p>
|
<p class="eyebrow">@status.Status</p>
|
||||||
<h3 class="mb-0">@status.Count.ToString("N0")</h3>
|
<h3 class="mb-0">@status.Count.ToString("N0")</h3>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
</div>
|
||||||
</div>
|
</section>
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="project-card-grid">
|
<section class="admin-dashboard__tools" aria-label="Admin tools">
|
||||||
<article class="project-card">
|
<article class="project-card admin-dashboard__tool-card admin-dashboard__tool-card--feature-requests">
|
||||||
<div class="project-card__body">
|
<div class="project-card__body">
|
||||||
<p class="eyebrow">User feedback</p>
|
<p class="eyebrow">User feedback</p>
|
||||||
<h2>Feature Requests</h2>
|
<h2>Feature Requests</h2>
|
||||||
@ -83,7 +81,7 @@
|
|||||||
<a class="btn btn-primary btn-sm" asp-action="FeatureRequests">Open</a>
|
<a class="btn btn-primary btn-sm" asp-action="FeatureRequests">Open</a>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
<article class="project-card">
|
<article class="project-card admin-dashboard__tool-card admin-dashboard__tool-card--ai">
|
||||||
<div class="project-card__body">
|
<div class="project-card__body">
|
||||||
<p class="eyebrow">Story Intelligence</p>
|
<p class="eyebrow">Story Intelligence</p>
|
||||||
<h2>AI Diagnostics</h2>
|
<h2>AI Diagnostics</h2>
|
||||||
@ -100,7 +98,7 @@
|
|||||||
<a class="btn btn-outline-primary btn-sm" asp-action="StoryIntelligenceIllustrationLibrary">Illustration library</a>
|
<a class="btn btn-outline-primary btn-sm" asp-action="StoryIntelligenceIllustrationLibrary">Illustration library</a>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
<article class="project-card">
|
<article class="project-card admin-dashboard__tool-card admin-dashboard__tool-card--names">
|
||||||
<div class="project-card__body">
|
<div class="project-card__body">
|
||||||
<p class="eyebrow">Reference data</p>
|
<p class="eyebrow">Reference data</p>
|
||||||
<h2>Name Intelligence</h2>
|
<h2>Name Intelligence</h2>
|
||||||
@ -119,11 +117,13 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
<article class="project-card">
|
<article class="project-card admin-dashboard__tool-card admin-dashboard__tool-card--subscriptions">
|
||||||
<div class="project-card__body">
|
<div class="project-card__body">
|
||||||
<p class="eyebrow">Placeholder</p>
|
<p class="eyebrow">Administration</p>
|
||||||
<h2>Subscriptions</h2>
|
<h2>Subscriptions</h2>
|
||||||
<p class="project-card__description">Subscription management tools will be added later.</p>
|
<p class="project-card__description">Inspect billing and trial state, extend trials, and grant audited access overrides.</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="project-card__actions"><a class="btn btn-outline-primary btn-sm" asp-action="Subscriptions">Manage subscriptions</a></div>
|
||||||
</article>
|
</article>
|
||||||
</section>
|
</section>
|
||||||
|
</div>
|
||||||
|
|||||||
52
PlotLine/Views/Admin/Subscriptions.cshtml
Normal file
52
PlotLine/Views/Admin/Subscriptions.cshtml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
@model AdminSubscriptionsViewModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Subscription administration";
|
||||||
|
var entitlement = Model.Entitlement;
|
||||||
|
var underlying = entitlement?.UnderlyingSubscription;
|
||||||
|
}
|
||||||
|
<nav class="breadcrumb-trail" aria-label="Breadcrumb"><a asp-action="Index">Admin</a><span>Subscriptions</span></nav>
|
||||||
|
<div class="page-heading compact"><div><p class="eyebrow">Administration</p><h1>Subscription access</h1><p class="lead-text">Billing state and PlotDirector access are shown separately.</p></div></div>
|
||||||
|
@if (TempData["AdminMessage"] is string message) { <div class="alert alert-success">@message</div> }
|
||||||
|
@if (TempData["AdminError"] is string error) { <div class="alert alert-warning">@error</div> }
|
||||||
|
|
||||||
|
<section class="edit-panel">
|
||||||
|
<form method="get" class="row g-2 align-items-end">
|
||||||
|
<div class="col-md-8"><label class="form-label" for="search">Email or display name</label><input class="form-control" id="search" name="search" value="@Model.Search" /></div>
|
||||||
|
<div class="col-md-4"><button class="btn btn-primary" type="submit">Search users</button></div>
|
||||||
|
</form>
|
||||||
|
@if (Model.Users.Count > 0)
|
||||||
|
{
|
||||||
|
<div class="list-group mt-3">
|
||||||
|
@foreach (var user in Model.Users)
|
||||||
|
{
|
||||||
|
<a class="list-group-item list-group-item-action" asp-action="Subscriptions" asp-route-search="@Model.Search" asp-route-userId="@user.UserID">
|
||||||
|
<strong>@user.Email</strong> — @user.DisplayName <span class="text-muted">@(user.UnderlyingPlanName ?? "No subscription")</span>
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (Model.SelectedUser is not null && entitlement is not null)
|
||||||
|
{
|
||||||
|
<section class="edit-panel">
|
||||||
|
<h2>@Model.SelectedUser.Email</h2>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Paid / underlying plan</p><p>@(underlying?.DisplayName ?? "None")</p></div>
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Billing status</p><p>@(underlying?.StripeStatus ?? (underlying?.IsTrial == true ? "Application trial" : "Not supplied"))</p></div>
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Effective access</p><p><strong>@(entitlement.EffectiveLevel?.DisplayName ?? "Read only")</strong> — @entitlement.State</p></div>
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Trial start</p><p>@(underlying?.StartDateUTC.ToString("d MMMM yyyy 'UTC'") ?? "Not set")</p></div>
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Trial expiry</p><p>@(entitlement.TrialExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "Not set")</p></div>
|
||||||
|
<div class="col-md-4"><p class="eyebrow">Books</p><p>@(Model.Usage?.BooksUsed ?? 0) / @(entitlement.EffectiveLevel?.MaxBooks.ToString("N0") ?? "0")</p></div>
|
||||||
|
</div>
|
||||||
|
@if (entitlement.ActiveOverride is not null)
|
||||||
|
{
|
||||||
|
<div class="alert alert-info"><strong>Administrative override active.</strong> @entitlement.ActiveOverride.LevelDisplayName; expires @(entitlement.ActiveOverride.ExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "never"). This is not a paid subscription.</div>
|
||||||
|
<form asp-action="RevokeSubscriptionOverride" method="post" class="row g-2"><input type="hidden" name="UserID" value="@Model.SelectedUser.UserID" /><div class="col-md-8"><label class="form-label">Reason</label><input class="form-control" name="Reason" required maxlength="1000" /></div><div class="col-md-4 align-self-end"><button class="btn btn-outline-danger" type="submit">Remove override</button></div></form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-lg-6"><section class="edit-panel h-100"><h2>Change trial expiry</h2><form asp-action="ExtendTrial" method="post"><input type="hidden" name="UserID" value="@Model.SelectedUser.UserID" /><label class="form-label">Expiry (UTC)</label><input class="form-control" type="datetime-local" name="TrialExpiryDateUTC" value="@((entitlement.TrialExpiryDateUTC ?? DateTime.UtcNow.AddDays(30)).ToString("yyyy-MM-ddTHH:mm"))" required /><label class="form-label mt-2">Reason</label><textarea class="form-control" name="Reason" required maxlength="1000"></textarea><button class="btn btn-primary mt-3" type="submit">Update trial</button></form></section></div>
|
||||||
|
<div class="col-lg-6"><section class="edit-panel h-100"><h2>Administrative access override</h2><p class="muted">This changes effective access only. Stripe billing is not modified.</p><form asp-action="SaveSubscriptionOverride" method="post"><input type="hidden" name="UserID" value="@Model.SelectedUser.UserID" /><label class="form-label">Existing plan level</label><select class="form-select" name="SubscriptionLevelID" required>@foreach (var level in Model.Levels) { <option value="@level.SubscriptionLevelID">@level.DisplayName</option> }</select><label class="form-label mt-2">Starts (UTC)</label><input class="form-control" type="datetime-local" name="StartDateUTC" value="@DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm")" required /><label class="form-label mt-2">Optional expiry (UTC)</label><input class="form-control" type="datetime-local" name="ExpiryDateUTC" /><label class="form-label mt-2">Reason</label><textarea class="form-control" name="Reason" required maxlength="1000"></textarea><button class="btn btn-primary mt-3" type="submit">Grant override</button></form></section></div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@ -59,6 +59,10 @@
|
|||||||
|
|
||||||
<section class="edit-panel">
|
<section class="edit-panel">
|
||||||
<h2>Subscription</h2>
|
<h2>Subscription</h2>
|
||||||
|
@if (Model.Entitlement is not null && Model.Entitlement.IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="alert alert-warning">@Model.Entitlement.Reason</div>
|
||||||
|
}
|
||||||
@if (subscription is null)
|
@if (subscription is null)
|
||||||
{
|
{
|
||||||
<p class="muted">No active subscription is assigned.</p>
|
<p class="muted">No active subscription is assigned.</p>
|
||||||
|
|||||||
@ -29,6 +29,16 @@
|
|||||||
|
|
||||||
<section class="edit-panel">
|
<section class="edit-panel">
|
||||||
<h2>Current subscription</h2>
|
<h2>Current subscription</h2>
|
||||||
|
@if (Model.Entitlement is not null)
|
||||||
|
{
|
||||||
|
<div class="alert @(Model.Entitlement.IsActive ? "alert-info" : "alert-warning")">
|
||||||
|
<strong>Current access: @(Model.Entitlement.EffectiveLevel?.DisplayName ?? "Read only")</strong> — @Model.Entitlement.Reason
|
||||||
|
@if (Model.Entitlement.UsesAdministrativeOverride)
|
||||||
|
{
|
||||||
|
<span> Access ends @(Model.Entitlement.ActiveOverride?.ExpiryDateUTC?.ToString("d MMMM yyyy") ?? "only when removed").</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@if (subscription is null)
|
@if (subscription is null)
|
||||||
{
|
{
|
||||||
<p class="muted">No active subscription is assigned.</p>
|
<p class="muted">No active subscription is assigned.</p>
|
||||||
@ -45,11 +55,11 @@
|
|||||||
</div>
|
</div>
|
||||||
<a class="btn btn-primary btn-sm" asp-controller="Pricing" asp-action="Index">Upgrade</a>
|
<a class="btn btn-primary btn-sm" asp-controller="Pricing" asp-action="Index">Upgrade</a>
|
||||||
</div>
|
</div>
|
||||||
<p>Your 30-day @trial.PlanName trial started on @FormatDate(trial.StartDateUtc) and expires on @FormatDate(trial.ExpiryDateUtc).</p>
|
<p>Your 30-day @trial.PlanName trial started on @FormatDate(trial.StartDateUtc) and @(trial.IsExpired ? "ended" : "expires") on @FormatDate(trial.ExpiryDateUtc).</p>
|
||||||
<div class="trial-progress" aria-label="Trial progress">
|
<div class="trial-progress" aria-label="Trial progress">
|
||||||
<div class="trial-progress__bar" style="width: @trial.ProgressPercentage%"></div>
|
<div class="trial-progress__bar" style="width: @trial.ProgressPercentage%"></div>
|
||||||
</div>
|
</div>
|
||||||
<p class="muted mb-0">@trial.DaysElapsed days used, @trial.DaysRemaining days remaining.</p>
|
<p class="muted mb-0">@(trial.IsExpired ? "Your existing work remains available to read and export." : $"{trial.DaysElapsed} days used, {trial.DaysRemaining} days remaining.")</p>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
|
|||||||
177
PlotLine/Views/PlotLineWorkspace/Index.cshtml
Normal file
177
PlotLine/Views/PlotLineWorkspace/Index.cshtml
Normal file
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||||
|
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||||
|
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||||
|
<span>Plot Lines</span>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="page-heading plot-workspace-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Story map · @Model.Mode mode</p>
|
||||||
|
<h1>Plot Lines <help-icon key="plotLines.workspace" /></h1>
|
||||||
|
<p class="muted">Follow one line in Focus mode or select several to inspect the weave.</p>
|
||||||
|
</div>
|
||||||
|
<div class="button-row">
|
||||||
|
<a class="btn btn-outline-secondary" asp-controller="PlotLines" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Manage lines</a>
|
||||||
|
<a class="btn btn-outline-secondary" asp-controller="PlotThreads" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Manage threads</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="get" asp-action="Index" class="plot-workspace-controls" id="plot-workspace-form">
|
||||||
|
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||||
|
<div class="plot-control-row">
|
||||||
|
<label>Book
|
||||||
|
<select name="bookId" class="form-select" data-plot-submit>
|
||||||
|
<option value="">All books</option>
|
||||||
|
@foreach (var book in Model.Books)
|
||||||
|
{
|
||||||
|
<option value="@book.BookID" selected="@(book.BookID == Model.SelectedBookID)">@book.BookDisplayTitle</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>Order
|
||||||
|
<select name="scenarioId" class="form-select" data-plot-submit>
|
||||||
|
<option value="">Canonical manuscript</option>
|
||||||
|
@foreach (var scenario in Model.Scenarios)
|
||||||
|
{
|
||||||
|
<option value="@scenario.ScenarioID" selected="@(scenario.ScenarioID == Model.SelectedScenarioID)">Scenario: @scenario.ScenarioName</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>Find a scene
|
||||||
|
<input class="form-control" type="search" id="plot-scene-search" placeholder="Title, chapter, POV…" />
|
||||||
|
</label>
|
||||||
|
<label class="plot-toggle"><input type="checkbox" name="showSuggestions" value="true" checked="@Model.ShowSuggestions" data-plot-submit /> Show pending suggestions</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset class="plot-line-picker">
|
||||||
|
<legend>Plot lines</legend>
|
||||||
|
@foreach (var item in Model.PlotLines)
|
||||||
|
{
|
||||||
|
<label class="plot-line-choice" style="--line-colour:@item.Line.Colour">
|
||||||
|
<input type="checkbox" name="plotLineId" value="@item.Line.PlotLineID" checked="@item.IsSelected" data-line-choice />
|
||||||
|
<span class="plot-line-dot"></span>
|
||||||
|
<span>@item.Line.PlotLineName</span>
|
||||||
|
<small>@item.Line.ContributionSceneCount scenes</small>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
<a class="plot-unattributed-link" asp-action="Unattributed" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.SelectedBookID" asp-route-scenarioId="@Model.SelectedScenarioID">Unattributed scenes</a>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
@if (!Model.IsUnattributedMode && selectedThreads.Count > 0)
|
||||||
|
{
|
||||||
|
<details class="plot-thread-filter" open="@(Model.SelectedThreadIDs.Count > 0)">
|
||||||
|
<summary>Thread filter @(Model.SelectedThreadIDs.Count > 0 ? $"({Model.SelectedThreadIDs.Count})" : "")</summary>
|
||||||
|
<div>
|
||||||
|
@foreach (var thread in selectedThreads)
|
||||||
|
{
|
||||||
|
<label><input type="checkbox" name="threadId" value="@thread.PlotThreadID" checked="@Model.SelectedThreadIDs.Contains(thread.PlotThreadID)" data-plot-submit /> @thread.ThreadTitle <small>@thread.ContributionCount</small></label>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@if (Model.IsUnattributedMode)
|
||||||
|
{
|
||||||
|
<section class="plot-attribution-audit">
|
||||||
|
<div class="plot-audit-column">
|
||||||
|
<h2>Proposed only <span>@Model.ProposedOnlyScenes.Count</span></h2>
|
||||||
|
<p class="muted">No canonical plot-line contribution; one or more pending suggestions exist.</p>
|
||||||
|
@foreach (var scene in Model.ProposedOnlyScenes)
|
||||||
|
{
|
||||||
|
<button class="plot-audit-scene" type="button" data-scene-inspector="@scene.SceneID">
|
||||||
|
<strong>Ch @scene.ChapterNumber.ToString("0.##") · Scene @scene.SceneNumber.ToString("0.##")</strong>
|
||||||
|
<span>@scene.SceneTitle</span><small>@scene.ProposedCandidateNames</small>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="plot-audit-column">
|
||||||
|
<h2>No known attribution <span>@Model.NoKnownAttributionScenes.Count</span></h2>
|
||||||
|
<p class="muted">Neither a canonical contribution nor a pending suggestion is known.</p>
|
||||||
|
@foreach (var scene in Model.NoKnownAttributionScenes)
|
||||||
|
{
|
||||||
|
<button class="plot-audit-scene" type="button" data-scene-inspector="@scene.SceneID">
|
||||||
|
<strong>Ch @scene.ChapterNumber.ToString("0.##") · Scene @scene.SceneNumber.ToString("0.##")</strong>
|
||||||
|
<span>@scene.SceneTitle</span>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
else if (Model.Scenes.Count == 0)
|
||||||
|
{
|
||||||
|
<section class="empty-state"><h2>No contributions in this view</h2><p>Choose another plot line, book, scenario, or thread filter.</p></section>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<section class="plot-story-map" aria-label="Plot-line scene contribution map">
|
||||||
|
@foreach (var scene in Model.Scenes)
|
||||||
|
{
|
||||||
|
if (scene.GapBefore > 0)
|
||||||
|
{
|
||||||
|
<div class="plot-gap" title="Scenes without a selected-line contribution">
|
||||||
|
<span>@scene.GapBefore scene@(scene.GapBefore == 1 ? "" : "s") between contributions</span>
|
||||||
|
@if (scene.ChapterGapBefore > 0) { <small>@scene.ChapterGapBefore whole chapter@(scene.ChapterGapBefore == 1 ? "" : "s")</small> }
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<article class="plot-scene-card @(scene.IsShared ? "is-shared" : "")" data-plot-scene data-search-text="@($"{scene.SceneTitle} {scene.ChapterTitle} {scene.PovCharacterName} {scene.LocationName}")">
|
||||||
|
<button type="button" class="plot-scene-open" data-scene-inspector="@scene.SceneID" aria-label="Inspect @scene.SceneTitle">
|
||||||
|
<span class="plot-scene-kicker">Ch @scene.ChapterNumber.ToString("0.##") · Scene @scene.SceneNumber.ToString("0.##")</span>
|
||||||
|
<strong>@scene.SceneTitle</strong>
|
||||||
|
@if (!string.IsNullOrWhiteSpace(scene.Summary)) { <span class="plot-scene-summary">@scene.Summary</span> }
|
||||||
|
</button>
|
||||||
|
<div class="plot-scene-memberships">
|
||||||
|
@foreach (var membership in scene.Memberships)
|
||||||
|
{
|
||||||
|
<div class="plot-membership" style="--line-colour:@membership.Colour">
|
||||||
|
<span class="plot-route"></span>
|
||||||
|
<div><strong>@membership.PlotLineName</strong>
|
||||||
|
@foreach (var contribution in membership.Contributions)
|
||||||
|
{
|
||||||
|
<span class="plot-contribution-role">@contribution.CanonicalRole · @contribution.ThreadTitle</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<footer>
|
||||||
|
@if (scene.IsShared) { <span class="badge text-bg-primary">Shared junction</span> }
|
||||||
|
@if (!string.IsNullOrWhiteSpace(scene.PovCharacterName)) { <span>POV @scene.PovCharacterName</span> }
|
||||||
|
@if (!string.IsNullOrWhiteSpace(scene.LocationName)) { <span>@scene.LocationName</span> }
|
||||||
|
@if (scene.WarningCount > 0) { <span class="text-warning">@scene.WarningCount warning@(scene.WarningCount == 1 ? "" : "s")</span> }
|
||||||
|
@if (scene.DependencyCount > 0) { <span>@scene.DependencyCount connection@(scene.DependencyCount == 1 ? "" : "s")</span> }
|
||||||
|
@if (scene.StructuralTargetCount > 0) { <span>@scene.StructuralTargetCount cross-line connection@(scene.StructuralTargetCount == 1 ? "" : "s")</span> }
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.ShowSuggestions && Model.SuggestedScenes.Count > 0)
|
||||||
|
{
|
||||||
|
<section class="plot-suggestion-panel">
|
||||||
|
<h2>Pending suggestions <span>@Model.SuggestedScenes.Count scenes</span></h2>
|
||||||
|
<p class="muted">Suggestions are review context, not canonical plot-line contributions.</p>
|
||||||
|
@foreach (var item in Model.SuggestedScenes.Take(60))
|
||||||
|
{
|
||||||
|
<button type="button" data-scene-inspector="@item.Scene.SceneID"><strong>@item.Scene.SceneTitle</strong><span>@string.Join(" · ", item.Suggestions.Select(x => x.CandidateTitle).Distinct())</span></button>
|
||||||
|
}
|
||||||
|
@if (Model.SuggestedScenes.Count > 60) { <p class="muted">Showing the first 60 scenes. Narrow to a book for a smaller review set.</p> }
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="plot-inspector-backdrop" id="plot-inspector-backdrop" hidden></div>
|
||||||
|
<aside class="plot-inspector" id="plot-inspector" aria-label="Scene inspector" aria-hidden="true">
|
||||||
|
<div id="plot-inspector-content"></div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
@section Scripts {
|
||||||
|
<script src="~/js/plot-line-workspace.js" asp-append-version="true"></script>
|
||||||
|
}
|
||||||
102
PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml
Normal file
102
PlotLine/Views/PlotLineWorkspace/_Inspector.cshtml
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
@model PlotLineWorkspaceInspectorViewModel
|
||||||
|
<div class="plot-inspector-header">
|
||||||
|
<div><p class="eyebrow">Scene contribution</p><h2>@Model.Scene.SceneTitle</h2></div>
|
||||||
|
<button type="button" class="btn-close" data-inspector-close aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<p class="muted">Scene @Model.Scene.SceneNumber.ToString("0.##") · @Model.Scene.TimeModeName</p>
|
||||||
|
<div class="button-row">
|
||||||
|
<a class="btn btn-primary btn-sm" asp-controller="Scenes" asp-action="Edit" asp-route-id="@Model.Scene.SceneID">Open scene</a>
|
||||||
|
<a class="btn btn-outline-secondary btn-sm" asp-controller="Writing" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID" asp-route-sceneId="@Model.Scene.SceneID">Open in Writer</a>
|
||||||
|
</div>
|
||||||
|
<nav class="plot-inspector-tabs" aria-label="Inspector sections">
|
||||||
|
<button type="button" data-inspector-tab="contribution" class="active">Contribution</button>
|
||||||
|
<button type="button" data-inspector-tab="scene">Scene</button>
|
||||||
|
<button type="button" data-inspector-tab="lines">Other lines</button>
|
||||||
|
<button type="button" data-inspector-tab="evidence">Evidence</button>
|
||||||
|
</nav>
|
||||||
|
<section data-inspector-panel="contribution">
|
||||||
|
@if (Model.Memberships.Count == 0) { <p class="muted">This scene has no canonical plot-line contribution.</p> }
|
||||||
|
@foreach (var membership in Model.Memberships)
|
||||||
|
{
|
||||||
|
<div class="plot-inspector-membership" style="--line-colour:@membership.Colour">
|
||||||
|
<h3>@membership.PlotLineName</h3>
|
||||||
|
@foreach (var contribution in membership.Contributions)
|
||||||
|
{
|
||||||
|
<article><strong>@contribution.CanonicalRole · @contribution.ThreadTitle</strong>
|
||||||
|
<p>@(string.IsNullOrWhiteSpace(contribution.CanonicalDescription) ? contribution.CanonicalTitle : contribution.CanonicalDescription)</p>
|
||||||
|
<small>@contribution.CanonicalStructuralType · @contribution.ThreadStatusName</small>
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
@foreach (var thread in Model.Threads.Where(x => x.PlotLineID == membership.PlotLineID))
|
||||||
|
{
|
||||||
|
<details class="plot-thread-boundaries">
|
||||||
|
<summary>@thread.ThreadTitle boundaries</summary>
|
||||||
|
<dl class="plot-facts">
|
||||||
|
<dt>Introduced</dt><dd>@(thread.IntroducedSceneLabel ?? "Not recorded")</dd>
|
||||||
|
<dt>Planned resolution</dt><dd>@(thread.PlannedResolutionSceneLabel ?? "Not recorded")</dd>
|
||||||
|
<dt>Actual resolution</dt><dd>@(thread.ActualResolutionSceneLabel ?? "Not recorded")</dd>
|
||||||
|
</dl>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section data-inspector-panel="scene" hidden>
|
||||||
|
<dl class="plot-facts">
|
||||||
|
<dt>Summary</dt><dd>@(Model.Scene.Summary ?? "Not recorded")</dd>
|
||||||
|
<dt>Time</dt><dd>@(Model.Scene.StartDateTime?.ToString("g") ?? Model.Scene.RelativeTimeText ?? Model.Scene.TimeModeName)</dd>
|
||||||
|
<dt>Purpose</dt><dd>@(Model.Scene.ScenePurposeNotes ?? "Not recorded")</dd>
|
||||||
|
<dt>Outcome</dt><dd>@(Model.Scene.SceneOutcomeNotes ?? "Not recorded")</dd>
|
||||||
|
</dl>
|
||||||
|
@if (Model.Scene.IsLinkedToManuscript)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" data-manuscript-load="@Model.Scene.SceneID">Load manuscript excerpt</button>
|
||||||
|
<div id="plot-manuscript-content"></div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section data-inspector-panel="lines" hidden>
|
||||||
|
@foreach (var membership in Model.Memberships)
|
||||||
|
{
|
||||||
|
<p><span class="plot-line-dot" style="background:@membership.Colour"></span> <strong>@membership.PlotLineName</strong> · @membership.Contributions.Count contribution@(membership.Contributions.Count == 1 ? "" : "s")</p>
|
||||||
|
}
|
||||||
|
@if (Model.Targets.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Explicit cross-line connections</h3>
|
||||||
|
@foreach (var target in Model.Targets)
|
||||||
|
{
|
||||||
|
<p><strong>@target.SourcePlotLineName</strong> → <strong>@target.TargetPlotLineName</strong><br /><small>@target.StructuralType</small></p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (Model.Dependencies.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Scene dependencies</h3>
|
||||||
|
@foreach (var dependency in Model.Dependencies)
|
||||||
|
{
|
||||||
|
<p><strong>@dependency.DependencyType</strong> · Scene @dependency.SourceSceneID → @dependency.TargetSceneID<br /><small>@dependency.Description</small></p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section data-inspector-panel="evidence" hidden>
|
||||||
|
@foreach (var contribution in Model.Memberships.SelectMany(x => x.Contributions))
|
||||||
|
{
|
||||||
|
<article class="plot-evidence">
|
||||||
|
<strong>@contribution.ThreadTitle</strong>
|
||||||
|
<p><b>Canonical:</b> @contribution.CanonicalTitle</p>
|
||||||
|
@if (contribution.CandidateMatchState == "SourceReferenceID + SceneID")
|
||||||
|
{
|
||||||
|
<p><b>Imported support:</b> @contribution.CandidateTitle</p>
|
||||||
|
@if (!string.IsNullOrWhiteSpace(contribution.CandidateDescription)) { <p>@contribution.CandidateDescription</p> }
|
||||||
|
@if (!string.IsNullOrWhiteSpace(contribution.CandidateEvidence)) { <blockquote>@contribution.CandidateEvidence</blockquote> }
|
||||||
|
}
|
||||||
|
else if (contribution.Source == "WholeBookPlotSynthesis")
|
||||||
|
{
|
||||||
|
<p class="muted">Imported support match: @contribution.CandidateMatchState</p>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
@if (Model.Suggestions.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Pending suggestions</h3>
|
||||||
|
@foreach (var suggestion in Model.Suggestions) { <p><strong>@suggestion.CandidateTitle</strong><br />@suggestion.Evidence</p> }
|
||||||
|
}
|
||||||
|
</section>
|
||||||
2
PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml
Normal file
2
PlotLine/Views/PlotLineWorkspace/_Manuscript.cshtml
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
@model PlotLineWorkspaceManuscriptViewModel
|
||||||
|
<article class="plot-manuscript"><p class="muted">@Model.SourceWordCount.ToString("N0") words · manuscript source</p><div>@Model.SourceText</div></article>
|
||||||
@ -25,7 +25,14 @@
|
|||||||
<div class="trial-dashboard-banner__body">
|
<div class="trial-dashboard-banner__body">
|
||||||
<p class="eyebrow">Free trial status</p>
|
<p class="eyebrow">Free trial status</p>
|
||||||
<h2>@trial.StatusLabel on @trial.PlanName</h2>
|
<h2>@trial.StatusLabel on @trial.PlanName</h2>
|
||||||
<p>Your 30-day trial expires on @FormatDate(trial.ExpiryDateUtc). Upgrade whenever you are ready.</p>
|
@if (trial.IsExpired)
|
||||||
|
{
|
||||||
|
<p>Your trial ended on @FormatDate(trial.ExpiryDateUtc). Your books remain available to read and export; upgrade to continue editing or creating books.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Your 30-day trial expires on @FormatDate(trial.ExpiryDateUtc). Upgrade whenever you are ready.</p>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="trial-dashboard-banner__actions">
|
<div class="trial-dashboard-banner__actions">
|
||||||
<a class="btn btn-primary btn-sm" asp-controller="ManageAccount" asp-action="Subscription">Upgrade</a>
|
<a class="btn btn-primary btn-sm" asp-controller="ManageAccount" asp-action="Subscription">Upgrade</a>
|
||||||
|
|||||||
@ -0,0 +1,7 @@
|
|||||||
|
@model EffectiveEntitlement
|
||||||
|
<div class="alert alert-warning entitlement-banner" role="status">
|
||||||
|
<strong>@(Model.IsTrialExpired ? "Your trial has ended." : "Your subscription is inactive.")</strong>
|
||||||
|
Your existing books remain available to read and export.
|
||||||
|
<a asp-controller="ManageAccount" asp-action="Subscription" class="alert-link">View subscription options</a>
|
||||||
|
to continue editing, importing, using Story Intelligence, or creating new books.
|
||||||
|
</div>
|
||||||
@ -139,6 +139,10 @@
|
|||||||
<input class="form-control form-control-sm" id="Characters_@(index)__EmotionalState" name="Characters[@index].EmotionalState" value="@character.EmotionalState" />
|
<input class="form-control form-control-sm" id="Characters_@(index)__EmotionalState" name="Characters[@index].EmotionalState" value="@character.EmotionalState" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="Characters_@(index)__KnowledgeNotes">Knowledge notes</label>
|
||||||
|
<textarea class="form-control form-control-sm" id="Characters_@(index)__KnowledgeNotes" name="Characters[@index].KnowledgeNotes" rows="2">@character.KnowledgeNotes</textarea>
|
||||||
|
</div>
|
||||||
</article>
|
</article>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@ -183,6 +187,10 @@
|
|||||||
<label for="NewCharacter_AppearanceNotes">Appearance notes</label>
|
<label for="NewCharacter_AppearanceNotes">Appearance notes</label>
|
||||||
<textarea class="form-control form-control-sm" id="NewCharacter_AppearanceNotes" name="NewCharacter.AppearanceNotes" rows="2"></textarea>
|
<textarea class="form-control form-control-sm" id="NewCharacter_AppearanceNotes" name="NewCharacter.AppearanceNotes" rows="2"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="NewCharacter_KnowledgeNotes">Knowledge notes</label>
|
||||||
|
<textarea class="form-control form-control-sm" id="NewCharacter_KnowledgeNotes" name="NewCharacter.KnowledgeNotes" rows="2"></textarea>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@ -132,6 +132,7 @@
|
|||||||
</environment>
|
</environment>
|
||||||
<link rel="stylesheet" href="~/css/onboarding.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/onboarding.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/story-intelligence-global-progress.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/story-intelligence-global-progress.css" asp-append-version="true" />
|
||||||
|
<link rel="stylesheet" href="~/css/plot-line-workspace.css" asp-append-version="true" />
|
||||||
|
|
||||||
<link rel="icon" href="~/favicon.ico" sizes="any" />
|
<link rel="icon" href="~/favicon.ico" sizes="any" />
|
||||||
<link rel="icon" type="image/svg+xml" href="~/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="~/favicon.svg" />
|
||||||
@ -159,6 +160,7 @@
|
|||||||
@if (isApplication)
|
@if (isApplication)
|
||||||
{
|
{
|
||||||
<partial name="_ApplicationShell" model="appNavigation" />
|
<partial name="_ApplicationShell" model="appNavigation" />
|
||||||
|
@await Component.InvokeAsync("EntitlementBanner")
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
@ -55,7 +55,6 @@
|
|||||||
int ChapterSceneColumns(ChapterTimelineViewModel chapter) => Math.Max(chapter.Scenes.Count, 1);
|
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);
|
int BookSceneColumns(BookTimelineViewModel book) => Math.Max(book.Chapters.Any() ? book.Chapters.Sum(ChapterSceneColumns) : 1, 1);
|
||||||
var hasSelectedScene = Model.SelectedScene is not null;
|
var hasSelectedScene = Model.SelectedScene is not null;
|
||||||
int CharacterAppearanceCount(CharacterLaneViewModel lane) => lane.SceneSlots.Sum(slot => slot.Appearances.Count);
|
|
||||||
int HiddenCount<T>(IReadOnlyList<T> items, int visibleCount) => Math.Max(0, items.Count - visibleCount);
|
int HiddenCount<T>(IReadOnlyList<T> items, int visibleCount) => Math.Max(0, items.Count - visibleCount);
|
||||||
string PlotMarkerKind(string? plotEventTypeName) => (plotEventTypeName ?? "Progress").Trim().ToLowerInvariant() switch
|
string PlotMarkerKind(string? plotEventTypeName) => (plotEventTypeName ?? "Progress").Trim().ToLowerInvariant() switch
|
||||||
{
|
{
|
||||||
@ -163,10 +162,6 @@
|
|||||||
.ThenBy(warning => warning.WarningTypeName)
|
.ThenBy(warning => warning.WarningTypeName)
|
||||||
.ToList()
|
.ToList()
|
||||||
: [];
|
: [];
|
||||||
bool HasStoryState(SceneCharacter appearance)
|
|
||||||
=> !string.IsNullOrWhiteSpace(appearance.EmotionalState)
|
|
||||||
|| !string.IsNullOrWhiteSpace(appearance.PhysicalCondition)
|
|
||||||
|| !string.IsNullOrWhiteSpace(appearance.KnowledgeNotes);
|
|
||||||
string AssetMarkerLabel(AssetEvent assetEvent)
|
string AssetMarkerLabel(AssetEvent assetEvent)
|
||||||
{
|
{
|
||||||
var typeName = assetEvent.AssetEventTypeName?.Trim() ?? string.Empty;
|
var typeName = assetEvent.AssetEventTypeName?.Trim() ?? string.Empty;
|
||||||
@ -282,203 +277,6 @@
|
|||||||
}
|
}
|
||||||
return string.Join(Environment.NewLine, lines);
|
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<ContinuityWarning> characterWarnings)
|
|
||||||
{
|
|
||||||
var classes = new List<string>();
|
|
||||||
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<ContinuityWarning> characterWarnings)
|
|
||||||
{
|
|
||||||
var lines = new List<string>
|
|
||||||
{
|
|
||||||
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
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||||
@ -653,7 +451,6 @@
|
|||||||
@if (Model.Settings.ShowSceneCards) { <label><input type="checkbox" data-timeline-toggle="scene-cards" checked /> Scene cards</label> }
|
@if (Model.Settings.ShowSceneCards) { <label><input type="checkbox" data-timeline-toggle="scene-cards" checked /> Scene cards</label> }
|
||||||
@if (Model.Settings.ShowPlotLines) { <label><input type="checkbox" data-timeline-toggle="plot-lines" checked /> Plot lines</label> }
|
@if (Model.Settings.ShowPlotLines) { <label><input type="checkbox" data-timeline-toggle="plot-lines" checked /> Plot lines</label> }
|
||||||
@if (Model.Settings.ShowStoryAssets) { <label><input type="checkbox" data-timeline-toggle="assets" checked /> Story assets</label> }
|
@if (Model.Settings.ShowStoryAssets) { <label><input type="checkbox" data-timeline-toggle="assets" checked /> Story assets</label> }
|
||||||
@if (Model.Settings.ShowCharacterAppearances) { <label><input type="checkbox" data-timeline-toggle="characters" checked /> Characters</label> }
|
|
||||||
@if (Model.Settings.ShowWarnings) { <label><input type="checkbox" data-timeline-toggle="warnings" checked /> Warnings</label> }
|
@if (Model.Settings.ShowWarnings) { <label><input type="checkbox" data-timeline-toggle="warnings" checked /> Warnings</label> }
|
||||||
@if (Model.Settings.ShowMetricShape) { <label><input type="checkbox" data-timeline-toggle="metrics" checked /> Metrics</label> }
|
@if (Model.Settings.ShowMetricShape) { <label><input type="checkbox" data-timeline-toggle="metrics" checked /> Metrics</label> }
|
||||||
</div>
|
</div>
|
||||||
@ -702,14 +499,6 @@
|
|||||||
<option value="@firstScene.SceneID">Asset: @lane.Asset.AssetName</option>
|
<option value="@firstScene.SceneID">Asset: @lane.Asset.AssetName</option>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@foreach (var lane in Model.CharacterLanes)
|
|
||||||
{
|
|
||||||
var firstScene = lane.SceneSlots.FirstOrDefault(x => x.Appearances.Any())?.Scene;
|
|
||||||
if (firstScene is not null)
|
|
||||||
{
|
|
||||||
<option value="@firstScene.SceneID">Character: @lane.Character.CharacterName</option>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@foreach (var locationScene in Model.OrderedScenes.Where(x => !string.IsNullOrWhiteSpace(x.PrimaryLocationName)).GroupBy(x => x.PrimaryLocationName).Select(x => x.First()))
|
@foreach (var locationScene in Model.OrderedScenes.Where(x => !string.IsNullOrWhiteSpace(x.PrimaryLocationName)).GroupBy(x => x.PrimaryLocationName).Select(x => x.First()))
|
||||||
{
|
{
|
||||||
<option value="@locationScene.SceneID">Location: @locationScene.PrimaryLocationName</option>
|
<option value="@locationScene.SceneID">Location: @locationScene.PrimaryLocationName</option>
|
||||||
@ -1053,8 +842,7 @@ else
|
|||||||
.SelectMany(x => x.SceneSlots.Where(slot => slot.Scene.SceneID == scene.SceneID).SelectMany(slot => slot.Events.Select(evt => $"{x.PlotLine.PlotLineName} {evt.ThreadTitle} {evt.EventTitle}"))));
|
.SelectMany(x => x.SceneSlots.Where(slot => slot.Scene.SceneID == scene.SceneID).SelectMany(slot => slot.Events.Select(evt => $"{x.PlotLine.PlotLineName} {evt.ThreadTitle} {evt.EventTitle}"))));
|
||||||
var assetSearch = string.Join(' ', Model.AssetLanes
|
var assetSearch = string.Join(' ', Model.AssetLanes
|
||||||
.SelectMany(x => x.SceneSlots.Where(slot => slot.Scene.SceneID == scene.SceneID).SelectMany(slot => slot.Events.Select(evt => $"{x.Asset.AssetName} {evt.EventTitle}"))));
|
.SelectMany(x => x.SceneSlots.Where(slot => slot.Scene.SceneID == scene.SceneID).SelectMany(slot => slot.Events.Select(evt => $"{x.Asset.AssetName} {evt.EventTitle}"))));
|
||||||
var characterSearch = string.Join(' ', Model.CharacterLanes
|
var characterSearch = string.Join(' ', overview.Characters.Select(character => character.CharacterName));
|
||||||
.SelectMany(x => x.SceneSlots.Where(slot => slot.Scene.SceneID == scene.SceneID).SelectMany(slot => slot.Appearances.Select(appearance => $"{x.Character.CharacterName} {appearance.RoleInSceneTypeName} {appearance.PresenceTypeName}"))));
|
|
||||||
var warningSearch = scene.WarningCount > 0 ? "warning warnings continuity" : "";
|
var warningSearch = scene.WarningCount > 0 ? "warning warnings continuity" : "";
|
||||||
var searchText = $"{scene.SceneNumber} {scene.SceneTitle} {scene.Summary} {povLabel} {scene.PrimaryLocationName} {string.Join(' ', scene.PurposeLabels.Select(x => x.PurposeName))} {plotSearch} {assetSearch} {characterSearch} {warningSearch}";
|
var searchText = $"{scene.SceneNumber} {scene.SceneTitle} {scene.Summary} {povLabel} {scene.PrimaryLocationName} {string.Join(' ', scene.PurposeLabels.Select(x => x.PurposeName))} {plotSearch} {assetSearch} {characterSearch} {warningSearch}";
|
||||||
<a class="timeline-scene-card @selectedClass @matchClass @focusClass"
|
<a class="timeline-scene-card @selectedClass @matchClass @focusClass"
|
||||||
@ -1450,93 +1238,6 @@ else
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@if (Model.Settings.ShowCharacterAppearances)
|
|
||||||
{
|
|
||||||
if (Model.CharacterLanes.Any() && Model.OrderedScenes.Any())
|
|
||||||
{
|
|
||||||
<div class="character-lane-board" data-timeline-section="characters" style="--scene-count:@timelineColumns.Count">
|
|
||||||
<div class="lane-board-heading character-lane-board-heading">
|
|
||||||
<button type="button" data-collapse-toggle="characters">Character appearances</button>
|
|
||||||
<help-icon key="timeline.characterAppearances" mode="inline" />
|
|
||||||
<small>All project characters, grouped by role and activity</small>
|
|
||||||
</div>
|
|
||||||
<div data-collapse-body="characters">
|
|
||||||
@foreach (var group in Model.CharacterLanes
|
|
||||||
.Select((lane, index) => new { lane, index, group = CharacterGroupName(lane) })
|
|
||||||
.GroupBy(x => x.group)
|
|
||||||
.OrderBy(group => CharacterGroupOrder(group.Key)))
|
|
||||||
{
|
|
||||||
var groupId = $"character-group-{CharacterGroupOrder(group.Key)}";
|
|
||||||
var defaultCollapsed = CharacterGroupOrder(group.Key) > 0 ? "collapsed" : null;
|
|
||||||
<div class="lane-group">
|
|
||||||
<button type="button" class="lane-group-heading" data-collapse-toggle="@groupId" data-collapse-default="@defaultCollapsed">@group.Key <span>@group.Count()</span></button>
|
|
||||||
<div class="character-lane-group-body" data-collapse-body="@groupId">
|
|
||||||
@foreach (var laneItem in group)
|
|
||||||
{
|
|
||||||
var lane = laneItem.lane;
|
|
||||||
var characterFocusClass = Model.Filter.FocusType == "character" && Model.Filter.FocusID.HasValue && Model.Filter.FocusID != lane.Character.CharacterID ? "lane-dim" : "";
|
|
||||||
var orderedLaneAppearances = lane.SceneSlots
|
|
||||||
.SelectMany(slot => slot.Appearances)
|
|
||||||
.OrderBy(appearance => timelineColumns.FindIndex(column => column.Scene?.SceneID == appearance.SceneID))
|
|
||||||
.ThenBy(appearance => appearance.SceneCharacterID)
|
|
||||||
.ToList();
|
|
||||||
var firstAppearance = orderedLaneAppearances.FirstOrDefault();
|
|
||||||
var lastAppearance = orderedLaneAppearances.LastOrDefault();
|
|
||||||
<div class="character-lane-row @characterFocusClass">
|
|
||||||
<a class="character-lane-label" asp-controller="Characters" asp-action="Details" asp-route-id="@lane.Character.CharacterID">
|
|
||||||
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = lane.Character.CharacterName, ImagePath = lane.Character.AvatarImagePath ?? lane.Character.ImagePath, ThumbnailPath = lane.Character.AvatarThumbnailPath ?? lane.Character.ThumbnailPath, Size = "sm" })" />
|
|
||||||
<span>
|
|
||||||
<strong>@lane.Character.CharacterName</strong>
|
|
||||||
<small>@(lane.Character.ShortName ?? "Character")</small>
|
|
||||||
</span>
|
|
||||||
</a>
|
|
||||||
<div class="character-lane-slots">
|
|
||||||
@foreach (var column in timelineColumns)
|
|
||||||
{
|
|
||||||
if (column.Scene is not Scene realCharacterScene)
|
|
||||||
{
|
|
||||||
<div class="character-lane-slot timeline-placeholder-cell is-placeholder" title="@column.PlaceholderLabel"></div>
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var slot = lane.SceneSlots.FirstOrDefault(x => x.Scene.SceneID == realCharacterScene.SceneID);
|
|
||||||
<div class="character-lane-slot" title="Scene @realCharacterScene.SceneNumber: @realCharacterScene.SceneTitle">
|
|
||||||
@foreach (var appearance in slot?.Appearances ?? Enumerable.Empty<SceneCharacter>())
|
|
||||||
{
|
|
||||||
var characterWarnings = EntityWarnings(realCharacterScene, "Character", appearance.CharacterID);
|
|
||||||
var characterMarkerTooltip = CharacterMarkerTooltip(appearance, realCharacterScene, firstAppearance, lastAppearance, characterWarnings);
|
|
||||||
var characterMarkerClass = CharacterMarkerClass(appearance, firstAppearance, lastAppearance, characterWarnings);
|
|
||||||
<a class="character-marker @characterMarkerClass"
|
|
||||||
asp-controller="Timeline"
|
|
||||||
asp-action="Index"
|
|
||||||
asp-route-ProjectID="@Model.Project.ProjectID"
|
|
||||||
asp-route-BookID="@Model.SelectedBookID"
|
|
||||||
asp-route-SelectedSceneID="@realCharacterScene.SceneID"
|
|
||||||
asp-route-FocusType="character"
|
|
||||||
asp-route-FocusID="@appearance.CharacterID"
|
|
||||||
title="@characterMarkerTooltip"
|
|
||||||
aria-label="@characterMarkerTooltip">
|
|
||||||
@CharacterMarkerLabel(appearance, firstAppearance, lastAppearance)
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="future-lane-placeholder">
|
|
||||||
Add characters to scenes to see character appearance lanes here.
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@ -68,13 +68,6 @@
|
|||||||
<small>Shows clues, objects, evidence and state changes by scene.</small>
|
<small>Shows clues, objects, evidence and state changes by scene.</small>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
<label class="timeline-setting-card">
|
|
||||||
<input asp-for="ShowCharacterAppearances" />
|
|
||||||
<span>
|
|
||||||
<strong>Character Appearances</strong>
|
|
||||||
<small>Shows which characters appear in each scene.</small>
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
<label class="timeline-setting-card">
|
<label class="timeline-setting-card">
|
||||||
<input asp-for="ShowWarnings" />
|
<input asp-for="ShowWarnings" />
|
||||||
<span>
|
<span>
|
||||||
|
|||||||
63
PlotLine/wwwroot/css/plot-line-workspace.css
Normal file
63
PlotLine/wwwroot/css/plot-line-workspace.css
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
.plot-workspace-heading { align-items: end; }
|
||||||
|
.plot-workspace-controls { position: sticky; top: .75rem; z-index: 15; margin-bottom: 2rem; padding: 1rem; border: 1px solid var(--bs-border-color); border-radius: 1rem; background: color-mix(in srgb, var(--bs-body-bg) 94%, transparent); box-shadow: 0 .5rem 2rem rgba(22, 30, 40, .08); backdrop-filter: blur(12px); }
|
||||||
|
.plot-control-row { display: grid; grid-template-columns: minmax(10rem, .8fr) minmax(13rem, 1fr) minmax(14rem, 1.4fr) auto; gap: .75rem; align-items: end; }
|
||||||
|
.plot-control-row label { display: grid; gap: .3rem; font-size: .82rem; font-weight: 650; }
|
||||||
|
.plot-control-row .plot-toggle { display: flex; align-items: center; gap: .5rem; min-height: 2.4rem; }
|
||||||
|
.plot-line-picker { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .9rem; padding: 0; border: 0; }
|
||||||
|
.plot-line-picker legend { float: left; width: auto; margin: .5rem .25rem 0 0; font-size: .78rem; font-weight: 750; text-transform: uppercase; letter-spacing: .05em; }
|
||||||
|
.plot-line-choice { display: flex; align-items: center; gap: .4rem; padding: .42rem .65rem; border: 1px solid var(--bs-border-color); border-radius: 999px; cursor: pointer; }
|
||||||
|
.plot-line-choice:has(input:checked) { border-color: var(--line-colour); box-shadow: inset 0 0 0 1px var(--line-colour); }
|
||||||
|
.plot-line-choice input { position: absolute; opacity: 0; pointer-events: none; }
|
||||||
|
.plot-line-choice small { color: var(--bs-secondary-color); }
|
||||||
|
.plot-line-dot { display: inline-block; width: .7rem; height: .7rem; border-radius: 50%; background: var(--line-colour); }
|
||||||
|
.plot-unattributed-link { align-self: center; margin-left: auto; font-size: .9rem; }
|
||||||
|
.plot-thread-filter { margin-top: .75rem; font-size: .9rem; }
|
||||||
|
.plot-thread-filter > div { display: flex; flex-wrap: wrap; gap: .8rem; padding-top: .5rem; }
|
||||||
|
.plot-thread-filter label { display: flex; gap: .35rem; align-items: center; }
|
||||||
|
.plot-thread-filter small { color: var(--bs-secondary-color); }
|
||||||
|
.plot-story-map { position: relative; display: grid; gap: .85rem; max-width: 68rem; margin: 0 auto 3rem; padding-left: 3rem; }
|
||||||
|
.plot-story-map::before { content: ""; position: absolute; top: 0; bottom: 0; left: 1.45rem; width: 2px; background: linear-gradient(var(--bs-primary), color-mix(in srgb, var(--bs-primary) 20%, transparent)); }
|
||||||
|
.plot-scene-card { position: relative; overflow: hidden; border: 1px solid var(--bs-border-color); border-radius: 1rem; background: var(--bs-body-bg); box-shadow: 0 .35rem 1.2rem rgba(22, 30, 40, .06); }
|
||||||
|
.plot-scene-card::before { content: ""; position: absolute; left: -2.08rem; top: 2.1rem; width: .9rem; height: .9rem; border: 3px solid var(--bs-body-bg); border-radius: 50%; background: var(--bs-primary); box-shadow: 0 0 0 2px var(--bs-primary); }
|
||||||
|
.plot-scene-card.is-shared::before { width: 1.15rem; height: 1.15rem; left: -2.2rem; top: 2rem; background: var(--bs-warning); box-shadow: 0 0 0 2px var(--bs-warning); }
|
||||||
|
.plot-scene-open { display: grid; width: 100%; padding: 1rem 1.1rem .75rem; border: 0; background: transparent; color: inherit; text-align: left; }
|
||||||
|
.plot-scene-open:hover strong { color: var(--bs-primary); }
|
||||||
|
.plot-scene-kicker { color: var(--bs-secondary-color); font-size: .76rem; font-weight: 750; letter-spacing: .05em; text-transform: uppercase; }
|
||||||
|
.plot-scene-open > strong { font-family: var(--heading-font, inherit); font-size: 1.2rem; }
|
||||||
|
.plot-scene-summary { margin-top: .25rem; color: var(--bs-secondary-color); }
|
||||||
|
.plot-scene-memberships { display: grid; gap: .35rem; padding: 0 1.1rem .85rem; }
|
||||||
|
.plot-membership { display: grid; grid-template-columns: .35rem 1fr; gap: .65rem; padding: .45rem .6rem; border-radius: .55rem; background: color-mix(in srgb, var(--line-colour) 8%, transparent); }
|
||||||
|
.plot-route { border-radius: 1rem; background: var(--line-colour); }
|
||||||
|
.plot-membership div { display: grid; }
|
||||||
|
.plot-contribution-role { color: var(--bs-secondary-color); font-size: .84rem; }
|
||||||
|
.plot-scene-card footer { display: flex; flex-wrap: wrap; gap: .7rem; padding: .65rem 1.1rem; border-top: 1px solid var(--bs-border-color); color: var(--bs-secondary-color); font-size: .78rem; }
|
||||||
|
.plot-gap { display: flex; align-items: center; gap: .75rem; min-height: 2rem; color: var(--bs-secondary-color); font-size: .82rem; }
|
||||||
|
.plot-gap span { padding: .25rem .65rem; border: 1px dashed var(--bs-border-color); border-radius: 999px; background: var(--bs-body-bg); }
|
||||||
|
.plot-attribution-audit { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
|
||||||
|
.plot-audit-column { display: grid; align-content: start; gap: .55rem; }
|
||||||
|
.plot-audit-column h2 span, .plot-suggestion-panel h2 span { color: var(--bs-secondary-color); font-size: .8em; }
|
||||||
|
.plot-audit-scene, .plot-suggestion-panel button { display: grid; gap: .15rem; padding: .8rem; border: 1px solid var(--bs-border-color); border-radius: .7rem; background: var(--bs-body-bg); color: inherit; text-align: left; }
|
||||||
|
.plot-audit-scene small, .plot-suggestion-panel button span { color: var(--bs-secondary-color); }
|
||||||
|
.plot-suggestion-panel { display: grid; gap: .5rem; margin: 2rem 0; padding: 1rem; border: 1px solid var(--bs-border-color); border-radius: 1rem; }
|
||||||
|
.plot-inspector-backdrop { position: fixed; inset: 0; z-index: 1035; background: rgba(10, 15, 25, .35); }
|
||||||
|
.plot-inspector { position: fixed; z-index: 1040; top: 0; right: 0; width: min(34rem, 94vw); height: 100dvh; overflow: auto; padding: 1.25rem; border-left: 1px solid var(--bs-border-color); background: var(--bs-body-bg); box-shadow: -1rem 0 3rem rgba(10, 15, 25, .18); transform: translateX(102%); transition: transform .2s ease; }
|
||||||
|
.plot-inspector[aria-hidden="false"] { transform: translateX(0); }
|
||||||
|
.plot-inspector-header { display: flex; justify-content: space-between; gap: 1rem; }
|
||||||
|
.plot-inspector-header h2 { margin: 0; }
|
||||||
|
.plot-inspector-tabs { display: flex; overflow-x: auto; gap: .25rem; margin: 1.25rem 0 1rem; border-bottom: 1px solid var(--bs-border-color); }
|
||||||
|
.plot-inspector-tabs button { padding: .55rem .7rem; border: 0; border-bottom: 2px solid transparent; background: transparent; color: var(--bs-secondary-color); }
|
||||||
|
.plot-inspector-tabs button.active { border-color: var(--bs-primary); color: var(--bs-body-color); }
|
||||||
|
.plot-inspector-membership { padding-left: .8rem; border-left: .3rem solid var(--line-colour); }
|
||||||
|
.plot-inspector-membership article, .plot-evidence { margin-bottom: .8rem; padding: .75rem; border-radius: .6rem; background: var(--bs-tertiary-bg); }
|
||||||
|
.plot-facts { display: grid; grid-template-columns: 6rem 1fr; gap: .5rem; }
|
||||||
|
.plot-facts dt { color: var(--bs-secondary-color); }
|
||||||
|
.plot-manuscript { margin-top: 1rem; padding: 1rem; border: 1px solid var(--bs-border-color); border-radius: .6rem; }
|
||||||
|
.plot-manuscript > div { max-height: 45vh; overflow: auto; white-space: pre-wrap; font-family: Georgia, serif; line-height: 1.65; }
|
||||||
|
.plot-inspector-loading { padding: 3rem; color: var(--bs-secondary-color); text-align: center; }
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.plot-control-row, .plot-attribution-audit { grid-template-columns: 1fr; }
|
||||||
|
.plot-workspace-controls { position: static; }
|
||||||
|
.plot-story-map { padding-left: 2.25rem; }
|
||||||
|
.plot-story-map::before { left: 1rem; }
|
||||||
|
.plot-scene-card::before, .plot-scene-card.is-shared::before { left: -1.7rem; }
|
||||||
|
}
|
||||||
@ -969,6 +969,136 @@ a:hover {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admin-dashboard {
|
||||||
|
display: grid;
|
||||||
|
gap: clamp(1.25rem, 2.5vw, 2rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard > :where(.page-heading, nav, .alert, section) {
|
||||||
|
margin-block: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__heading,
|
||||||
|
.admin-dashboard__feature-panel {
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__section-heading {
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__section-heading h2,
|
||||||
|
.admin-dashboard__status-section h3,
|
||||||
|
.admin-dashboard__tool-card h2 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__summary-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__metric,
|
||||||
|
.admin-dashboard__status-card {
|
||||||
|
display: block;
|
||||||
|
min-width: 0;
|
||||||
|
border: 1px solid var(--plotline-border-soft);
|
||||||
|
border-radius: var(--plotline-radius-sm);
|
||||||
|
padding: 1rem;
|
||||||
|
background: color-mix(in srgb, var(--plotline-surface) 82%, var(--plotline-accent-soft));
|
||||||
|
color: var(--plotline-text);
|
||||||
|
text-decoration: none;
|
||||||
|
transition: border-color 0.18s ease, background-color 0.18s ease, transform 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__metric:hover,
|
||||||
|
.admin-dashboard__metric:focus,
|
||||||
|
.admin-dashboard__status-card:hover,
|
||||||
|
.admin-dashboard__status-card:focus {
|
||||||
|
border-color: rgba(122, 77, 44, 0.34);
|
||||||
|
background: color-mix(in srgb, var(--plotline-surface) 64%, var(--plotline-accent-soft));
|
||||||
|
color: var(--plotline-text);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__metric h2 {
|
||||||
|
font-size: clamp(1.8rem, 3vw, 2.5rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__status-section {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.85rem;
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
padding-top: 1.25rem;
|
||||||
|
border-top: 1px solid var(--plotline-border-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__status-section > h3 {
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__status-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr));
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__status-card {
|
||||||
|
padding: 0.85rem 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__status-card h3 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tools {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(12, minmax(0, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card--feature-requests {
|
||||||
|
grid-column: span 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card--ai {
|
||||||
|
grid-column: span 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card--names,
|
||||||
|
.admin-dashboard__tool-card--subscriptions {
|
||||||
|
grid-column: span 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card .project-card__body {
|
||||||
|
align-content: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card .project-card__actions {
|
||||||
|
align-content: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.admin-dashboard__tools {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-dashboard__tool-card--feature-requests,
|
||||||
|
.admin-dashboard__tool-card--ai,
|
||||||
|
.admin-dashboard__tool-card--names,
|
||||||
|
.admin-dashboard__tool-card--subscriptions {
|
||||||
|
grid-column: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 680px) {
|
||||||
|
.admin-dashboard__summary-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.project-cover-stack {
|
.project-cover-stack {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: min(11.5rem, 70%);
|
width: min(11.5rem, 70%);
|
||||||
|
|||||||
2
PlotLine/wwwroot/css/plotline-theme.min.css
vendored
2
PlotLine/wwwroot/css/plotline-theme.min.css
vendored
File diff suppressed because one or more lines are too long
62
PlotLine/wwwroot/js/plot-line-workspace.js
Normal file
62
PlotLine/wwwroot/js/plot-line-workspace.js
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
(() => {
|
||||||
|
const form = document.getElementById("plot-workspace-form");
|
||||||
|
const inspector = document.getElementById("plot-inspector");
|
||||||
|
const inspectorContent = document.getElementById("plot-inspector-content");
|
||||||
|
const backdrop = document.getElementById("plot-inspector-backdrop");
|
||||||
|
if (!form || !inspector || !inspectorContent || !backdrop) return;
|
||||||
|
|
||||||
|
const projectId = form.querySelector('[name="projectId"]')?.value;
|
||||||
|
const bookId = () => form.querySelector('[name="bookId"]')?.value || "";
|
||||||
|
const scenarioId = () => form.querySelector('[name="scenarioId"]')?.value || "";
|
||||||
|
|
||||||
|
form.querySelectorAll("[data-plot-submit]").forEach(control => control.addEventListener("change", () => form.submit()));
|
||||||
|
form.querySelectorAll("[data-line-choice]").forEach(control => control.addEventListener("change", () => {
|
||||||
|
if (!form.querySelector("[data-line-choice]:checked")) control.checked = true;
|
||||||
|
form.querySelectorAll('[name="threadId"]').forEach(thread => thread.checked = false);
|
||||||
|
form.submit();
|
||||||
|
}));
|
||||||
|
|
||||||
|
document.getElementById("plot-scene-search")?.addEventListener("input", event => {
|
||||||
|
const query = event.target.value.trim().toLocaleLowerCase();
|
||||||
|
document.querySelectorAll("[data-plot-scene]").forEach(card => {
|
||||||
|
card.hidden = query.length > 0 && !card.dataset.searchText.toLocaleLowerCase().includes(query);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const closeInspector = () => {
|
||||||
|
inspector.setAttribute("aria-hidden", "true");
|
||||||
|
backdrop.hidden = true;
|
||||||
|
document.body.classList.remove("plot-inspector-open");
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindInspector = () => {
|
||||||
|
inspectorContent.querySelector("[data-inspector-close]")?.addEventListener("click", closeInspector);
|
||||||
|
inspectorContent.querySelectorAll("[data-inspector-tab]").forEach(tab => tab.addEventListener("click", () => {
|
||||||
|
inspectorContent.querySelectorAll("[data-inspector-tab]").forEach(item => item.classList.toggle("active", item === tab));
|
||||||
|
inspectorContent.querySelectorAll("[data-inspector-panel]").forEach(panel => panel.hidden = panel.dataset.inspectorPanel !== tab.dataset.inspectorTab);
|
||||||
|
}));
|
||||||
|
inspectorContent.querySelector("[data-manuscript-load]")?.addEventListener("click", async event => {
|
||||||
|
const target = document.getElementById("plot-manuscript-content");
|
||||||
|
event.currentTarget.disabled = true;
|
||||||
|
target.innerHTML = '<p class="muted">Loading manuscript…</p>';
|
||||||
|
const query = new URLSearchParams({ projectId, bookId: bookId(), sceneId: event.currentTarget.dataset.manuscriptLoad });
|
||||||
|
const response = await fetch(`/PlotLineWorkspace/Manuscript?${query}`);
|
||||||
|
target.innerHTML = response.ok ? await response.text() : '<p class="text-danger">The manuscript excerpt could not be loaded.</p>';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("click", async event => {
|
||||||
|
const trigger = event.target.closest("[data-scene-inspector]");
|
||||||
|
if (!trigger) return;
|
||||||
|
const query = new URLSearchParams({ projectId, bookId: bookId(), sceneId: trigger.dataset.sceneInspector, scenarioId: scenarioId() });
|
||||||
|
inspectorContent.innerHTML = '<div class="plot-inspector-loading">Loading scene…</div>';
|
||||||
|
inspector.setAttribute("aria-hidden", "false");
|
||||||
|
backdrop.hidden = false;
|
||||||
|
document.body.classList.add("plot-inspector-open");
|
||||||
|
const response = await fetch(`/PlotLineWorkspace/Inspector?${query}`);
|
||||||
|
inspectorContent.innerHTML = response.ok ? await response.text() : '<p class="text-danger">The scene inspector could not be loaded.</p>';
|
||||||
|
if (response.ok) bindInspector();
|
||||||
|
});
|
||||||
|
backdrop.addEventListener("click", closeInspector);
|
||||||
|
document.addEventListener("keydown", event => { if (event.key === "Escape") closeInspector(); });
|
||||||
|
})();
|
||||||
@ -1207,7 +1207,6 @@
|
|||||||
".timeline-shell",
|
".timeline-shell",
|
||||||
".plot-lane-board",
|
".plot-lane-board",
|
||||||
".asset-lane-board",
|
".asset-lane-board",
|
||||||
".character-lane-board",
|
|
||||||
".metric-graph-stack",
|
".metric-graph-stack",
|
||||||
"[data-timeline-minimap]"
|
"[data-timeline-minimap]"
|
||||||
].join(",");
|
].join(",");
|
||||||
|
|||||||
522
docs/discovery-plot-line-data-audit.md
Normal file
522
docs/discovery-plot-line-data-audit.md
Normal file
@ -0,0 +1,522 @@
|
|||||||
|
# Discovery Plot-Line Data Audit
|
||||||
|
|
||||||
|
Date: 29 October 2026
|
||||||
|
Scope: read-only audit of the development database `PlotDirector_Development`; no review decisions, regeneration, data changes, schema changes, or production access
|
||||||
|
|
||||||
|
## A. Executive summary
|
||||||
|
|
||||||
|
The completed development import corresponding to *The Alpha Flame: Discovery* is project 4085, **The Alpha Flame**, book 6097, **The Alpha Flame** (Book 1). The database title omits the subtitle “Discovery”, but this is the only populated active book in development, it contains all 48 imported chapters and 299 active scenes, all 299 scenes are linked to one active manuscript document and have non-empty manuscript source text, and it has a current completed whole-book synthesis. There is no competing candidate book.
|
||||||
|
|
||||||
|
The current canonical Plot Line model is exceptionally sparse compared with the information retained by Story Intelligence:
|
||||||
|
|
||||||
|
| Population | Scenes | % of 299 |
|
||||||
|
|---|---:|---:|
|
||||||
|
| Canonically attributed | 30 | 10.03% |
|
||||||
|
| Proposed-only | 265 | 88.63% |
|
||||||
|
| No known attribution | 4 | 1.34% |
|
||||||
|
| **Total** | **299** | **100.00%** |
|
||||||
|
|
||||||
|
“Proposed-only” is large because 33 pending legacy `SceneSignals` candidates have evidence spread over most of the book. This is not equivalent to 265 high-quality Plot Line recommendations: several candidates are extremely broad and contain visibly unrelated evidence. It is nevertheless persisted candidate evidence and must be kept separate from scenes for which the system knows nothing.
|
||||||
|
|
||||||
|
Five accepted, active canonical Plot Lines contain 11 threads and 31 events. Every canonical line and thread was materialised from the completed whole-book synthesis. All 31 events have source/provenance and confidence. However:
|
||||||
|
|
||||||
|
- every structural Plot Event type is `Progress` (31/31, 100%);
|
||||||
|
- every canonical event title is merely its role name (for example, `Developed` or `Payoff`);
|
||||||
|
- the canonical description is an evidence/source reference rather than the richer candidate description;
|
||||||
|
- all 31 accepted candidate events have `AcceptedThreadEventID = NULL`, although all can be matched unambiguously by `SourceReferenceID` plus `SceneID`;
|
||||||
|
- 29/31 canonical confidence values differ from the corresponding per-event candidate confidence, because materialisation appears to have used thread-level confidence;
|
||||||
|
- only one canonical scene is shared by two Plot Lines, and none is shared by the selected Sisters/Maggie/Predator lines;
|
||||||
|
- no scene dependencies or branch/split/merge targets exist for the book.
|
||||||
|
|
||||||
|
Selecting **Sisters of the Alpha Flame** would show nine canonical contributions across seven chapters. The sequence is understandable as a compact spine—recognition, rescue/care, growing intimacy, belonging, proof, reunion, and lived sisterhood—but it omits nearly all intervening texture. Every Sisters contribution has complete manuscript text and richer candidate evidence available.
|
||||||
|
|
||||||
|
Selecting Sisters, Maggie’s Arc, and Predator together would show 22 scenes. The weave supports ordering and dormant-gap display, but not convergence: none of those 22 scenes is canonically shared between the selected lines, and no structured dependency connects them. The visual would therefore be three interleaved sparse sequences rather than a richly connected braid.
|
||||||
|
|
||||||
|
The data already supports a useful read-only Plot Lines workspace without schema changes: compact canonical spines, selected-line unions, manuscript order, chronology, role, confidence, metrics, manuscript text, richer synthesis evidence, pending-evidence overlays, and gap warnings. It cannot honestly provide canonical per-contribution significance, reliable structural Plot Event semantics, or cross-line causality.
|
||||||
|
|
||||||
|
## B. Book/import verification
|
||||||
|
|
||||||
|
| Field | Authoritative value |
|
||||||
|
|---|---|
|
||||||
|
| Environment | `PlotDirector_Development` |
|
||||||
|
| Project | 4085 — The Alpha Flame |
|
||||||
|
| Book | 6097 — The Alpha Flame, Book 1 |
|
||||||
|
| Active chapters | 48 |
|
||||||
|
| Active scenes | 299 |
|
||||||
|
| Manuscript document | 1 active document; all 299 scenes linked |
|
||||||
|
| Scene manuscript sources | 299/299 non-empty; 154,428 words total |
|
||||||
|
| Structural chapter sources | 48/48 chapters |
|
||||||
|
| Chapter Story Intelligence runs | 48: 19 `Completed`, 29 `CompletedWithWarnings` |
|
||||||
|
| Scenes reported completed by runs | 299 (two module-level failures are also recorded across warning runs) |
|
||||||
|
| Whole-book synthesis | Run 6, `Completed`, current, model `gpt-5`, completed 9 June 2026 |
|
||||||
|
| Whole-book review data | 5 accepted Plot Line candidates, 11 accepted Thread candidates, 31 candidate events; 33 additional pending `SceneSignals` candidates |
|
||||||
|
|
||||||
|
The import is therefore the completed full-book development import. `Scenes.ImportRunID` is null for these Word Companion imports, so completion is established by the complete chapter/source/document coverage and Story Intelligence records rather than that field.
|
||||||
|
|
||||||
|
## C. Attribution coverage
|
||||||
|
|
||||||
|
The audit uses these mutually exclusive definitions:
|
||||||
|
|
||||||
|
1. canonical: at least one active `ThreadEvent → PlotThread → PlotLine` path;
|
||||||
|
2. proposed-only: no canonical path, but at least one persisted candidate-event or candidate-evidence row;
|
||||||
|
3. no known attribution: neither of the above.
|
||||||
|
|
||||||
|
The resulting counts are 30 + 265 + 4 = 299. All proposed-only rows are associated with **pending** `SceneSignals` candidates; there are no rejected candidate populations in this book. Of the proposed-only scenes, 162 appear under at least one pending Plot Line candidate and 252 under at least one pending Thread candidate; these overlap heavily.
|
||||||
|
|
||||||
|
This is coverage of what PlotDirector currently knows, not an editorial judgement. In particular, no canonical Plot Line does not mean no narrative purpose.
|
||||||
|
|
||||||
|
## D. Canonical Plot Line inventory
|
||||||
|
|
||||||
|
All five lines have no parent or emerges-from line, colour `#2f6f63`, sort order 0, type `Main Plot`, importance `Primary`, and book scope 6097. All have accepted `WholeBookPlotSynthesis` candidates, so their Story Intelligence provenance is reliable rather than inferred.
|
||||||
|
|
||||||
|
| ID | Plot Line | Description (abridged) | Threads | Scenes | Events | First → last contribution | Chapters | Book coverage |
|
||||||
|
|---:|---|---|---:|---:|---:|---|---:|---:|
|
||||||
|
| 13 | Beth’s Survival, Agency, and Healing | Beth’s movement from orphaning and exploitation toward resistance, care, and choosing life | 2 | 6 | 6 | 1.1 Finding Her Mother → 48.3 Beth's Memory and Resolve | 5 | 2.01% |
|
||||||
|
| 14 | Maggie’s Arc: Competence, Love, and Courage | Competence, style, courage, and a developing relationship with Rob | 2 | 5 | 5 | 2.7 Incident and Assessment → 38.5 Confession and Response | 5 | 1.67% |
|
||||||
|
| 15 | Rot in the System | Institutional complicity and Graham’s constrained effort to act | 1 | 3 | 3 | 28.3 Office Friction and Resolve → 46.2 Meeting at the Pub | 3 | 1.00% |
|
||||||
|
| 16 | Sisters of the Alpha Flame | Hidden kinship, recognition, proof, belonging, and chosen family | 3 | 9 | 9 | 3.7 Garage and Reflection → 48.2 Under the Flyover | 7 | 3.01% |
|
||||||
|
| 17 | The Predator and the Taped Confession | Rick’s abuse and murders culminating in the planned sting and confrontation | 3 | 8 | 8 | 16.4 Feeding and Bathing → 47.7 Maggie Joins the Fight | 5 | 2.68% |
|
||||||
|
|
||||||
|
No line is broad in canonical coverage; the broadest touches only 9/299 scenes. The canonical model is more at risk of under-association than indiscriminate association.
|
||||||
|
|
||||||
|
## E. Plot Thread inventory
|
||||||
|
|
||||||
|
All 11 threads are active, type `Question`, importance 5. No thread has zero or one event, but the uniform type and importance indicate flattened materialisation.
|
||||||
|
|
||||||
|
Every `PlannedResolutionSceneID` is null; the boundary column therefore lists only configured introduced and actual-resolution scenes.
|
||||||
|
|
||||||
|
| Line | ID — thread | Status | Boundary scenes | Events/scenes | Actual event span | Longest internal gap |
|
||||||
|
|---|---|---|---|---:|---|---:|
|
||||||
|
| Beth | 34 — Orphaned and Unbelieved | Introduced | Introduced 1.1; no planned/actual resolution | 3/3 | index 1–72 | 68 scenes |
|
||||||
|
| Beth | 28 — Edges of Tenderness | Resolved | Introduced 6.10; actual resolution 48.3 | 3/3 | index 41–298 | 179 scenes |
|
||||||
|
| Maggie | 26 — Becoming: Style and Steel | Planned | Introduced 2.7; actual resolution 26.2 | 2/2 | index 12–144 | 131 scenes |
|
||||||
|
| Maggie | 31 — Love and Legitimacy | Resolved | Introduced 34.3; actual resolution 38.5 | 3/3 | index 198–227 | 22 scenes |
|
||||||
|
| Rot | 27 — Bent Lines, Straight Cop | Planned | Introduced 28.3; no resolution boundary | 3/3 | index 160–285 | 72 scenes |
|
||||||
|
| Sisters | 29 — First Sparks: Recognition Before Proof | Planned | Introduced 3.7; actual resolution 16.3 | 3/3 | index 20–113 | 78 scenes |
|
||||||
|
| Sisters | 35 — Proof and Belonging | Planned | Introduced 42.8; actual resolution 42.9 | 3/3 | index 256–262 | 4 scenes |
|
||||||
|
| Sisters | 33 — New Sisterhood in Practice | Resolved | Introduced 39.5; actual resolution 48.2 | 3/3 | index 233–297 | 35 scenes |
|
||||||
|
| Predator | 30 — From Grooming to Resistance | Planned | Introduced 16.5; no resolution boundary | 2/2 | index 100–101 | 0 scenes |
|
||||||
|
| Predator | 32 — Murder Web: Mum, Adam, Cindy | Planned | Introduced 20.3; no resolution boundary | 3/3 | index 114–293 | 167 scenes |
|
||||||
|
| Predator | 36 — The Sting at Rubery Hill | Planned | Introduced 46.4; actual resolution 47.7 | 3/3 | index 287–294 | 3 scenes |
|
||||||
|
|
||||||
|
Thread summaries and named event spans:
|
||||||
|
|
||||||
|
| ID | Summary | First → last event scene |
|
||||||
|
|---:|---|---|
|
||||||
|
| 34 | Beth’s mother’s death, institutional indifference, homelessness, search for Grace, and resulting mistrust | 1.1 Finding Her Mother → 11.4 Aftermath and Return |
|
||||||
|
| 28 | Maggie’s care, Ricardo’s night, sea day, bench farewell, and Ben’s steadying presence | 6.10 Ride Home → 48.3 Beth's Memory and Resolve |
|
||||||
|
| 26 | Driving-test competence, fashion craft, karate backbone, and confrontation with Sophie | 2.7 Incident and Assessment → 26.2 Confrontation with Sophie |
|
||||||
|
| 31 | Rob’s respectful attraction, Elle feature, beach intimacy, and choosing Rob while preserving friendship with Zoe | 34.3 Drinks and the Surprise → 38.5 Confession and Response |
|
||||||
|
| 27 | Baker obstructs while Graham builds a shadow case and risks his career | 28.3 Office Friction and Resolve → 46.2 Meeting at the Pub |
|
||||||
|
| 29 | Maggie’s unexplained pull toward Beth and Beth’s trust before either knows they are related | 3.7 Garage and Reflection → 20.2 Conversation with Maggie |
|
||||||
|
| 35 | Mirror, documents, and family acceptance confirm sisterhood and belonging | 42.3 Parents’ Concern and Offer → 42.9 Realization and Reunion |
|
||||||
|
| 33 | Sisterly milestones at Ricardo’s, the sea, and the closing bench return | 39.5 Entering Ricardo’s → 48.2 Under the Flyover |
|
||||||
|
| 30 | Beth’s exploitation history and Maggie’s care begin transforming fear into action | 16.4 Feeding and Bathing → 16.5 Beth’s Story |
|
||||||
|
| 32 | Deaths linked to Rick, Baker’s protection, and partial confirmation from a frightened relative | 20.3 Beth Reveals Her Mother’s Death → 47.6 Rick Confronts Beth |
|
||||||
|
| 36 | Plan, lure, confession, confrontation, and arrest strategy at Rubery Hill | 46.4 Plan and Resolve → 47.7 Maggie Joins the Fight |
|
||||||
|
|
||||||
|
Notable boundary/status disagreements:
|
||||||
|
|
||||||
|
- `Becoming: Style and Steel` is `Planned` despite a `Payoff` event and configured actual-resolution scene.
|
||||||
|
- `First Sparks`, `Proof and Belonging`, and `The Sting at Rubery Hill` are `Planned` despite configured actual-resolution scenes and Payoff/Resolved-like events.
|
||||||
|
- `Orphaned and Unbelieved`, `Bent Lines`, `From Grooming to Resistance`, and `Murder Web` have no payoff/resolution-like event.
|
||||||
|
- Large gaps of 68–179 scenes are common. Some reflect legitimately long-running arcs, but the sparse event set makes “dormant” warnings unreliable without proposed evidence or author review.
|
||||||
|
|
||||||
|
## F. Contribution roles
|
||||||
|
|
||||||
|
### ThreadEvent roles
|
||||||
|
|
||||||
|
| Plot Line | Actual role counts |
|
||||||
|
|---|---|
|
||||||
|
| Beth | Introduced 1; Developed 4; Resolved 1 |
|
||||||
|
| Maggie | Developed 3; Payoff 1; Resolved 1 |
|
||||||
|
| Rot | Developed 2; Clue Planted 1 |
|
||||||
|
| Sisters | Developed 5; Revealed 1; Payoff 2; Resolved 1 |
|
||||||
|
| Predator | Developed 4; Clue Planted 1; Revealed 2; Payoff 1 |
|
||||||
|
| **All lines** | **Introduced 1; Developed 18; Clue Planted 2; Revealed 3; Payoff 4; Resolved 3** |
|
||||||
|
|
||||||
|
The remaining active lookup values—Mentioned, Complicated, Question Raised, Question Answered, False Lead, Contradicted, Retconned, and Note—are unused.
|
||||||
|
|
||||||
|
### PlotEvent roles
|
||||||
|
|
||||||
|
All 31 events are `Progress`. Start, Reveal, Twist, Branch, Split, Merge, Resolve, and Abandon have zero use. The investigation finding is therefore confirmed exactly: imported canonical events in Discovery are **31/31 Progress (100%)**.
|
||||||
|
|
||||||
|
### Compact spines for the other canonical lines
|
||||||
|
|
||||||
|
The Sisters spine is expanded in section G. Below are all 22 contributions for the other four lines. In every row the canonical Plot Event type is `Progress`, the canonical title repeats the ThreadEvent role, and the canonical description is the source reference shown after `ref`.
|
||||||
|
|
||||||
|
| Line / order | Chapter.scene — title | POV / stored story time | Thread · role · confidence | Contribution; canonical ref |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Beth / 1 | 1.1 — Finding Her Mother | Beth · 7 May 1980 night | Orphaned and Unbelieved · Introduced · .86 | Beth discovers her mother dead and enters shock/grief; `Ch1 S1 (5244)` |
|
||||||
|
| Beth / 3 | 1.3 — Social Workers Question | Beth · 7 May 1980 night | Orphaned and Unbelieved · Developed · .86 | Beth names an aunt and unknown sister while adults determine her future; `Ch1 S3 (5246)` |
|
||||||
|
| Beth / 41 | 6.10 — Ride Home | Maggie · 28 Dec 1982 night | Edges of Tenderness · Developed · .85 | Greg helps the group home after Rosie becomes ill; `Ch6 S10 (5519)` |
|
||||||
|
| Beth / 72 | 11.4 — Aftermath and Return | Beth · 30 Jan 1983 afternoon | Orphaned and Unbelieved · Developed · .86 | Beth and Maggie process the failed encounter and Beth returns to the flyover; `Ch12 S4 (5256)` |
|
||||||
|
| Beth / 221 | 37.9 — Afterglow and Departure | Maggie · 7 May 1983 night | Edges of Tenderness · Developed · .85 | Maggie and Rob rest, pack, and leave together; this is the questionable shared association; `Ch43 S9 (5420)` |
|
||||||
|
| Beth / 298 | 48.3 — Beth's Memory and Resolve | Beth · 18 May 1983 evening | Edges of Tenderness · Resolved · .85 | Beth reflects on her mother, changed identity, Maggie’s rescue, and a new chapter; `Ch48 S3 (5503)` |
|
||||||
|
| Maggie / 12 | 2.7 — Incident and Assessment | Maggie · 24 Dec 1982 morning | Becoming: Style and Steel · Developed · .82 | Maggie completes her driving assessment after the child-road incident; `Ch2 S7–S8 (5302–5303)` |
|
||||||
|
| Maggie / 144 | 26.2 — Confrontation with Sophie | Maggie · 7 Mar 1983 night | Becoming: Style and Steel · Payoff · .82 | Maggie withstands Sophie’s public attack before Rob intervenes; `Ch26 S6 (5336)` |
|
||||||
|
| Maggie / 198 | 34.3 — Drinks and the Surprise | Maggie · 16 Apr 1983 evening | Love and Legitimacy · Developed · .80 | Rob reveals Maggie’s Elle centre spread among admiring friends; `Ch38 S3 (5397)` |
|
||||||
|
| Maggie / 221 | 37.9 — Afterglow and Departure | Maggie · 7 May 1983 night | Love and Legitimacy · Developed · .80 | Maggie and Rob leave the picnic holding hands; `Ch43 S9 (5420)` |
|
||||||
|
| Maggie / 227 | 38.5 — Confession and Response | Maggie · 1 May 1983 afternoon | Love and Legitimacy · Resolved · .80 | Maggie tells Zoe about Rob; sadness and acceptance preserve their friendship; `Ch40 S5–S6 (5426–5427)` |
|
||||||
|
| Rot / 160 | 28.3 — Office Friction and Resolve | Graham · 7 Apr 1983 night | Bent Lines, Straight Cop · Developed · .77 | Baker dismisses the stakeout; Graham resolves to build evidence; `Ch28 S3 (5352)` |
|
||||||
|
| Rot / 212 | 36.3 — Cassette Revelation | Graham · 24 Apr 1983 night | Bent Lines, Straight Cop · Clue Planted · .77 | A cassette suggests instructions to make a report “clean”; `Ch28 S3 (5411)` |
|
||||||
|
| Rot / 285 | 46.2 — Meeting at the Pub | Maggie · 15 May 1983 morning | Bent Lines, Straight Cop · Developed · .77 | The group explains Rick’s crimes and failed efforts to obtain police action; `Ch46 S2 (5490)` |
|
||||||
|
| Predator / 100 | 16.4 — Feeding and Bathing | Maggie · 5 Feb 1983 night | From Grooming to Resistance · Developed · .86 | Care restores dignity while Maggie sees the extent of Beth’s injuries; `Ch16 S4 (5284)` |
|
||||||
|
| Predator / 101 | 16.5 — Beth’s Story | Maggie · 5 Feb 1983 night | From Grooming to Resistance · Revealed · .86 | Beth recounts Rick’s escalating abuse and exploitation; `Ch16 S5 (5285)` |
|
||||||
|
| Predator / 114 | 20.3 — Beth Reveals Her Mother’s Death | Beth · stored 7 May 1980 | Murder Web · Clue Planted · .88 | Beth challenges the accidental-drowning explanation; `Ch10 S3 (5306)` |
|
||||||
|
| Predator / 282 | 45.3 — Revelations and Refusals | Maggie · 15 May 1983 night | Murder Web · Developed · .88 | A frightened relative says Adam was murdered and refuses police involvement; `Ch45 S3 (5487)` |
|
||||||
|
| Predator / 287 | 46.4 — Plan and Resolve | Maggie · 15 May 1983 morning | The Sting at Rubery Hill · Developed · .95 | The group plans to lure Rick and record a confession; `Ch46 S4 (5492)` |
|
||||||
|
| Predator / 291 | 47.4 — Ben’s Intervention and Chase | Beth · 15 May 1983 night | The Sting at Rubery Hill · Developed · .95 | Rick attacks Ben and pursues Beth toward Rubery Hill; `Ch47 S4 (5496)` |
|
||||||
|
| Predator / 293 | 47.6 — Rick Confronts Beth | Beth · 15 May 1983 night | Murder Web · Revealed · .88 | Rick traps Beth and recounts violent murders; `Ch47 S6 (5498)` |
|
||||||
|
| Predator / 294 | 47.7 — Maggie Joins the Fight | Beth · 15 May 1983 night | The Sting at Rubery Hill · Payoff · .95 | Maggie confronts Rick and the physical fight begins; `Ch47 S7–S8 (5499–5500)` |
|
||||||
|
|
||||||
|
## G. Sisters of the Alpha Flame
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
|
||||||
|
- 9 contributing scenes across 7 chapters; 3.01% of the book.
|
||||||
|
- First: chapter 3, scene 7, index 20, **Garage and Reflection**.
|
||||||
|
- Last: chapter 48, scene 2, index 297, **Under the Flyover**.
|
||||||
|
- Roles: Developed 5, Revealed 1, Payoff 2, Resolved 1.
|
||||||
|
- Canonical confidence: three events at 0.84, three at 0.85, three at 0.92; mean 0.87.
|
||||||
|
- Longest gap: 78 intervening manuscript scenes, from index 20 to 99. Other notable gaps are 35 scenes (233→269) and 22 (233→256 when viewed across threads).
|
||||||
|
- All 9 scenes are unique to Sisters in the canonical model; none is shared with another line.
|
||||||
|
- Threads: First Sparks, Proof and Belonging, New Sisterhood in Practice.
|
||||||
|
- Candidate evidence: 9/9 canonical events match richer candidate events by candidate ID and scene.
|
||||||
|
- Manuscript: 9/9 have full source text, source paragraph ranges, Word paragraph ranges, and document linkage.
|
||||||
|
|
||||||
|
### Complete canonical spine
|
||||||
|
|
||||||
|
All structural Plot Event types are `Progress`. “Candidate detail” is retained review data, not the impoverished canonical event title/description.
|
||||||
|
|
||||||
|
| Order | Chapter.scene — title | POV / story time | Thread · role · conf. | Scene contribution and retained candidate detail |
|
||||||
|
|---:|---|---|---|---|
|
||||||
|
| 20 | 3.7 — Garage and Reflection | Maggie · 24 Dec 1982 evening | First Sparks · Developed · .85 | Maggie remains preoccupied with the girl under the flyover. Candidate: repeated care/visits establish recognition before proof; evidence references several source scenes. |
|
||||||
|
| 99 | 16.3 — Bringing Beth Home | Maggie · 5 Feb 1983 night | First Sparks · Payoff · .85 | Maggie offers food and shelter and brings Beth into the family home. Candidate: unconditional care deepens trust. |
|
||||||
|
| 113 | 20.2 — Conversation with Maggie | Beth · 9 Feb 1983 afternoon | First Sparks · Developed · .85 | Their teasing, observation, and familiarity show closeness. Candidate event confidence is only .64, materially below canonical .85. |
|
||||||
|
| 233 | 39.5 — Entering Ricardo’s | Maggie · 7 May 1983 evening | New Sisterhood · Developed · .84 | A special birthday dinner gives Beth warmth and dignity. Candidate: “A night for Mum”. |
|
||||||
|
| 256 | 42.3 — Parents’ Concern and Offer | Maggie · 8 May 1983 morning | Proof and Belonging · Developed · .92 | The parents offer Beth a permanent home and begin the disclosure. |
|
||||||
|
| 261 | 42.8 — Birth Certificate Revealed | Maggie · stored 31 Aug 1965 | Proof and Belonging · Revealed · .92 | Documents disclose Maggie’s birth identity/date and establish the twin connection. The stored story date appears to represent the certificate date, not scene time. |
|
||||||
|
| 262 | 42.9 — Realization and Reunion | Maggie · stored 31 Aug 1965 | Proof and Belonging · Payoff · .92 | Mirror recognition, embrace, and acceptance of the new family. The same chronology anomaly applies. |
|
||||||
|
| 269 | 43.7 — Arriving at Fairbourne | Maggie · 14 May 1983 morning | New Sisterhood · Developed · .84 | Beth’s first sight of the sea becomes a healing shared milestone. |
|
||||||
|
| 297 | 48.2 — Under the Flyover | Beth · 18 May 1983 evening | New Sisterhood · Resolved · .84 | Return to the bench frames a decision not to return to the former life and a shared future. |
|
||||||
|
|
||||||
|
This sequence does produce a coherent high-level telling, especially from index 233 onward. It is not a complete telling: the 78-scene early gap and absence of intermediate touches mean a “hide everything else” view would feel very compressed. The candidate detail is substantially more useful than the canonical titles `Developed`, `Payoff`, and so on.
|
||||||
|
|
||||||
|
## H. Multi-Plot-Line weave
|
||||||
|
|
||||||
|
The exact selected names are **Sisters of the Alpha Flame**, **Maggie’s Arc: Competence, Love, and Courage**, and **The Predator and the Taped Confession**.
|
||||||
|
|
||||||
|
Their union contains 22 scenes. None belongs canonically to more than one selected line.
|
||||||
|
|
||||||
|
| Order | Chapter.scene — title | Selected line(s) | Hidden scenes since prior selected contribution |
|
||||||
|
|---:|---|---|---:|
|
||||||
|
| 12 | 2.7 — Incident and Assessment | Maggie | — |
|
||||||
|
| 20 | 3.7 — Garage and Reflection | Sisters | 7 |
|
||||||
|
| 99 | 16.3 — Bringing Beth Home | Sisters | 78 |
|
||||||
|
| 100 | 16.4 — Feeding and Bathing | Predator | 0 |
|
||||||
|
| 101 | 16.5 — Beth’s Story | Predator | 0 |
|
||||||
|
| 113 | 20.2 — Conversation with Maggie | Sisters | 11 |
|
||||||
|
| 114 | 20.3 — Beth Reveals Her Mother’s Death | Predator | 0 |
|
||||||
|
| 144 | 26.2 — Confrontation with Sophie | Maggie | 29 |
|
||||||
|
| 198 | 34.3 — Drinks and the Surprise | Maggie | 53 |
|
||||||
|
| 221 | 37.9 — Afterglow and Departure | Maggie | 22 |
|
||||||
|
| 227 | 38.5 — Confession and Response | Maggie | 5 |
|
||||||
|
| 233 | 39.5 — Entering Ricardo’s | Sisters | 5 |
|
||||||
|
| 256 | 42.3 — Parents’ Concern and Offer | Sisters | 22 |
|
||||||
|
| 261 | 42.8 — Birth Certificate Revealed | Sisters | 4 |
|
||||||
|
| 262 | 42.9 — Realization and Reunion | Sisters | 0 |
|
||||||
|
| 269 | 43.7 — Arriving at Fairbourne | Sisters | 6 |
|
||||||
|
| 282 | 45.3 — Revelations and Refusals | Predator | 12 |
|
||||||
|
| 287 | 46.4 — Plan and Resolve | Predator | 4 |
|
||||||
|
| 291 | 47.4 — Ben’s Intervention and Chase | Predator | 3 |
|
||||||
|
| 293 | 47.6 — Rick Confronts Beth | Predator | 1 |
|
||||||
|
| 294 | 47.7 — Maggie Joins the Fight | Predator | 0 |
|
||||||
|
| 297 | 48.2 — Under the Flyover | Sisters | 2 |
|
||||||
|
|
||||||
|
The consecutive selected-line transitions are: Maggie→Sisters 2; Maggie→Maggie 3; Sisters→Sisters 5; Sisters→Predator 3; Predator→Predator 5; Predator→Sisters 2; Predator→Maggie 1. Immediate manuscript adjacency occurs at 99→100, 100→101, 113→114, 261→262, and 293→294.
|
||||||
|
|
||||||
|
The visible shape would be a long early Maggie/Sisters gap, a tightly alternating Sisters/Predator block in chapters 16 and 20, a Maggie-dominant middle stretch, a Sisters-dominant proof/belonging stretch, and a Predator-dominant climax followed by a Sisters coda. This is adjacency only; the database provides no causal edge.
|
||||||
|
|
||||||
|
## I. Plot-Line overlap
|
||||||
|
|
||||||
|
Only one canonical pair overlaps:
|
||||||
|
|
||||||
|
| Plot Line A | Plot Line B | A scenes | B scenes | Shared | % of A | % of B |
|
||||||
|
|---|---|---:|---:|---:|---:|---:|
|
||||||
|
| Beth’s Survival, Agency, and Healing | Maggie’s Arc: Competence, Love, and Courage | 6 | 5 | 1 | 16.67% | 20.00% |
|
||||||
|
|
||||||
|
Shared-scene distribution among the 30 canonical scenes:
|
||||||
|
|
||||||
|
| Lines per scene | Scenes | % canonical scenes |
|
||||||
|
|---:|---:|---:|
|
||||||
|
| 1 | 29 | 96.67% |
|
||||||
|
| 2 | 1 | 3.33% |
|
||||||
|
| 3 | 0 | 0% |
|
||||||
|
| 4+ | 0 | 0% |
|
||||||
|
|
||||||
|
The sole shared scene is chapter 37 scene 9, **Afterglow and Departure** (index 221). It has a `Developed` event in both Beth’s `Edges of Tenderness` thread and Maggie’s `Love and Legitimacy` thread. Both canonical descriptions are the same terse source reference, `Ch43 S9 (5420).` The summary concerns Maggie and Rob resting, packing up, and leaving after intimacy. The Beth association is therefore suspicious or at least not explainable from the canonical record; richer candidate data should be shown before treating it as a genuine convergence point.
|
||||||
|
|
||||||
|
The current data does not substantiate a multi-line convergence visual beyond this single questionable overlap.
|
||||||
|
|
||||||
|
## J. Sequencing and dependencies
|
||||||
|
|
||||||
|
The selected weave has useful manuscript-gap information, but no structured cross-Plot-Line dependencies:
|
||||||
|
|
||||||
|
- active `SceneDependencies` involving book 6097: 0;
|
||||||
|
- Reveal Setup, Action Consequence, Knowledge, Relationship, and Must Occur Before edges: 0;
|
||||||
|
- `PlotEventTargetPlotLines` rows for the book: 0;
|
||||||
|
- Branch/Split/Merge canonical events: 0.
|
||||||
|
|
||||||
|
There are 1,225 active continuity warnings across the book, dominated by general missing metadata and advisory character-knowledge warnings. They are not dependency edges. Relevant warnings correctly expose chronology reversals (for example, flashback dates and the birth-certificate-date anomaly) and long event gaps, but their volume means they need filtering before use in a Plot Line inspector.
|
||||||
|
|
||||||
|
Story-time gap arithmetic is unsafe across the weave without temporal interpretation. Examples include a 1980 flashback after a 1983 scene, chapters 42.8–42.9 stored as 31 August 1965, and chapter 38 stored earlier than chapter 37. The workspace should display stored chronology and warnings, not imply continuous elapsed time.
|
||||||
|
|
||||||
|
## K. Story Intelligence evidence
|
||||||
|
|
||||||
|
All 31 canonical events have `Source = WholeBookPlotSynthesis`, `SourceReferenceID`, `SourceKey`, and confidence. All 31 can still be matched to one persisted candidate event by `SourceReferenceID` (thread candidate) plus `SceneID`.
|
||||||
|
|
||||||
|
| Measure | Count | % of 31 |
|
||||||
|
|---|---:|---:|
|
||||||
|
| Matchable to candidate event | 31 | 100% |
|
||||||
|
| Canonical confidence present | 31 | 100% |
|
||||||
|
| Candidate confidence present | 31 | 100% |
|
||||||
|
| Useful candidate evidence present | 31 | 100% |
|
||||||
|
| Useful candidate description present | 31 | 100% |
|
||||||
|
| Richer candidate title not retained canonically | 31 | 100% |
|
||||||
|
| Richer candidate description not retained canonically | 31 | 100% |
|
||||||
|
| Canonical and candidate confidence differ | 29 | 93.55% |
|
||||||
|
| Candidate event lacks `AcceptedThreadEventID` backlink | 31 | 100% |
|
||||||
|
|
||||||
|
Example: Sisters chapter 42 scene 8 is canonically `Revealed / Revealed / Ch42 S8 (5466). / .92`. The candidate retains the title “Birth certificates reveal Grace and Beth’s twin birth”, a description of what the dates establish, the evidence reference, and event confidence .92. Chapter 20 scene 2 is canonically `Developed / Developed / Ch10 S2 (5305). / .85`; its candidate has a meaningful title and explanation but only .64 event confidence.
|
||||||
|
|
||||||
|
The canonical record has therefore lost useful display information even though the review tables still retain it. Matching is currently reconstructable but less durable than the intended explicit backlink.
|
||||||
|
|
||||||
|
## L. Manuscript availability
|
||||||
|
|
||||||
|
All 30 distinct canonical contributing scenes have:
|
||||||
|
|
||||||
|
- non-empty `SceneManuscriptSources.SourceText` (17,524 words in total);
|
||||||
|
- source paragraph start/end ranges;
|
||||||
|
- Word paragraph start/end indices;
|
||||||
|
- a scene-level manuscript document link to the one active document.
|
||||||
|
|
||||||
|
No contributing scene is missing source text. Sisters is 9/9 on every measure. A future inspector can show the actual imported manuscript immediately. It should not print or duplicate large manuscript passages in the workspace; load the selected scene on demand. Exact evidence highlighting remains unavailable because evidence has no durable character-offset mapping into source text.
|
||||||
|
|
||||||
|
## M. Confidence
|
||||||
|
|
||||||
|
Canonical imported-event confidence:
|
||||||
|
|
||||||
|
- minimum .77;
|
||||||
|
- maximum .95;
|
||||||
|
- mean .8555;
|
||||||
|
- median .85.
|
||||||
|
|
||||||
|
| Band | Events |
|
||||||
|
|---|---:|
|
||||||
|
| .90–1.00 | 6 |
|
||||||
|
| .80–.89 | 22 |
|
||||||
|
| .70–.79 | 3 |
|
||||||
|
| below .70 | 0 |
|
||||||
|
|
||||||
|
All three sub-.80 events belong to **Rot in the System**, making that entire line low-confidence in canonical terms (mean .77). Candidate per-event confidence ranges more widely; Sisters alone includes a .64 candidate event that became .85 canonically. The canonical confidence should therefore not be described as per-event model confidence without correcting or clearly labelling the materialisation behavior.
|
||||||
|
|
||||||
|
## N. Unattributed scenes
|
||||||
|
|
||||||
|
These are the complete four-scene no-known-attribution population. All have manuscript text and metrics but no purpose label/notes, outcome notes, location, or dependency.
|
||||||
|
|
||||||
|
| Order | Chapter.scene — title | Summary / POV / characters | Stored story time | Metrics (I/T/E/A) | Diagnostic label |
|
||||||
|
|---:|---|---|---|---|---|
|
||||||
|
| 33 | 6.2 — Gifts and Getting Ready | Gifts and a day getting ready for the pub; Maggie POV; Maggie, Mary, Rosie and imported incidental characters | 28 Dec 1982 morning | 6/3/6/4 | Preparation; relationship/character development; setup |
|
||||||
|
| 87 | 14.1 — Narration Label | Seven-word narration/date label; Zoe POV | 4 Feb 1983 | 1/1/1/1 | Exposition/time marker; likely structural parsing artefact |
|
||||||
|
| 264 | 43.2 — Getting Ready and Farewells | Maggie and Beth prepare for the day trip; Mary asks to be called “Mum”; Maggie POV | 14 May 1983 morning | 5/3/5/5 | Relationship development; setup/transition; possible missing Sisters association |
|
||||||
|
| 271 | 43.9 — Ice Cream Stand Flirtation | Beach lunch and a brief flirtatious encounter; Maggie POV | 14 May 1983 midday | 5/2/3/4 | Character/relationship beat; lightness/comic relief |
|
||||||
|
|
||||||
|
`I/T/E/A` means Overall Intensity, Tension, Emotional Weight, and Action. The remaining stored metric values support the same reading: scene 33 has Hope 7 and low Darkness/Violence/Mystery; scene 87 is 1 in every metric; scene 264 has Hope 7 and all Darkness/Romance/Sexual Charge/Violence/Comedy/Mystery values at 1; scene 271 has Romance 4, Sexual Charge 3, Hope 8, and low threat values. The labels are audit inferences from existing summaries and metrics, not canonical classifications. Scene 264 is the strongest missing-association candidate because it directly develops the new family relationship during an already canonical Sisters chapter. None of the four can responsibly be called unnecessary from current data.
|
||||||
|
|
||||||
|
## O. Proposed-only scenes
|
||||||
|
|
||||||
|
The 265 proposed-only scenes come entirely from pending `SceneSignals` candidates: 9 Plot Line candidates and 24 Thread candidates. There are no rejected candidates and no candidate event rows for these pending records; their associations are `StoryIntelligenceNarrativeCandidateEvidence` rows.
|
||||||
|
|
||||||
|
Pending Plot Line inventory:
|
||||||
|
|
||||||
|
| Candidate | Confidence / significance | Distinct evidence scenes | Proposed-only | Also canonical |
|
||||||
|
|---|---|---:|---:|---:|
|
||||||
|
| Death of Beth's mother | .95 / major | 76 | 66 | 10 |
|
||||||
|
| Driving test & flirtation | .93 / major | 15 | 14 | 1 |
|
||||||
|
| Driving Test Preparation / Nerves | .95 / major | 19 | 17 | 2 |
|
||||||
|
| Imminent change after departure | .90 / major | 2 | 2 | 0 |
|
||||||
|
| Maggie's Passing and Homecoming | .95 / major | 60 | 51 | 9 |
|
||||||
|
| Maggie’s Compassion Toward Beth | .90 / moderate | 1 | 1 | 0 |
|
||||||
|
| Tableroom Provocation | .93 / major | 4 | 4 | 0 |
|
||||||
|
| Threat to Cindy | .90 / major | 3 | 3 | 0 |
|
||||||
|
| Zoe's policing past and local corruption hints | .92 / moderate | 6 | 6 | 0 |
|
||||||
|
|
||||||
|
Thread candidates range from 2 to 129 distinct evidence scenes. The broadest are “What will happen to Beth now that she perceives herself as alone?” (129 distinct, 113 proposed-only), “night to early hours” (65/58), “Will Maggie’s nervousness affect her driving test outcome?” (56/51), and several mother-death/social-worker questions spanning much of the book.
|
||||||
|
|
||||||
|
Evidence quality is uneven. For example, `Death of Beth's mother` includes relevant grief/search scenes but also driving-test and pub-rescue scenes. Candidate evidence sometimes duplicates the same scene. Consequently proposed-only should be available as a separately styled review/evidence overlay, never silently mixed into canonical membership.
|
||||||
|
|
||||||
|
Some proposed-only scenes are already canonically associated with another line at the candidate level, but by definition the 265-scene population itself has no canonical association. Across candidate records, accepted/canonical scenes frequently also have pending evidence; that overlap is shown by the “Also canonical” column and must not create duplicate scene membership.
|
||||||
|
|
||||||
|
## P. Chapter coverage
|
||||||
|
|
||||||
|
`C/P/N` means canonical, proposed-only, and no-known-attribution scenes. Dominant shows canonical contributions only.
|
||||||
|
|
||||||
|
| Ch. | Title | Scenes | C/P/N | Lines | Dominant canonical line(s) | Canonical % |
|
||||||
|
|---:|---|---:|---|---:|---|---:|
|
||||||
|
| 1 | Drowning in Silence | 5 | 2/3/0 | 1 | Beth (2) | 40.0 |
|
||||||
|
| 2 | The Last Lesson | 8 | 1/7/0 | 1 | Maggie (1) | 12.5 |
|
||||||
|
| 3 | Revving Into Freedom | 7 | 1/6/0 | 1 | Sisters (1) | 14.3 |
|
||||||
|
| 4 | The Girl in Red | 6 | 0/6/0 | 0 | — | 0 |
|
||||||
|
| 5 | Echoes of Grace | 5 | 0/5/0 | 0 | — | 0 |
|
||||||
|
| 6 | Danger in the Dark | 10 | 1/8/1 | 1 | Beth (1) | 10.0 |
|
||||||
|
| 7 | Unveiling Desires | 10 | 0/10/0 | 0 | — | 0 |
|
||||||
|
| 8 | Threads of Fate | 6 | 0/6/0 | 0 | — | 0 |
|
||||||
|
| 9 | A Pattern of Purpose | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 10 | Drawn to the Flame | 4 | 0/4/0 | 0 | — | 0 |
|
||||||
|
| 11 | A Name That Shouldn’t Be Spoken | 4 | 1/3/0 | 1 | Beth (1) | 25.0 |
|
||||||
|
| 12 | Business as Usual | 4 | 0/4/0 | 0 | — | 0 |
|
||||||
|
| 13 | A Name She Never Owned | 10 | 0/10/0 | 0 | — | 0 |
|
||||||
|
| 14 | Threads and No Rope | 3 | 0/2/1 | 0 | — | 0 |
|
||||||
|
| 15 | Dinner, Drama, and Champagne | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 16 | The Cost of Survival | 6 | 3/3/0 | 2 | Predator (2) | 50.0 |
|
||||||
|
| 17 | The Weight of Kindness | 1 | 0/1/0 | 0 | — | 0 |
|
||||||
|
| 18 | A Date with Disappointment | 5 | 0/5/0 | 0 | — | 0 |
|
||||||
|
| 19 | The Right Side of the Line | 3 | 0/3/0 | 0 | — | 0 |
|
||||||
|
| 20 | That Wasn’t Her | 4 | 2/2/0 | 2 | Sisters; Predator (1 each) | 50.0 |
|
||||||
|
| 21 | Tainted | 4 | 0/4/0 | 0 | — | 0 |
|
||||||
|
| 22 | Stitched in Suspicion | 4 | 0/4/0 | 0 | — | 0 |
|
||||||
|
| 23 | The Girl in the Photograph | 6 | 0/6/0 | 0 | — | 0 |
|
||||||
|
| 24 | Lost and Missing | 6 | 0/6/0 | 0 | — | 0 |
|
||||||
|
| 25 | The Room at the End | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 26 | The Girl Who Wasn’t There | 10 | 1/9/0 | 1 | Maggie (1) | 10.0 |
|
||||||
|
| 27 | Silent Longing | 5 | 0/5/0 | 0 | — | 0 |
|
||||||
|
| 28 | Eyes on Limelight | 3 | 1/2/0 | 1 | Rot (1) | 33.3 |
|
||||||
|
| 29 | Ten Times the Woman | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 30 | Chaos and Chemistry | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 31 | Patterns in the Dark | 8 | 0/8/0 | 0 | — | 0 |
|
||||||
|
| 32 | The Long Silence | 8 | 0/8/0 | 0 | — | 0 |
|
||||||
|
| 33 | The View from the Hill | 5 | 0/5/0 | 0 | — | 0 |
|
||||||
|
| 34 | A Moment to Shine | 7 | 1/6/0 | 1 | Maggie (1) | 14.3 |
|
||||||
|
| 35 | Paid in Desire | 7 | 0/7/0 | 0 | — | 0 |
|
||||||
|
| 36 | Thin Blue Lies | 3 | 1/2/0 | 1 | Rot (1) | 33.3 |
|
||||||
|
| 37 | Claimed by Fire | 10 | 1/9/0 | 2 | Maggie; Beth (same shared scene) | 10.0 |
|
||||||
|
| 38 | Brighter Days | 6 | 1/5/0 | 1 | Maggie (1) | 16.7 |
|
||||||
|
| 39 | A Taste of Freedom | 11 | 1/10/0 | 1 | Sisters (1) | 9.1 |
|
||||||
|
| 40 | No Way Out | 8 | 0/8/0 | 0 | — | 0 |
|
||||||
|
| 41 | Threaded Souls | 6 | 0/6/0 | 0 | — | 0 |
|
||||||
|
| 42 | Born Twice | 9 | 3/6/0 | 1 | Sisters (3) | 33.3 |
|
||||||
|
| 43 | Waves and Wishes | 15 | 1/12/2 | 1 | Sisters (1) | 6.7 |
|
||||||
|
| 44 | Some Questions Don’t Need Answers | 2 | 0/2/0 | 0 | — | 0 |
|
||||||
|
| 45 | Shadows in Harborne | 4 | 1/3/0 | 1 | Predator (1) | 25.0 |
|
||||||
|
| 46 | The Bait | 4 | 2/2/0 | 2 | Predator; Rot (1 each) | 50.0 |
|
||||||
|
| 47 | No Going Back | 8 | 3/5/0 | 1 | Predator (3) | 37.5 |
|
||||||
|
| 48 | Freedom | 4 | 2/2/0 | 2 | Sisters; Beth (1 each) | 50.0 |
|
||||||
|
|
||||||
|
Twenty-four chapters have zero canonical coverage. The highest canonical convergence is only two distinct lines in chapters 16, 20, 37, 46, and 48. Chapter 37’s two-line convergence is a single shared scene. The chapter table reinforces that the accepted canonical set is a highlight reel, not comprehensive scene attribution.
|
||||||
|
|
||||||
|
## Q. Visual significance feasibility
|
||||||
|
|
||||||
|
Existing signals can support cautious first-pass visual weighting:
|
||||||
|
|
||||||
|
- ThreadEvent role differentiates ordinary development from reveal/payoff/resolution.
|
||||||
|
- All 30 canonical scenes have the complete 1–10 metric set.
|
||||||
|
- Average metrics align directionally with role: Revealed averages intensity 8.33, tension 8.00, emotional weight 8.67; Payoff averages 7.75/6.75/7.50; Developed averages 6.89/5.33/6.44.
|
||||||
|
- line importance and thread importance exist, although all imported lines are Primary and all threads are 5, so they provide no within-book discrimination here;
|
||||||
|
- canonical and candidate confidence exist, but canonical confidence is not reliably per-event;
|
||||||
|
- candidate significance exists at candidate/thread level, not contribution level;
|
||||||
|
- shared-scene count, dependencies, and branch/split/merge involvement provide almost no signal in this book (one shared scene, zero dependencies, zero structural targets);
|
||||||
|
- canonical scenes have no assigned scene-purpose labels, so purpose cannot currently weight these contributions.
|
||||||
|
|
||||||
|
A first workspace can visually distinguish roles and show metrics/confidence as separate cues. It should not manufacture a composite percentage or label a contribution “major” solely from these heuristics. Author-confirmed contribution significance remains absent.
|
||||||
|
|
||||||
|
## R. Data anomalies
|
||||||
|
|
||||||
|
1. Canonical coverage is only 30/299 scenes, while pending evidence touches 265 more.
|
||||||
|
2. All 31 structural event types are flattened to `Progress`.
|
||||||
|
3. All 31 event titles are generic role labels; richer titles/descriptions remain only in candidate records.
|
||||||
|
4. All 31 accepted candidate events lack the intended `AcceptedThreadEventID` backlink.
|
||||||
|
5. Canonical confidence differs from candidate event confidence for 29/31 events.
|
||||||
|
6. All lines are Main Plot/Primary/same colour/sort 0; all threads are Question/importance 5.
|
||||||
|
7. Several planned threads have actual-resolution boundaries and payoff-like events; several unresolved threads have no resolution event.
|
||||||
|
8. Very long gaps occur within threads (up to 179 intervening scenes).
|
||||||
|
9. The only shared canonical scene has a questionable Beth association based on its summary.
|
||||||
|
10. No canonical scene has a scene-purpose assignment, though all have metrics.
|
||||||
|
11. No scene dependencies or plot-event targets exist, preventing structured causal/weave analysis.
|
||||||
|
12. Pending `SceneSignals` evidence is overbroad and sometimes duplicated or unrelated to the candidate title.
|
||||||
|
13. Candidate title `Maggie\u00039s Compassion Toward Beth` contains a control-character encoding defect.
|
||||||
|
14. Accepted candidate `Significance` text is truncated by its short storage field (for example, “Core identity, emoti”), so it is not a clean display label.
|
||||||
|
15. Canonical descriptions and candidate evidence contain stale/mismatched chapter references (for example database chapter 3 described as `Ch4`, chapter 37 as `Ch43`, and Rot chapter 36 described as `Ch28`).
|
||||||
|
16. Stored story dates sometimes represent recalled/document dates rather than scene time, producing large false elapsed-time gaps and continuity warnings.
|
||||||
|
17. The book status is still `Planning` despite being a complete import; this field should not be used to decide import completeness.
|
||||||
|
18. No canonical event has a missing title/description, no duplicate same-thread/same-scene event was found, no event points at an archived book/chapter/scene/thread/line, and no canonical manuscript source is missing.
|
||||||
|
|
||||||
|
## S. Implications for the dedicated Plot Lines design
|
||||||
|
|
||||||
|
Without schema changes, the first workspace can display:
|
||||||
|
|
||||||
|
- a selectable inventory of the five canonical lines and their 11 threads;
|
||||||
|
- only contributing scenes, ordered by `NarrativeSceneOrder`, with chapter/scene, summary, POV, stored chronology, characters/location, role, event confidence, thread status/importance, and line colour;
|
||||||
|
- complete single-line spines such as the nine-scene Sisters sequence;
|
||||||
|
- a multi-line union such as the 22-scene selected weave, with line labels, adjacency, manuscript gaps, and chapter gaps;
|
||||||
|
- shared-scene badges (while making the scarcity visible rather than suggesting dense overlap);
|
||||||
|
- on-demand complete manuscript text for every canonical contribution;
|
||||||
|
- richer candidate title, description, evidence, and candidate confidence by matching the retained synthesis records;
|
||||||
|
- a separate proposed-evidence overlay, clearly marked Pending and never presented as canonical;
|
||||||
|
- continuity warnings and metric profiles, filtered to selected scenes;
|
||||||
|
- explicit “no structured dependency” states instead of invented causal links.
|
||||||
|
|
||||||
|
It cannot currently display reliable canonical contribution significance, meaningful Start/Twist/Branch/Merge structure, durable accepted-event backlinks, or structured cross-line causality. The design should preserve the distinction between canonical, pending evidence, and no-known attribution.
|
||||||
|
|
||||||
|
## T. Recommended next implementation step
|
||||||
|
|
||||||
|
Implement the read-only contribution read model proposed by the architectural investigation, before building the visual workspace. It should query canonical line/thread/event/scene data and enrich each imported event from its persisted candidate record using `SourceReferenceID + SceneID`, while returning pending evidence as a separate collection.
|
||||||
|
|
||||||
|
The read model should explicitly expose data quality states: candidate match method, confidence source, stale/missing accepted backlink, structural type flattening, shared-line count, manuscript availability, chronology warnings, and canonical versus pending status. Build the first Sisters and selected-weave screens against that read model. Do not add contribution-significance fields until the resulting UI demonstrates what author-confirmed fact actually needs persistence.
|
||||||
|
|
||||||
|
## Appendix: reproducibility notes
|
||||||
|
|
||||||
|
The audit ran direct read-only `SELECT` statements against a connection forced to `PlotDirector_Development`. The core population query was equivalent to:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WITH ActiveScenes AS (
|
||||||
|
SELECT s.SceneID, nso.ChapterID, nso.GlobalSceneIndex
|
||||||
|
FROM dbo.Scenes s
|
||||||
|
JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = s.SceneID
|
||||||
|
WHERE nso.BookID = 6097 AND s.IsArchived = 0
|
||||||
|
), Canonical AS (
|
||||||
|
SELECT DISTINCT te.SceneID
|
||||||
|
FROM dbo.ThreadEvents te
|
||||||
|
JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID AND pt.IsArchived = 0
|
||||||
|
JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID AND pl.IsArchived = 0
|
||||||
|
WHERE pl.ProjectID = 4085 AND (pl.BookID IS NULL OR pl.BookID = 6097)
|
||||||
|
), Proposed AS (
|
||||||
|
SELECT ev.SceneID
|
||||||
|
FROM dbo.StoryIntelligenceNarrativeCandidateEvents ev
|
||||||
|
JOIN dbo.StoryIntelligenceNarrativeCandidates nc
|
||||||
|
ON nc.NarrativeCandidateID = ev.NarrativeCandidateID
|
||||||
|
WHERE nc.BookID = 6097
|
||||||
|
UNION
|
||||||
|
SELECT e.SceneID
|
||||||
|
FROM dbo.StoryIntelligenceNarrativeCandidateEvidence e
|
||||||
|
JOIN dbo.StoryIntelligenceNarrativeCandidates nc
|
||||||
|
ON nc.NarrativeCandidateID = e.NarrativeCandidateID
|
||||||
|
WHERE nc.BookID = 6097
|
||||||
|
)
|
||||||
|
SELECT CASE
|
||||||
|
WHEN c.SceneID IS NOT NULL THEN N'Canonical'
|
||||||
|
WHEN p.SceneID IS NOT NULL THEN N'Proposed-only'
|
||||||
|
ELSE N'No known attribution'
|
||||||
|
END AS Population,
|
||||||
|
COUNT(*) AS SceneCount
|
||||||
|
FROM ActiveScenes a
|
||||||
|
LEFT JOIN Canonical c ON c.SceneID = a.SceneID
|
||||||
|
LEFT JOIN Proposed p ON p.SceneID = a.SceneID
|
||||||
|
GROUP BY CASE
|
||||||
|
WHEN c.SceneID IS NOT NULL THEN N'Canonical'
|
||||||
|
WHEN p.SceneID IS NOT NULL THEN N'Proposed-only'
|
||||||
|
ELSE N'No known attribution'
|
||||||
|
END;
|
||||||
|
```
|
||||||
|
|
||||||
|
Canonical spines joined `PlotLines → PlotThreads → ThreadEvents → NarrativeSceneOrder → Scenes`, with active lifecycle filters and book 6097. Candidate enrichment matched `ThreadEvents.SourceReferenceID = StoryIntelligenceNarrativeCandidateEvents.NarrativeCandidateID` and equal `SceneID`; the explicit candidate-event backlink was deliberately not assumed because it is null for all 31 rows. Pairwise overlap counted distinct scene IDs per line. All percentages use the 299 active-scene denominator unless explicitly labelled “canonical scenes”.
|
||||||
582
docs/plot-lines-scene-contribution-timeline-investigation.md
Normal file
582
docs/plot-lines-scene-contribution-timeline-investigation.md
Normal file
@ -0,0 +1,582 @@
|
|||||||
|
# Plot Lines, Scene Contribution, and Timeline Simplification Investigation
|
||||||
|
|
||||||
|
Date: 29 October 2026
|
||||||
|
Scope: read-only source/schema investigation; no application, database, prompt, or data changes
|
||||||
|
|
||||||
|
## A. Executive summary
|
||||||
|
|
||||||
|
PlotDirector is substantially closer to the proposed direction than the current Timeline suggests. The canonical model already separates scenes, plot abstractions, scene-anchored plot developments, chronology, and scenario ordering:
|
||||||
|
|
||||||
|
- A `PlotLine` is a project-owned, optionally book-scoped narrative abstraction.
|
||||||
|
- A `PlotThread` is a stateful strand inside a plot line.
|
||||||
|
- A `ThreadEvent` is the effective scene-to-thread—and therefore scene-to-plot-line—association. It classifies what happened at that scene and can describe branch, split, merge, and other plot structure.
|
||||||
|
- A `Scene` owns manuscript order and story-time fields.
|
||||||
|
- A `ScenarioSceneOrder` overlays an alternative order without changing canonical scenes until explicitly applied.
|
||||||
|
- `SceneManuscriptSources` retains complete imported scene text and source ranges.
|
||||||
|
|
||||||
|
The sparse Timeline is principally a presentation problem. `BuildPlotLanes` deliberately expands every visible plot line over every ordered scene, creating an empty slot for non-contributing scenes. A dedicated Plot Lines workspace can instead query the same `ThreadEvents`, keep only their scenes, and order those scenes by canonical or scenario order. No new scene/plot join table is needed merely to produce single-line or multi-line narrative views.
|
||||||
|
|
||||||
|
There are, however, material semantic gaps. Canonical membership is currently event-based and effectively binary. `ThreadEvent.EventTypeID` provides a useful contribution role and `Confidence` is retained for imported events, but canonical events do not have an independent significance/weight or a durable evidence excerpt. Whole-book Story Intelligence knows more: it produces plot-line significance, per-event confidence, descriptions, and evidence, and persists those in review/synthesis records. Acceptance only materialises some of that information into `PlotLines`, `PlotThreads`, and `ThreadEvents`. A future contribution model should extend this existing event association rather than introduce a parallel membership system.
|
||||||
|
|
||||||
|
The main Timeline can safely lose Plot Line and Character lanes without deleting either domain. Plot filters/focus, scene-card character chips, the Scene Inspector, character quick-add, and all canonical associations are independent of the lane rows. Plot-lane removal is not entirely cosmetic, though: the client currently draws branch/split/merge connectors and computes several plot-health warnings there. Those capabilities should be preserved in the dedicated Plot Lines/Story Health experience before removing their only visualisation. Character-lane removal has lower domain risk; its unique rich appearance tooltip should be checked against the Character and Scene Inspector pages before retirement.
|
||||||
|
|
||||||
|
The recommended direction is therefore reuse-first:
|
||||||
|
|
||||||
|
1. establish a contribution read model over existing `ThreadEvents` and synthesis evidence;
|
||||||
|
2. build the dedicated, compact Plot Lines workspace;
|
||||||
|
3. integrate scenario ordering through `ScenarioSceneOrder`;
|
||||||
|
4. relocate plot-only health and structural visualisation;
|
||||||
|
5. remove both lane presentations and their settings from Timeline;
|
||||||
|
6. only then add persisted role/significance/evidence fields where the confirmed UX cannot be satisfied by existing records.
|
||||||
|
|
||||||
|
No development/test database count was included. The repository has no isolated fixture that represents a fully analysed imported book, and accessing the shared development database was unnecessary for the architectural conclusions. The report includes a safe count definition for a later read-only audit.
|
||||||
|
|
||||||
|
## B. Current Plot Line architecture
|
||||||
|
|
||||||
|
### Canonical hierarchy
|
||||||
|
|
||||||
|
```text
|
||||||
|
Project
|
||||||
|
└─ PlotLine (optionally scoped to Book)
|
||||||
|
└─ PlotThread
|
||||||
|
└─ ThreadEvent ──> Scene ──> Chapter ──> Book
|
||||||
|
└─ PlotEventTargetPlotLines ──> other PlotLines
|
||||||
|
```
|
||||||
|
|
||||||
|
There is no direct `ScenePlotLine` table or model. A scene participates in a plot line when a non-archived thread in that plot line has a `ThreadEvent` attached to the scene. Multiple events and multiple threads can attach the same scene to the same or different plot lines.
|
||||||
|
|
||||||
|
Primary implementation references are:
|
||||||
|
|
||||||
|
- schema and current timeline procedure: `PlotLine/Sql/004_Phase1C_PlotThreads.sql` and `PlotLine/Sql/053_Phase6A_PlotLineDataModel.sql`;
|
||||||
|
- models: `PlotLine/Models/CoreModels.cs`;
|
||||||
|
- persistence: `PlotLine/Data/Repositories.cs` (`PlotRepository`, `TimelineRepository`);
|
||||||
|
- domain/UI services: `PlotLine/Services/CoreServices.cs` (`PlotService`, `TimelineService`);
|
||||||
|
- management UI: `PlotLine/Controllers/PlotLinesController.cs`, `PlotLine/Controllers/PlotThreadsController.cs`, `PlotLine/Views/PlotLines`, `PlotLine/Views/PlotThreads`;
|
||||||
|
- scene-level management: `PlotLine/Views/Shared/SceneInspectorV2/_SceneThreadsEditor.cshtml`;
|
||||||
|
- Timeline presentation: `PlotLine/Views/Timeline/Index.cshtml`, `PlotLine/wwwroot/js/site.js`, and `PlotLine/wwwroot/css/site.css`.
|
||||||
|
|
||||||
|
### Relevant field matrix
|
||||||
|
|
||||||
|
| Concept/field | Storage and population | Reads/UI | Status |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Plot line name and description | `PlotLines.PlotLineName`, `Description`; manual Plot Line editor or accepted Story Intelligence candidate | Plot list/editor, thread pages, Timeline labels, filters, Story Intelligence context | Active |
|
||||||
|
| Ownership/scope | required `ProjectID`, optional `BookID`; manual selection or synthesis book | Lists and Timeline include project-wide lines plus matching book | Active; no direct chapter ownership |
|
||||||
|
| Type/category | `PlotLineTypeID` lookup: Main Plot, Side Plot, Mystery, Emotional Arc, Relationship Arc, Character Arc, Object Trail, Investigation, Location Plot, Theme | Stored and shown on Plot Line list; editor currently posts a hidden type field instead of offering the former type selector | Active data, incompletely exposed in current editor |
|
||||||
|
| Plot importance | `PlotImportanceID`: Primary, Secondary, Minor | Plot list/editor and synthesis materialisation default | Active, line-level only |
|
||||||
|
| Parent/emergence | `ParentPlotLineID`, `EmergesFromPlotLineID` | Plot editor and model/list reads | Active structural metadata; not used to decide scene membership |
|
||||||
|
| Sort and colour | `SortOrder`, `Colour` | Plot list and Timeline lane ordering/colour | Active; presentation metadata reusable in a dedicated workspace |
|
||||||
|
| Timeline visibility | `IsVisibleOnTimeline` | Plot editor/list and `Timeline_GetByProject` | Active but Timeline-specific; becomes legacy when plot lanes leave Timeline |
|
||||||
|
| Archive state | `IsArchived` | All canonical list/read procedures | Active lifecycle field |
|
||||||
|
| Thread title/summary/type | `PlotThreads.ThreadTitle`, `Summary`, `ThreadTypeID` | Thread management, Scene Inspector, Timeline tooltip/context | Active |
|
||||||
|
| Thread state | `ThreadStatusID`: Planned, Introduced, Developing, Dormant, Ready for Payoff, Resolved, Abandoned | Thread editor and Timeline/health logic | Active; this is thread state, not plot-line state |
|
||||||
|
| Thread importance | integer `Importance` (1–10) | Thread UI and Timeline marker prioritisation/tooltip | Active; thread-level, not per-scene contribution significance |
|
||||||
|
| Thread boundary scenes | `IntroducedSceneID`, `PlannedResolutionSceneID`, `ActualResolutionSceneID` | Thread management and health/context | Active, but separate from individual event associations |
|
||||||
|
| Scene association | `ThreadEvents.SceneID` plus `PlotThreadID` | Scene Inspector, plot/thread lists, Timeline/filter/focus, Story Health | Active canonical membership mechanism |
|
||||||
|
| Contribution/development role | `ThreadEvents.EventTypeID` → Introduced, Mentioned, Developed, Complicated, Clue Planted, Question Raised, Question Answered, False Lead, Revealed, Payoff, Resolved, Contradicted, Retconned, Note | Event editor, markers/tooltips, scenario checks, synthesis output constraint | Active and close to proposed “Role,” though vocabulary differs |
|
||||||
|
| Structural plot event | `PlotEventTypeID` → Start, Progress, Reveal, Twist, Branch, Split, Merge, Resolve, Abandon | Event editor and Timeline connector drawing | Active; imported events are currently materialised as `Progress`, which loses this dimension |
|
||||||
|
| Event targets | legacy single `TargetPlotLineID` plus many-to-many `PlotEventTargetPlotLines` | Event editing and Timeline branch/split/merge connectors | Active; expresses structural links, not shared event identity |
|
||||||
|
| Event description | `EventTitle`, `EventDescription` | Scene Inspector and Timeline tooltips | Active; can contain an explanation, but has no enforced semantics |
|
||||||
|
| Provenance/confidence | `Source`, `SourceReferenceID`, `SourceKey`, `Confidence` | populated by Story Intelligence acceptance; mainly persistence/idempotency and review traceability | Active backend data, minimally exposed in canonical UI |
|
||||||
|
| Plot-line status | none on `PlotLines` | Whole-book candidate has `BookStatus`; canonical status is inferred from threads/events | Does not exist canonically |
|
||||||
|
| Direct character/relationship/asset/location link | none on `PlotLines` | Indirectly discoverable by joining shared scenes; whole-book prompt receives character context | Does not exist |
|
||||||
|
|
||||||
|
Plot lines are included in project backup/restore and permanent-deletion handling. They are not merely transient Timeline constructs.
|
||||||
|
|
||||||
|
### Services and UI behavior
|
||||||
|
|
||||||
|
`PlotService` is a conventional Dapper/stored-procedure service for list, create, edit, save, and archive. The plot list describes each line and links to Timeline focus and thread creation. The editor exposes name, importance, book scope, parent, emergence, sort, colour, description, and Timeline visibility. The current editor carries `PlotLineTypeID` as a hidden input, so category is not presently editable there even though it remains canonical.
|
||||||
|
|
||||||
|
Threads and thread events provide the operational development model. Events can be maintained from thread pages and from a scene’s inspector. This is important for the future workspace: manual books already have a supported way to create membership and contribution records; imported books materialise the same canonical records after review.
|
||||||
|
|
||||||
|
## C. Scene/Plot Line association
|
||||||
|
|
||||||
|
### Exact membership rule
|
||||||
|
|
||||||
|
For canonical/accepted data:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Scene X belongs to Plot Line Y
|
||||||
|
iff an active ThreadEvent references X
|
||||||
|
and its active PlotThread references Y.
|
||||||
|
```
|
||||||
|
|
||||||
|
The current Timeline implements the same rule. `Timeline_GetByProject` joins `ThreadEvents → PlotThreads → PlotLines → Scenes`. `BuildPlotLanes` groups those events by `PlotLineID` and `SceneID`, then creates one slot for every scene. The latter expansion creates the visual sparsity; it is not a storage limitation.
|
||||||
|
|
||||||
|
### Cardinality and ordering
|
||||||
|
|
||||||
|
- One scene can have zero, one, or many thread events.
|
||||||
|
- Those events can belong to multiple threads and multiple plot lines, so scene-to-plot-line membership is effectively many-to-many.
|
||||||
|
- Multiple events in the same line and scene are permitted.
|
||||||
|
- Membership has no independent sort field. Plot developments inherit manuscript order from `Book.SortOrder`, `Chapter.SortOrder`, and `Scene.SortOrder`/`NarrativeSceneOrder`.
|
||||||
|
- In a scenario they inherit the overlay order from `ScenarioSceneOrder.ProposedChapterID` and `ProposedSortOrder`.
|
||||||
|
- Story-time position is inherited from the linked scene’s chronology fields.
|
||||||
|
|
||||||
|
### Manual versus imported books
|
||||||
|
|
||||||
|
Manual membership is authored by adding a thread event to a scene. The author selects the thread, event type, structural plot-event type/targets, title, and description.
|
||||||
|
|
||||||
|
Imported membership has two stages:
|
||||||
|
|
||||||
|
1. proposed membership in Story Intelligence candidate/event/evidence tables;
|
||||||
|
2. canonical membership only after review acceptance creates or matches a plot line/thread and materialises `ThreadEvents`.
|
||||||
|
|
||||||
|
Pending or rejected candidates do not make a scene a member for Timeline/filter purposes. Consequently “no canonical plot line” and “the analysis found no possible plot line” are not equivalent.
|
||||||
|
|
||||||
|
### Binary, weighted, classified, or inferred?
|
||||||
|
|
||||||
|
- Membership itself is binary and inferred from existence of at least one canonical event.
|
||||||
|
- It is classified by event type and optionally structural plot-event type.
|
||||||
|
- A thread has importance 1–10; a plot line has Primary/Secondary/Minor importance.
|
||||||
|
- Imported events may carry confidence.
|
||||||
|
- There is no canonical per-scene/per-plot-line significance or contribution weight.
|
||||||
|
- Imported evidence/reasoning exists in review records but is not part of the canonical membership row.
|
||||||
|
|
||||||
|
## D. Existing contribution/significance data
|
||||||
|
|
||||||
|
The proposed “Role” and “Significance” should remain distinct because existing data already demonstrates that distinction.
|
||||||
|
|
||||||
|
### Role
|
||||||
|
|
||||||
|
`ThreadEventType` is the strongest reusable role concept. It covers introduction, mention, development, complication, clue/question mechanics, false leads, revelation, payoff, resolution, contradiction, retcon, and notes. `PlotEventType` adds structural semantics—start/progress/reveal/twist/branch/split/merge/resolve/abandon. Scene purpose labels add broader scene functions such as Advances Plot, Setup, Payoff, Reveal, Exposition, Emotional Recovery, Transition/Travel, Consequence, and Reversal.
|
||||||
|
|
||||||
|
These sources can support an initial read model, but they are not interchangeable:
|
||||||
|
|
||||||
|
- thread event type describes the scene’s contribution to one thread;
|
||||||
|
- plot event type describes structural behavior between plot lines;
|
||||||
|
- scene purpose describes the whole scene and is not line-specific.
|
||||||
|
|
||||||
|
The illustrative future roles can be mapped approximately for display, but “Escalation,” “Turning Point,” “Aftermath,” “Reflection,” and “Transition” are not consistently encoded as line-specific event roles. Derivation should be labelled as derived, not presented as author-confirmed data.
|
||||||
|
|
||||||
|
### Significance
|
||||||
|
|
||||||
|
Available signals are:
|
||||||
|
|
||||||
|
- `PlotImportance` at line level (Primary/Secondary/Minor);
|
||||||
|
- `PlotThread.Importance` at thread level (1–10);
|
||||||
|
- Story Intelligence candidate `Significance` at candidate/plot/thread level;
|
||||||
|
- candidate event and canonical imported event `Confidence`;
|
||||||
|
- scene metrics and scene purpose, which describe the scene globally;
|
||||||
|
- event type and recurrence, from which prominence could be heuristically ranked.
|
||||||
|
|
||||||
|
None is a canonical per-scene contribution significance. Critical/Major/Supporting/Minor cannot be faithfully represented without either a clearly documented derivation or new persisted information. A first workspace can operate without it and show role, confidence, line/thread importance, and evidence separately.
|
||||||
|
|
||||||
|
### Explanation and evidence
|
||||||
|
|
||||||
|
Manual `EventDescription` and imported candidate-event `Description` are explanations. `StoryIntelligenceNarrativeCandidateEvents.Evidence` and `StoryIntelligenceNarrativeCandidateEvidence.Evidence` retain textual evidence. Canonical `ThreadEvents` do not have an evidence column. When accepted, evidence may become the event description only when no event description exists; otherwise the distinct evidence is not copied.
|
||||||
|
|
||||||
|
## E. Story Intelligence import
|
||||||
|
|
||||||
|
### Discovery point and inputs
|
||||||
|
|
||||||
|
The current path is whole-book plot synthesis after character resolution. `WholeBookPlotIntelligenceService` supplies the synthesis with:
|
||||||
|
|
||||||
|
- complete canonical scene sequence and full `SceneManuscriptSources.SourceText`;
|
||||||
|
- scene summaries, setting, POV, and chronology context;
|
||||||
|
- canonical characters and aliases;
|
||||||
|
- existing plot lines and threads;
|
||||||
|
- optional author plot seeds/context.
|
||||||
|
|
||||||
|
The prompt asks for sustained plot lines, subordinate threads, and every meaningful scene touch. It explicitly distinguishes meaningful narrative contribution from mere character presence. Per-event output is constrained to the existing thread-event vocabulary.
|
||||||
|
|
||||||
|
An older per-scene consolidation path in `StoryIntelligenceNarrativeReviewService.EnsureCandidatesAsync` can read `SceneIntelligenceNarrativeArc` values (title, description, arc type, scale, change type, significance, matching IDs, evidence, and confidence). Current review GET behavior uses persisted whole-book candidates and does not generate candidates during rendering; this older path should be treated as legacy/fallback behavior, not the current authority.
|
||||||
|
|
||||||
|
### What is returned and persisted
|
||||||
|
|
||||||
|
Whole-book output includes:
|
||||||
|
|
||||||
|
- plot-line title, description, significance, book status, existing-line match/confidence/reason, and author-seed match/confidence/reason;
|
||||||
|
- subordinate thread details and match data;
|
||||||
|
- per-scene event key, `SceneID`, event type, title, description, evidence, confidence, and sort order.
|
||||||
|
|
||||||
|
Persistence is deliberately redundant for audit/review:
|
||||||
|
|
||||||
|
- `WholeBookPlotSynthesisRuns.ResultJson` keeps the raw result, request/response metadata, model, token counts, status, and errors;
|
||||||
|
- `StoryIntelligenceNarrativeCandidates` keeps line/thread candidates, significance, state/change information, matches, confidence, source, and review decision;
|
||||||
|
- `StoryIntelligenceNarrativeCandidateEvents` keeps structured scene touches and evidence;
|
||||||
|
- `StoryIntelligenceNarrativeCandidateEvidence` keeps scene-keyed contribution/evidence rows.
|
||||||
|
|
||||||
|
This means useful AI output is not merely transient.
|
||||||
|
|
||||||
|
### Materialisation losses
|
||||||
|
|
||||||
|
On acceptance, `StoryIntelligenceNarrativeReviewService` creates or matches canonical entities and events. The following reductions occur:
|
||||||
|
|
||||||
|
- a new line is materialised with canonical importance defaulted to Primary rather than preserving a candidate-level significance scale;
|
||||||
|
- a new thread receives importance 5 rather than a synthesis-derived value;
|
||||||
|
- per-event type, title/description, source reference/key, and confidence survive;
|
||||||
|
- distinct evidence does not have a canonical destination;
|
||||||
|
- candidate-level `Significance` does not become a per-scene contribution value;
|
||||||
|
- imported `PlotEventTypeID` is set to Progress, so structural start/reveal/twist/branch/merge semantics are not inferred/materialised even where event type wording may imply them.
|
||||||
|
|
||||||
|
The review/synthesis records remain available, but ordinary Plot Line/Timeline reads do not join them. The current UI therefore exposes considerably less than the import knows.
|
||||||
|
|
||||||
|
## F. Manuscript text availability
|
||||||
|
|
||||||
|
Migration `150_Phase24I_SceneManuscriptSource.sql` establishes `SceneManuscriptSources`, with one durable row per scene containing:
|
||||||
|
|
||||||
|
- complete `SourceText` (`nvarchar(max)`);
|
||||||
|
- project, book, chapter, and scene IDs;
|
||||||
|
- word and character counts;
|
||||||
|
- source start/end paragraph;
|
||||||
|
- Word start/end paragraph index;
|
||||||
|
- source kind and timestamps.
|
||||||
|
|
||||||
|
The row is efficiently retrievable by its primary-key `SceneID`, and repository procedures list scene sources by chapter/book. Complete scene text is therefore already available for a future inspector without re-running AI or reparsing the raw document.
|
||||||
|
|
||||||
|
`ManuscriptStructuralChapterSources` also retains whole chapter text, a paragraph map JSON document, structural parse JSON, and narrator/POV context. Scenes and chapters retain `ManuscriptDocumentID` and external/link metadata. `ManuscriptDocuments` provides the document identity/binding record.
|
||||||
|
|
||||||
|
Precision limits are important:
|
||||||
|
|
||||||
|
- scene and chapter paragraph ranges are retained;
|
||||||
|
- full scene text is retained;
|
||||||
|
- candidate evidence contains free-text excerpts/reasoning;
|
||||||
|
- there is no normalized passage entity or durable character/paragraph offset tying a particular candidate event evidence string to an exact source span;
|
||||||
|
- edits in Word can make imported numeric paragraph indices stale, while the Word content-control markers are intended to remain the live anchors.
|
||||||
|
|
||||||
|
Consequently a future workspace can already show summary, complete imported scene text, and stored AI evidence. It can associate all of them with the same scene/contribution. Exact highlighted passages in the imported text would require evidence-to-source alignment or new persisted offsets; that capability does not presently exist.
|
||||||
|
|
||||||
|
## G. Word Companion integration
|
||||||
|
|
||||||
|
The Word Companion is a hosted Office add-in (`PlotDirector.WordCompanion`) backed by `WordCompanionController`, `WordCompanionService`, and SignalR presence/hub services.
|
||||||
|
|
||||||
|
Existing capabilities include:
|
||||||
|
|
||||||
|
- document identity and manuscript structure retrieval;
|
||||||
|
- hidden content controls/bookmarks tagged `PD-CHAPTER-{id}` and `PD-SCENE-{id}`;
|
||||||
|
- paragraph-range scanning to resolve the current scene;
|
||||||
|
- scene/manuscript sync and link updates;
|
||||||
|
- pushing Word’s current scene into PlotDirector and broadcasting `storyPositionChanged`;
|
||||||
|
- web pages following the current Word position;
|
||||||
|
- server-to-add-in requests to rescan the current position.
|
||||||
|
|
||||||
|
A future plot development can immediately link to the PlotDirector scene route and load the stored imported text by `SceneID`. The same `SceneID` is also the logical Word anchor.
|
||||||
|
|
||||||
|
What is not currently present is a reverse “open/select this scene in Word” command from an arbitrary web page. The existing hub connection, companion registration, and `PD-SCENE` markers make this extension feasible, but it requires a new command and add-in handler. Numeric paragraph positions alone should not be the preferred live navigation mechanism after document edits; tagged content controls are the stronger reusable anchor.
|
||||||
|
|
||||||
|
## H. Events and chronology
|
||||||
|
|
||||||
|
PlotDirector does not currently have a generic, independent story-world `Event` entity. “Plot events” are `ThreadEvents` attached to scenes. Other event-like domains—asset events, relationship events, character attribute events, custody/knowledge changes—are also scene-anchored.
|
||||||
|
|
||||||
|
Story chronology is primarily stored on `Scene`:
|
||||||
|
|
||||||
|
- `TimeModeID`;
|
||||||
|
- `StartDateTime` and `EndDateTime`;
|
||||||
|
- duration amount/unit;
|
||||||
|
- relative time text;
|
||||||
|
- time confidence.
|
||||||
|
|
||||||
|
Thus a plot development inherits chronology through its `SceneID`. This already supports the proposed two-axis interpretation:
|
||||||
|
|
||||||
|
- manuscript/narrative position from scene order;
|
||||||
|
- story-world time from the scene’s chronology.
|
||||||
|
|
||||||
|
The Story Calendar already sorts dated scenes by story date/time and separates unplaced scenes. Story Intelligence’s temporal resolver derives canonical scene chronology from temporal analysis/clues. Continuity validation and scene dependencies detect date/order, travel, knowledge, reveal/setup, action-consequence, relationship, object, location, and other consistency issues. Timeline warning infrastructure can be reused for selected contribution scenes.
|
||||||
|
|
||||||
|
Limitations:
|
||||||
|
|
||||||
|
- a `ThreadEvent` has no own date/time, so two distinct events within one scene cannot occupy different story-world moments;
|
||||||
|
- a plot event cannot exist independently of a scene;
|
||||||
|
- temporal clues may survive in analysis JSON, but the durable canonical result is scene chronology rather than a normalized event timeline;
|
||||||
|
- branch/merge targets describe plot structure, not chronology.
|
||||||
|
|
||||||
|
The dedicated Plot Lines workspace can initially anchor developments to scene chronology with no new event system. A generic independent Event model would only be justified by requirements that cannot be represented at scene granularity.
|
||||||
|
|
||||||
|
## I. Scenario reuse
|
||||||
|
|
||||||
|
Scenarios are a good fit and should be reused.
|
||||||
|
|
||||||
|
`Scenario_Create` snapshots the canonical `NarrativeSceneOrder` into `ScenarioSceneOrder`. Each row keeps the same `SceneID` while overlaying a proposed chapter and sort order. Moves update only the overlay. Canonical chapter/scene ordering changes only after explicit Apply to Main.
|
||||||
|
|
||||||
|
Because plot membership, characters, assets, location, manuscript text, and chronology are keyed to `SceneID`, all of them automatically follow a moved scenario scene. `Scenario_Timeline` already demonstrates this by returning thread, asset, character, location, time, and warning labels in proposed order.
|
||||||
|
|
||||||
|
Scenario validation currently checks:
|
||||||
|
|
||||||
|
- hard “Must Occur Before” scene dependencies;
|
||||||
|
- adjacent exact-date reversals;
|
||||||
|
- reveal/payoff before a setup event in the same thread;
|
||||||
|
- validating asset dependency order;
|
||||||
|
- large pacing/emotional metric jumps.
|
||||||
|
|
||||||
|
The plot-thread setup check is weaker than its label suggests: it searches for an event type containing “Setup,” while the canonical thread-event lookup does not currently include a type named Setup. It should not be relied upon without correction or mapping (for example, treating Introduced/Clue Planted/Question Raised as setup semantics).
|
||||||
|
|
||||||
|
Reuse considerations for a filtered Plot Lines workspace:
|
||||||
|
|
||||||
|
- the scenario must retain a full-book order even when the UI displays only selected plot scenes;
|
||||||
|
- moving a visible scene relative to another visible scene must define its position among hidden scenes deterministically;
|
||||||
|
- validation should run against the full scenario, not just the filtered subset;
|
||||||
|
- the existing Scenario page uses forms/up/down/chapter moves rather than the rich Timeline drag UI, so interaction code may need extension, but the storage model should not be duplicated.
|
||||||
|
|
||||||
|
## J. Multi-Plot-Line feasibility
|
||||||
|
|
||||||
|
### Shared scenes
|
||||||
|
|
||||||
|
Fully supported. Group canonical `ThreadEvents` by `SceneID` and select scenes associated with two or more selected `PlotLineID` values. A shared scene can show all contributing threads/events without ambiguity.
|
||||||
|
|
||||||
|
### Shared events
|
||||||
|
|
||||||
|
Partially supported. Different plot lines can have events in the same scene, which provides a useful scene-level intersection. A single canonical `ThreadEvent` belongs to one `PlotThread`, and therefore one source plot line. `PlotEventTargetPlotLines` supplies cross-line targets for branch/split/merge behavior, but it does not establish one shared event identity across lines.
|
||||||
|
|
||||||
|
### Sequential interaction
|
||||||
|
|
||||||
|
Supported as a query/read-model concern. Union the selected lines’ scenes, order by `NarrativeSceneOrder` or scenario order, and label each scene with all selected memberships. Adjacent contributions and dormant stretches can be computed without new persistence.
|
||||||
|
|
||||||
|
### Cause and effect
|
||||||
|
|
||||||
|
Partially supported:
|
||||||
|
|
||||||
|
- `SceneDependencies` explicitly model source/target scene relationships including Reveal Setup, Action Consequence, Relationship, Knowledge, Object, Location, Travel, and Must Occur Before;
|
||||||
|
- plot branch/split/merge targets model structural relationships between lines;
|
||||||
|
- character knowledge and other continuity records can supply supporting causal context;
|
||||||
|
- Story Intelligence descriptions/evidence may state causal reasoning in free text.
|
||||||
|
|
||||||
|
There is no direct structured “contribution in line A causes contribution in line B” edge. Existing scene dependency edges should be surfaced first. A plot-specific causal edge should only be added if scene dependencies and plot targets prove semantically insufficient.
|
||||||
|
|
||||||
|
## K. Unattributed scenes
|
||||||
|
|
||||||
|
Canonical unattributed scenes are directly identifiable: active scenes for which no active `ThreadEvent → PlotThread → PlotLine` path exists. The count should be computed per project/book with the same archive/scope rules as canonical plot reads.
|
||||||
|
|
||||||
|
Three populations should be reported separately:
|
||||||
|
|
||||||
|
1. **canonically attributed** — at least one accepted thread event;
|
||||||
|
2. **proposed but not canonical** — no canonical event, but pending/rejected candidate events or candidate evidence exist;
|
||||||
|
3. **no known attribution** — neither canonical nor proposed evidence.
|
||||||
|
|
||||||
|
This distinction avoids labelling a review backlog or rejected suggestion as an AI miss.
|
||||||
|
|
||||||
|
Existing data that can explain an unattributed scene includes:
|
||||||
|
|
||||||
|
- scene purpose labels (including Character Development, Relationship Development, Setup, Exposition, Emotional Recovery, Comic Relief, Transition/Travel, Location Change, Time Passage, Consequence, and Reversal);
|
||||||
|
- purpose/outcome notes and scene/chapter summaries;
|
||||||
|
- POV, characters, relationships, assets, location, and character-state/knowledge data;
|
||||||
|
- scene dependencies and continuity warnings;
|
||||||
|
- metrics such as tension/emotional weight/action;
|
||||||
|
- Story Intelligence raw result, per-scene parsed narrative arcs, candidate evidence, and temporal clues;
|
||||||
|
- manuscript text itself.
|
||||||
|
|
||||||
|
This information can support editorial categories, but the system does not currently persist a definitive reason a scene is intentionally plot-unattributed. “Breathing scene,” “world building,” “aftermath,” or “missing plot association” would be inference unless explicitly authored or added as review state.
|
||||||
|
|
||||||
|
A later read-only development audit should report counts by book and the three populations above. It should not equate zero canonical events with an unnecessary scene.
|
||||||
|
|
||||||
|
## L. Timeline Plot Line removal
|
||||||
|
|
||||||
|
### Server-side components
|
||||||
|
|
||||||
|
- `ProjectTimelineSettings.ShowPlotLines` model, view model, service mapping, repository parameter, SQL column/default/save procedure, backup/restore, and Settings checkbox.
|
||||||
|
- `needsPlotTimelineData` in `TimelineService.GetAsync`.
|
||||||
|
- `TimelineData.PlotLines`, `TimelineData.ThreadEvents`, `TimelineViewModel.PlotLanes`, `PlotLineLaneViewModel`, and slot models, to the extent they are lane-only.
|
||||||
|
- `BuildPlotLanes` and lane enrichment.
|
||||||
|
- Timeline SQL result sets controlled by `@IncludePlotLines`.
|
||||||
|
|
||||||
|
Plot/thread filter and focus still use `ThreadEvents` and remain useful on a lean scene Timeline. Removing lanes must not accidentally stop loading the event data needed by those filters. A cleaner read path may load only membership IDs when lanes are gone.
|
||||||
|
|
||||||
|
### Razor and interactions
|
||||||
|
|
||||||
|
- plot lane board, labels, scene slots, event markers/tooltips, and SVG overlay in `Views/Timeline/Index.cshtml`;
|
||||||
|
- “Plot lines” View toggle;
|
||||||
|
- plot-line items in “Jump to lane item”;
|
||||||
|
- lane-specific event links/focus styling;
|
||||||
|
- the Plot Lines list’s Timeline “Focus” link remains valid if plot focus remains a scene filter; its wording may need to change.
|
||||||
|
|
||||||
|
No plot lane drag/drop was found. Plot event editing is handled elsewhere, so lane removal does not remove canonical authoring.
|
||||||
|
|
||||||
|
### JavaScript/state
|
||||||
|
|
||||||
|
- `plotline.timeline.visibility` key’s `plot-lines` member and hide class;
|
||||||
|
- plot SVG sizing, marker coordinates, path drawing, branch/split/merge connectors, layout observers, and resize/redraw handling;
|
||||||
|
- client plot-health calculations: neglected stretches, dangling branch/merge targets, questionable resolution, and abandoned-line notices;
|
||||||
|
- preset `VisibilityJson` contains lane visibility. `LoadPreset` currently deserializes `FilterJson` but does not apply `VisibilityJson`, making saved visibility effectively dead on load already. Existing stored JSON can be tolerated during migration and later cleaned/ignored.
|
||||||
|
|
||||||
|
### CSS, tests, and documentation
|
||||||
|
|
||||||
|
- lane-board, plot lane/slot/marker/SVG/path/connector/tooltip/health styles in `site.css`;
|
||||||
|
- Timeline browser coverage and the regression harness should gain assertions that lanes and retired controls are absent while plot filtering/focus still works;
|
||||||
|
- update `Help/Articles/Timeline/PlotLines.md`, `PlotThreadLanes.md`, `Overview.md`, `FiltersAndFocus.md`, and visibility/settings help;
|
||||||
|
- update `Help/Articles/PlotLines/Fields/Visibility.md` and Plot Line list/editor wording because `IsVisibleOnTimeline` becomes obsolete;
|
||||||
|
- retain Plot Lines/Threads and Scene Inspector help, but redirect visualization guidance to the new workspace.
|
||||||
|
|
||||||
|
### Functionality that must be preserved elsewhere
|
||||||
|
|
||||||
|
- branch/split/merge visualization based on event targets;
|
||||||
|
- event marker role/tooltip information;
|
||||||
|
- dormant/neglected/dangling/resolution/abandoned plot-health signals;
|
||||||
|
- plot line/thread focus over scenes;
|
||||||
|
- fast navigation from plot structure to a scene.
|
||||||
|
|
||||||
|
The first three are the main sequencing dependency: move them to the dedicated workspace or Story Health before deleting their Timeline implementation.
|
||||||
|
|
||||||
|
## M. Timeline Character lane removal
|
||||||
|
|
||||||
|
### What the lanes display
|
||||||
|
|
||||||
|
`BuildCharacterLanes` loads `CharacterTimeline_GetByProject`, groups `SceneCharacters` by character and scene, ranks characters by importance/classification and appearance roles, and creates an empty-or-populated slot for every ordered scene. Markers/tooltips expose presence, role/POV, introduction/exit, location, entry/exit, emotional and physical state, outfit/appearance notes, knowledge notes, and warnings.
|
||||||
|
|
||||||
|
### Affected implementation
|
||||||
|
|
||||||
|
- `ProjectTimelineSettings.ShowCharacterAppearances` across model/view model/service/repository/SQL/defaults/backup/restore;
|
||||||
|
- `needsCharacterTimelineData` and `BuildCharacterLanes`/`CharacterLanePriority`;
|
||||||
|
- `CharacterLaneViewModel`/slot data and `TimelineViewModel.CharacterLanes`;
|
||||||
|
- character lane board and entity-jump options in the Timeline view;
|
||||||
|
- the `characters` local visibility member/hide class;
|
||||||
|
- lane-specific CSS and any layout-observer selectors;
|
||||||
|
- `Help/Articles/Timeline/CharacterAppearances.md`, Timeline Overview/settings/view help, and any lane references in character help;
|
||||||
|
- browser/regression assertions for character-lane rendering and setting behavior.
|
||||||
|
|
||||||
|
### What should remain
|
||||||
|
|
||||||
|
- `SceneCharacters` and every appearance field;
|
||||||
|
- character filter/focus on the scene Timeline;
|
||||||
|
- POV filter and POV labels;
|
||||||
|
- characters shown on scene cards/Scene Inspector;
|
||||||
|
- Character details, scene appearance history, knowledge, relationships, and dedicated character features;
|
||||||
|
- Timeline quick-add palette and dropping a character onto a scene. This workflow targets scene cards and is independent of character lanes;
|
||||||
|
- character-derived continuity warnings.
|
||||||
|
|
||||||
|
The rich lane tooltip is the only concentrated presentation of several appearance-state fields. Before removal, verify equivalent discoverability in Character details and the Scene Inspector; add navigation there if necessary. No other domain feature depends on the lane rows themselves.
|
||||||
|
|
||||||
|
## N. Lean Timeline after removal
|
||||||
|
|
||||||
|
The resulting Timeline can retain:
|
||||||
|
|
||||||
|
- book/chapter bands and ordered scene cards;
|
||||||
|
- scene summaries, purpose, POV, location, character/asset chips, warnings, and dependency counts;
|
||||||
|
- metric shape, if still useful;
|
||||||
|
- story-time labels and chronological indicators;
|
||||||
|
- scene selection and the Scene Inspector;
|
||||||
|
- scene reorder/drop behavior;
|
||||||
|
- asset lanes only if they materially communicate chronological custody/state; this report does not recommend their removal;
|
||||||
|
- scene filters/focus for plot line, plot thread, character, POV, asset, location, purpose, revision, and warnings;
|
||||||
|
- quick-add/drop workflows on scene cards;
|
||||||
|
- saved filter views.
|
||||||
|
|
||||||
|
Immediate simplification opportunities are:
|
||||||
|
|
||||||
|
- remove two high-volume grid sections and their View toggles;
|
||||||
|
- rename “Jump to lane item” or limit it to remaining lane/entity types;
|
||||||
|
- remove plot/character visibility keys from future presets/local state while accepting older JSON;
|
||||||
|
- simplify layout-height and SVG redraw observers;
|
||||||
|
- keep plot/character filters as abstractions over the scene sequence rather than confusing them with lane visibility;
|
||||||
|
- revisit `VisibilityJson`, because saved visibility is collected but not restored today;
|
||||||
|
- emphasize story chronology and temporal conflicts rather than narrative abstraction in Timeline copy/help.
|
||||||
|
|
||||||
|
## O. Gap analysis
|
||||||
|
|
||||||
|
### Already exists and reusable
|
||||||
|
|
||||||
|
- canonical plot line/thread/event hierarchy;
|
||||||
|
- many-to-many scene/plot membership through thread events;
|
||||||
|
- meaningful contribution-role vocabulary;
|
||||||
|
- plot line/thread importance and lifecycle metadata;
|
||||||
|
- branch/split/merge targets;
|
||||||
|
- canonical and scenario manuscript ordering;
|
||||||
|
- scene chronology and warning/dependency infrastructure;
|
||||||
|
- complete imported scene text;
|
||||||
|
- Story Intelligence candidate events, confidence, evidence, raw synthesis output, and provenance;
|
||||||
|
- Word scene markers and current-position bridge;
|
||||||
|
- plot/thread and character scene filtering/focus;
|
||||||
|
- scenario overlay, compare, validate, and apply flow.
|
||||||
|
|
||||||
|
### Exists but is not exposed
|
||||||
|
|
||||||
|
- imported event confidence and source/provenance in ordinary plot UI;
|
||||||
|
- candidate-event evidence and match reasoning after materialisation;
|
||||||
|
- full scene manuscript text in a plot contribution inspector;
|
||||||
|
- candidate plot significance/book status;
|
||||||
|
- cross-line branch/split/merge structure outside Timeline SVG;
|
||||||
|
- useful distinction between canonical and proposed-only attribution.
|
||||||
|
|
||||||
|
### Exists partially and needs extension
|
||||||
|
|
||||||
|
- contribution role: strong current vocabulary, but incomplete mapping to the proposed editorial terms;
|
||||||
|
- significance: available at line/thread/candidate levels, not contribution level;
|
||||||
|
- evidence: durable in review tables but not canonically attached/highlighted;
|
||||||
|
- shared event: shared scene and target edges exist, no common event identity;
|
||||||
|
- causality: scene dependencies exist, no plot-contribution edge;
|
||||||
|
- Word navigation: Word-to-web exists, web-to-specific-Word-scene does not;
|
||||||
|
- scenario plot view: storage/order/validation exist, filtered workspace interaction does not;
|
||||||
|
- scenario setup/payoff validation: intended but current lookup matching is ineffective/incomplete;
|
||||||
|
- saved Timeline visibility: persisted but not restored.
|
||||||
|
|
||||||
|
### Does not exist
|
||||||
|
|
||||||
|
- direct scene/plot-line membership row independent of an event (not currently required);
|
||||||
|
- canonical per-contribution significance/weight;
|
||||||
|
- canonical distinct evidence/explanation with exact manuscript offsets;
|
||||||
|
- independent story-world Event entity with its own chronology;
|
||||||
|
- direct PlotLine-to-character/relationship/asset/location associations;
|
||||||
|
- structured cross-plot causal edge at contribution level;
|
||||||
|
- persisted intentional reason for a scene having no plot line;
|
||||||
|
- dedicated compact single-line/multi-line Plot Lines workspace;
|
||||||
|
- reverse open/select-scene command for Word Companion.
|
||||||
|
|
||||||
|
### Legacy functionality that can be removed
|
||||||
|
|
||||||
|
- Timeline plot lane generation/rendering after its health/connector value is relocated;
|
||||||
|
- Timeline character lane generation/rendering;
|
||||||
|
- `ShowPlotLines` and `ShowCharacterAppearances` settings and View toggles;
|
||||||
|
- `IsVisibleOnTimeline` field/UI after compatibility/migration planning (not as part of the first presentation-only removal);
|
||||||
|
- plot/character lane visibility local-state members and preset members;
|
||||||
|
- lane-only jump options, SVG/layout code, CSS, tests, and help;
|
||||||
|
- stale help for the former Main Plot field/type behavior;
|
||||||
|
- potentially `VisibilityJson` as a saved-view feature if the remaining visibility system is intentionally retired, otherwise fix it for remaining sections.
|
||||||
|
|
||||||
|
## P. Recommended implementation phases
|
||||||
|
|
||||||
|
### Phase 0 — confirm data with a read-only audit
|
||||||
|
|
||||||
|
- Run a read-only development query on one completed imported book.
|
||||||
|
- Report canonical, proposed-only, and no-known-attribution scene counts.
|
||||||
|
- Sample candidate evidence, canonical event descriptions/confidence, and manuscript-source availability.
|
||||||
|
- Confirm archived rows and project/book scope rules.
|
||||||
|
- Do not alter review state or regenerate analysis.
|
||||||
|
|
||||||
|
### Phase 1 — define a contribution read model
|
||||||
|
|
||||||
|
- Build a query/service over `PlotLines → PlotThreads → ThreadEvents → Scenes → NarrativeSceneOrder`.
|
||||||
|
- Include all events for a scene/line, role, line/thread importance, confidence/provenance, chronology, other line memberships, and available candidate evidence.
|
||||||
|
- Keep derivations (for example inferred significance) explicitly labelled.
|
||||||
|
- Add no schema until real UI requirements demonstrate a missing durable fact.
|
||||||
|
|
||||||
|
### Phase 2 — deliver the dedicated read-only Plot Lines workspace
|
||||||
|
|
||||||
|
- Single-line mode: only contributing scenes, in manuscript order, with no empty cells.
|
||||||
|
- Weave mode: union selected lines, consolidate shared scenes, label memberships, and show adjacency/dormant spans.
|
||||||
|
- Inspector: summary, events/roles, chronology, other lines, characters/assets/location, stored manuscript text, evidence/confidence, and Open Scene.
|
||||||
|
- Reuse colours, filters, help, and existing canonical routes.
|
||||||
|
- Relocate branch/split/merge drawing and plot-health signals here or to Story Health.
|
||||||
|
|
||||||
|
### Phase 3 — Scenario integration
|
||||||
|
|
||||||
|
- Read the same contribution model against `ScenarioSceneOrder`.
|
||||||
|
- Keep the complete scenario order behind a selected-line projection.
|
||||||
|
- Reuse Scenario move, compare, validate, and apply operations.
|
||||||
|
- Correct/extend setup-payoff validation using actual event semantics.
|
||||||
|
- Make chronology/dependency warnings visible without creating a second scenario engine.
|
||||||
|
|
||||||
|
### Phase 4 — evidence and Word navigation
|
||||||
|
|
||||||
|
- Expose existing full scene text and candidate evidence first.
|
||||||
|
- Add web-to-Word scene selection using the companion connection and `PD-SCENE-{id}` controls.
|
||||||
|
- Only if exact highlighting is required, add a robust evidence-to-source alignment design; do not treat imported paragraph numbers as permanently stable Word anchors.
|
||||||
|
|
||||||
|
### Phase 5 — contribution semantics extension
|
||||||
|
|
||||||
|
- Validate the desired role vocabulary against current `ThreadEventType`/`PlotEventType` usage.
|
||||||
|
- Decide whether author-confirmed role/significance/evidence belongs on each `ThreadEvent` or on a distinct contribution record that groups multiple events for one scene/line.
|
||||||
|
- Preserve synthesis provenance and review decisions.
|
||||||
|
- If schema changes are approved, use a new forward-only, idempotent SQL migration and stored procedures; do not alter historical scripts.
|
||||||
|
|
||||||
|
### Phase 6 — remove Plot Line and Character lanes from Timeline
|
||||||
|
|
||||||
|
- First verify relocated plot health/structural views and character appearance discoverability.
|
||||||
|
- Remove lane rendering, view models/builders, lane-only SQL loads, JS/SVG/layout code, CSS, toggles, settings, and help.
|
||||||
|
- Retain scene filters/focus, character quick-add, scene cards/inspector, and canonical data.
|
||||||
|
- Accept old local/preset JSON during compatibility transition.
|
||||||
|
- Update Plot Line “Timeline visibility” UI/data in a separate compatibility-conscious step.
|
||||||
|
|
||||||
|
### Phase 7 — simplify and harden the lean Timeline
|
||||||
|
|
||||||
|
- Tune the remaining chapter/scene/chronology layout.
|
||||||
|
- Add regression/browser coverage for absence of removed lanes and continued operation of plot/character filters, scene inspection, quick-add, saved views, chronology, and warnings.
|
||||||
|
- Measure Timeline query/render cost to confirm lane data is no longer fetched unless a retained filter requires it.
|
||||||
|
|
||||||
|
This sequence delivers the highest-value presentation correction early, preserves the current canonical model, and postpones schema additions until the dedicated workspace proves exactly which semantics must be durable.
|
||||||
56
docs/subscription-entitlements.md
Normal file
56
docs/subscription-entitlements.md
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
# Subscription entitlements
|
||||||
|
|
||||||
|
PlotDirector calculates access at request time. It does not persist a second "effective plan" field.
|
||||||
|
|
||||||
|
## Plans and limits
|
||||||
|
|
||||||
|
`SubscriptionLevel` remains the authoritative plan catalogue. The existing levels are Draft Desk, Writing Room, Story Forge, and Author Studio. Their book, chapter, scene, character, storage, and collaborator limits are database data and must not be duplicated in controllers or views.
|
||||||
|
|
||||||
|
Active books in active projects owned by the user count toward `MaxBooks`. Archived books and archived projects do not. A downgrade never deletes or hides existing data; an account at or above its new limit may read its existing books but cannot create another.
|
||||||
|
|
||||||
|
## Effective access precedence
|
||||||
|
|
||||||
|
`SubscriptionService.GetEffectiveEntitlementAsync` is the application authority. Precedence is:
|
||||||
|
|
||||||
|
1. An active, non-revoked administrative override whose start has arrived and whose optional expiry has not arrived.
|
||||||
|
2. An active application-managed trial whose expiry is strictly later than the current UTC time.
|
||||||
|
3. An active paid subscription, including a cancellation that has not yet reached its paid-through period end.
|
||||||
|
4. Read-only access for an expired trial, ended subscription, or missing subscription.
|
||||||
|
|
||||||
|
The expiry boundary is exclusive: at the exact expiry instant, temporary access has ended. Expired overrides need no background job; they simply stop participating in evaluation and the underlying billing/trial state applies again.
|
||||||
|
|
||||||
|
Stripe state remains commercial state. `SubscriptionOverride` never updates Stripe identifiers, price IDs, status, or billing periods.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
All authenticated unsafe MVC/API requests pass through `SubscriptionEnforcementFilter`. Inactive accounts retain GET/read/export/account/billing access, while writes are redirected to subscription information or receive an API 403 problem response. Account management, billing, export, webhook, and authorised administration endpoints are intentionally exempt.
|
||||||
|
|
||||||
|
Resource creation also remains guarded at its service boundary. Normal MVC, onboarding, Word Companion, legacy JSON imports, and project-backup imports all use the same subscription service. Book creation obtains a short database reservation through `SubscriptionEntitlement_TryReserveBookSlots`; `sp_getapplock` serializes the final-slot decision per owner, so concurrent requests cannot both consume one remaining place. Reservations are released after the operation and expire defensively after 15 minutes.
|
||||||
|
|
||||||
|
Insert triggers on books, chapters, scenes, and characters are the final backstop for alternate and future bulk paths. They evaluate the same underlying subscription/override precedence and reject creation above the configured plan limit without affecting updates, reads, archives, or existing over-limit data. Bulk imports and Word Companion sync also perform projected-limit checks first so users receive a useful message rather than a database error.
|
||||||
|
|
||||||
|
Story Intelligence queue and worker execution both call the central feature decision. This prevents already-queued paid AI work from running after access expires. Export remains available because no existing plan defines it as restricted and authors must be able to retrieve their work.
|
||||||
|
|
||||||
|
When adding a future plan-specific feature, add its decision to `SubscriptionFeature` and `SubscriptionService`; do not inspect subscription rows or plan names in a controller.
|
||||||
|
|
||||||
|
## Trials
|
||||||
|
|
||||||
|
New registration rows are explicit Draft Desk trials with `IsTrial = 1` and `TrialExpiryDateUTC = StartDateUTC + 30 days`. Historical Draft Desk/no-Stripe rows are materialized the same way by migration 201. Missing legacy expiry remains defensively interpreted as start plus 30 days in the evaluator.
|
||||||
|
|
||||||
|
Expired trials can authenticate, read existing projects and books, export, manage their account, and reach pricing. They cannot edit, import, create resources, or queue/execute Story Intelligence.
|
||||||
|
|
||||||
|
## Administration and audit
|
||||||
|
|
||||||
|
Subscription administration is under `/admin/subscriptions` and the existing `AdminOnly` policy. It shows underlying billing state separately from effective access and current book usage.
|
||||||
|
|
||||||
|
Administrators can:
|
||||||
|
|
||||||
|
- set an application-managed trial expiry;
|
||||||
|
- grant an existing level from a UTC start until an optional UTC expiry;
|
||||||
|
- revoke an override.
|
||||||
|
|
||||||
|
Every change requires a reason and writes previous/new state, affected user, administrator, action, and timestamp to `SubscriptionAdministrationAudit`. Internal reasons are not shown on user-facing subscription pages.
|
||||||
|
|
||||||
|
## Schema
|
||||||
|
|
||||||
|
Migration `PlotLine/Sql/201_SubscriptionEntitlementEnforcement.sql` adds `SubscriptionOverride`, `SubscriptionAdministrationAudit`, `SubscriptionBookSlotReservation`, their stored procedures and insert guards, explicit trial creation, and the safe historical trial-expiry materialization.
|
||||||
Loading…
x
Reference in New Issue
Block a user