From 5d2e080539c10c3a2c6aed5c18c169abc8a55e77 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 2 Nov 2026 16:51:32 +0000 Subject: [PATCH] Commit completed calendar navigation and subscription override updates --- .../Browser/calendar-installed-pwa.cjs | 29 +++++ PlotLine.Tests/Browser/calendar-ribbon.cjs | 55 +++++++++ PlotLine.Tests/CalendarNavigationTests.cs | 39 ++++++ PlotLine.Tests/Program.cs | 6 +- .../SubscriptionEntitlementTests.cs | 115 +++++++++++++++++- PlotLine.Tests/ToolbarBrowserHost.cs | 7 ++ PlotLine/Controllers/AdminController.cs | 23 ---- .../Controllers/ManageAccountController.cs | 4 +- PlotLine/Controllers/PricingController.cs | 7 +- PlotLine/Data/SubscriptionRepository.cs | 9 -- PlotLine/Services/CoreServices.cs | 49 +++----- PlotLine/ViewModels/AuthViewModels.cs | 67 +++++++--- PlotLine/Views/Admin/Subscriptions.cshtml | 25 ++-- PlotLine/Views/ManageAccount/Index.cshtml | 43 ++++--- .../Views/ManageAccount/Subscription.cshtml | 60 +++++---- PlotLine/Views/Pricing/Index.cshtml | 2 +- PlotLine/Views/Projects/Index.cshtml | 22 ++-- .../_StoryCalendarSurface.cshtml | 11 +- PlotLine/wwwroot/css/application-shell.css | 19 +++ .../wwwroot/js/application-page-context.js | 2 +- PlotLine/wwwroot/js/story-calendar.js | 2 +- docs/subscription-entitlements.md | 15 ++- 22 files changed, 438 insertions(+), 173 deletions(-) create mode 100644 PlotLine.Tests/Browser/calendar-installed-pwa.cjs create mode 100644 PlotLine.Tests/Browser/calendar-ribbon.cjs create mode 100644 PlotLine.Tests/CalendarNavigationTests.cs diff --git a/PlotLine.Tests/Browser/calendar-installed-pwa.cjs b/PlotLine.Tests/Browser/calendar-installed-pwa.cjs new file mode 100644 index 00000000..f57cb14e --- /dev/null +++ b/PlotLine.Tests/Browser/calendar-installed-pwa.cjs @@ -0,0 +1,29 @@ +const {chromium}=require('playwright'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +(async()=>{ + const profile=fs.mkdtempSync(path.join(os.tmpdir(),'pd-calendar-installed-')); + const context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}); + const cdp=await context.browser().newBrowserCDPSession(); + const base='http://127.0.0.1:5238',manifestId=base+'/Projects'; + try{ + await context.pages()[0].goto(base+'/fixture?page=calendar-test'); + await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'}); + await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'}); + const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture?page=calendar-test'}); + const app=await opened;await app.waitForLoadState(); + assert(await app.evaluate(()=>matchMedia('(display-mode: standalone)').matches)); + for(const width of [1440,390]){ + await app.setViewportSize({width,height:1000});await app.waitForTimeout(300); + assert(await app.locator('.story-calendar-filter').isHidden()); + const group=app.locator('.pd-context-group[aria-label="Calendar"]'); + const menu=group.locator(':scope > details'); + if(width===390) assert.equal(await menu.getAttribute('data-compact'),'true'); + if(!await menu.evaluate(e=>e.open))await menu.locator(':scope > summary').click(); + await group.getByLabel('Month',{exact:true}).selectOption('1983-05'); + await app.waitForFunction(()=>document.querySelector('#month').value==='1983-05'); + console.log('PASS installed PWA '+width+'x1000: standalone, ribbon, responsive collapse, month change'); + await app.screenshot({path:`/tmp/calendar-installed-${width}.png`,fullPage:true}); + } + }finally{await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true});} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/Browser/calendar-ribbon.cjs b/PlotLine.Tests/Browser/calendar-ribbon.cjs new file mode 100644 index 00000000..db6375d7 --- /dev/null +++ b/PlotLine.Tests/Browser/calendar-ribbon.cjs @@ -0,0 +1,55 @@ +const {chromium}=require('playwright'); +const assert=require('node:assert/strict'); +(async()=>{ + const browser=await chromium.launch(); + try { + for(const width of [1440,390]) for(const pwa of [false,true]) { + const context=await browser.newContext({viewport:{width,height:1000}}); + if(pwa) await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); + const page=await context.newPage(); const errors=[];page.on('pageerror',e=>errors.push(e.message)); + await page.goto('http://127.0.0.1:5238/fixture?page=calendar-test'); + await page.waitForFunction(()=>!!window.PlotDirectorPageContext); + const filter=page.locator('.story-calendar-filter'); + await page.waitForTimeout(300); + assert.equal(await filter.isVisible(),!pwa,'in-page panel visibility'); + async function controls(){ + await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))); + if(!pwa) return filter; + const group=page.locator('.pd-context-group[aria-label="Calendar"]'); + const details=group.locator(':scope > details'); + if(await details.getAttribute('data-compact')==='true' && !await details.evaluate(e=>e.open)) await details.locator(':scope > summary').click(); + return group; + } + let scope=await controls(); + if(pwa && width===390) { + assert.equal(await scope.locator(':scope > details').getAttribute('data-compact'),'true','narrow Calendar uses shared collapse'); + assert(await scope.locator('form').evaluate(e=>e.getBoundingClientRect().left>=0 && e.getBoundingClientRect().right<=innerWidth),'controls fit viewport'); + } + const month=()=>pwa ? scope.getByLabel('Month',{exact:true}) : scope.locator('#month'); + assert.deepEqual(await month().locator('option').evaluateAll(os=>os.map(o=>o.value)),['1983-03','1983-05','1983-09']); + const top=await page.locator('.story-calendar-month').evaluate(e=>e.getBoundingClientRect().top); + await page.getByRole('link',{name:'Next month',exact:true}).click(); + await page.waitForFunction(()=>document.querySelector('#month').value==='1983-04'); + scope=await controls(); assert.equal(await month().inputValue(),'1983-04'); + assert(await page.locator('.story-calendar-month-title').textContent().then(t=>t.includes('April 1983'))); + await page.getByRole('link',{name:'Next story month',exact:true}).click(); + await page.waitForFunction(()=>document.querySelector('#month').value==='1983-05'); + scope=await controls();assert.equal(await month().inputValue(),'1983-05'); + assert.equal(await month().locator('option[value="1983-04"]').count(),0,'temporary empty month removed'); + await (pwa ? scope.getByLabel('Book',{exact:true}) : scope.locator('#bookId')).selectOption('13'); + await page.waitForFunction(()=>document.querySelector('#bookId').value==='13' && document.querySelector('#month option[value="1983-03"]')===null); + scope=await controls(); assert.equal(await month().inputValue(),'1983-05','current empty month retained after book change'); + assert.deepEqual(await month().locator('option').evaluateAll(os=>os.map(o=>o.value)),['1983-05','1983-09']); + await month().selectOption('1983-09'); + await page.waitForFunction(()=>document.querySelector('.story-calendar-month-title').textContent.includes('September 1983')); + scope=await controls();assert.equal(await page.getByRole('button',{name:'Apply',exact:true,includeHidden:true}).count(),0,'no redundant Apply button in page or ribbon'); + await page.waitForFunction(()=>!document.querySelector('[data-story-calendar-root]').hasAttribute('aria-busy')); + assert.equal(await page.locator('#month').inputValue(),'1983-09'); + assert.equal(await filter.isVisible(),!pwa); + assert.equal(errors.length,0,errors.join('\n')); + console.log(JSON.stringify({width,pwa,gridTop:Math.round(top),panelHeight:await filter.evaluate(e=>e.getBoundingClientRect().height)})); + await page.screenshot({path:`/tmp/calendar-${width}-${pwa?'pwa':'web'}.png`,fullPage:true}); + await context.close(); + } + } finally {await browser.close();} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/CalendarNavigationTests.cs b/PlotLine.Tests/CalendarNavigationTests.cs new file mode 100644 index 00000000..118e97df --- /dev/null +++ b/PlotLine.Tests/CalendarNavigationTests.cs @@ -0,0 +1,39 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; + +internal static class CalendarNavigationTests +{ + public static TimelineData Data() => new() + { + Project = new() { ProjectID = 7, ProjectName = "Calendar fixture" }, + Books = [new() { BookID = 12, ProjectID = 7, BookTitle = "A long book title for checking ribbon width", BookNumber = 1 }, new() { BookID = 13, ProjectID = 7, BookTitle = "Second book", BookNumber = 2 }], + Chapters = [new() { ChapterID = 21, BookID = 12 }, new() { ChapterID = 22, BookID = 13 }], + Scenes = [new() { SceneID = 1, ChapterID = 21, BookID = 12, SceneTitle = "March", StartDateTime = new(1983, 3, 5) }, + new() { SceneID = 2, ChapterID = 21, BookID = 12, SceneTitle = "May", StartDateTime = new(1983, 5, 7) }, + new() { SceneID = 3, ChapterID = 22, BookID = 13, SceneTitle = "September", StartDateTime = new(1983, 9, 8) }], + ThreadEvents = [new() { ThreadEventID = 1, SceneID = 3, EventTitle = "Scene anchored event", CreatedDate = new(2026, 11, 2) }] + }; + + public static void Run() + { + var service = new StoryCalendarService(new FakeTimelineRepository(Data())); + var march = service.GetAsync(7, null, null, null).GetAwaiter().GetResult()!; + Check(march.MonthOptions.Select(o => o.Value).SequenceEqual(new[] { "1983-03", "1983-05", "1983-09" }), "Only populated months across books"); + Check(march.NextMonth == new DateOnly(1983, 4, 1) && march.NextStoryMonth == new DateOnly(1983, 5, 1), "Chronological and story navigation differ"); + var april = service.GetAsync(7, null, march.NextMonth, null).GetAwaiter().GetResult()!; + Check(april.MonthOptions.Single(o => o.Selected).Value == "1983-04", "Empty current month selected"); + Check(april.Weeks.SelectMany(w => w.Days).All(d => d.Scenes.Count == 0), "Empty month renders normally"); + Check(april.PreviousMonth == march.SelectedMonth && april.NextStoryMonth == march.NextStoryMonth, "Empty month navigation"); + var firstBook = service.GetAsync(7, 12, null, null).GetAwaiter().GetResult()!; + Check(firstBook.MonthOptions.Select(o => o.Value).SequenceEqual(new[] { "1983-03", "1983-05" }), "Book scope excludes other book's event and scene month"); + var secondBook = service.GetAsync(7, 13, null, null).GetAwaiter().GetResult()!; + Check(secondBook.MonthOptions.Single().Value == "1983-09", "Event owning scene supplies canonical month, not audit date"); + Check(typeof(ThreadEvent).GetProperty("StartDateTime") is null, "Current events have no independent story date"); + } + + private static void Check(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 44ce63a4..9ac3de07 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -105,6 +105,7 @@ var tests = new (string Name, Action Test)[] ("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation), ("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata), ("Subscription entitlement evaluates trials, paid access, overrides and real plan limits", SubscriptionEntitlementTests.EffectiveStateAndLimits), + ("Subscription overrides control access and dashboard presentation without trial contradictions", SubscriptionEntitlementTests.OverridePrecedenceAndPresentation), ("Subscription enforcement is concurrent, audited and admin-authorised", SubscriptionEntitlementTests.EnforcementAndAdminSecurity), ("Plot Health stays scene-based with 12,000 contributions", PlotHealthTests.GeneratedScale), ("Plot Health preserves Discovery planning and boundary contradictions", PlotHealthTests.DiscoveryContradictions), @@ -245,6 +246,7 @@ var tests = new (string Name, Action Test)[] ("Story Intelligence temporal importer preserves manual chronology", StoryIntelligenceTemporalImporterPreservesManualChronology), ("Story Intelligence temporal materialisation saves canonical chronology", StoryIntelligenceTemporalMaterialisationSavesCanonicalChronology), ("Story Intelligence temporal malformed values are discarded", StoryIntelligenceTemporalMalformedValuesAreDiscarded), + ("Story Calendar useful months and sparse navigation", CalendarNavigationTests.Run), ("Story Calendar places dated scenes on Monday-first month grid", StoryCalendarPlacesDatedScenesOnMondayFirstMonthGrid), ("Story Calendar separates unplaced scenes without guessing", StoryCalendarSeparatesUnplacedScenesWithoutGuessing), ("Story Calendar book filter and all books scope work", StoryCalendarBookFilterAndAllBooksScopeWork), @@ -3693,8 +3695,8 @@ static string RelationshipTypeFromEvidence(string signal, string? evidence, stri "RelationshipTypeFromEvidence", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); Assert(method is not null, "RelationshipTypeFromEvidence was not found."); - var classification = method!.Invoke(null, [signal, evidence, sceneContext, characterAName, characterBName]); - Assert(classification is not null, "RelationshipTypeFromEvidence returned null."); + var classification = method!.Invoke(null, [signal, evidence, sceneContext, characterAName, characterBName]) + ?? throw new InvalidOperationException("RelationshipTypeFromEvidence returned null."); return classification.GetType().GetProperty("Type")?.GetValue(classification) as string ?? string.Empty; } diff --git a/PlotLine.Tests/SubscriptionEntitlementTests.cs b/PlotLine.Tests/SubscriptionEntitlementTests.cs index d66421c3..27b612a1 100644 --- a/PlotLine.Tests/SubscriptionEntitlementTests.cs +++ b/PlotLine.Tests/SubscriptionEntitlementTests.cs @@ -4,6 +4,7 @@ using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; +using PlotLine.ViewModels; internal static class SubscriptionEntitlementTests { @@ -25,7 +26,7 @@ internal static class SubscriptionEntitlementTests { nameof(ISubscriptionRepository.GetCurrentSubscriptionAsync) => Task.FromResult(subscription), nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult(subscription), - nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(activeOverride), + nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)), nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult(levels[(int)args![0]!]), nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks), _ => DefaultTask(method) @@ -45,7 +46,7 @@ internal static class SubscriptionEntitlementTests 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."); + Check(extended.State == EntitlementState.ActiveTrial, "A genuine application trial with a later stored expiry must be active."); subscription.TrialExpiryDateUTC = null; subscription.StartDateUTC = now.AddDays(-31); @@ -122,6 +123,97 @@ internal static class SubscriptionEntitlementTests "A cancelled paid subscription at its period boundary must be read-only."); } + public static void OverridePrecedenceAndPresentation() + { + var now = new DateTime(2026, 11, 2, 12, 0, 0, DateTimeKind.Utc); + var underlying = Trial(now.AddDays(-10), now.AddDays(20)); + SubscriptionOverride? activeOverride = null; + var levels = new Dictionary + { + [1] = Level(1, "DraftDesk", "Draft Desk", 2, false), + [4] = Level(4, "AuthorStudio", "Author Studio", 999999, true) + }; + var repository = Proxy((method, args) => method switch + { + nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult(underlying), + nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)), + nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult(levels[(int)args![0]!]), + _ => DefaultTask(method) + }); + var service = new SubscriptionService(repository, Proxy((method, _) => DefaultTask(method))); + + var genuineTrial = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + var genuineBanner = TrialVisibilityViewModel.FromEntitlement(genuineTrial, now); + Check(genuineTrial.State == EntitlementState.ActiveTrial && genuineBanner is { IsAdministrativeOverride: false }, + "A genuine Draft Desk application trial must retain trial presentation when no override exists."); + Check(genuineBanner!.Description.Contains("30-day Draft Desk trial", StringComparison.Ordinal), + "Only a genuine application trial should use 30-day trial wording."); + + activeOverride = Override(1, now.AddDays(-1), now.AddDays(60), "Draft Desk"); + var draftTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + var draftTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(draftTemporary, now); + Check(draftTemporary.EffectiveLevel?.Name == "DraftDesk" && draftTemporaryBanner is { IsAdministrativeOverride: true }, + "A temporary Draft Desk override must be effective access, not an extension of the underlying trial."); + Check(!draftTemporaryBanner!.Description.Contains("trial", StringComparison.OrdinalIgnoreCase) + && !draftTemporaryBanner.Description.Contains("30-day", StringComparison.OrdinalIgnoreCase), + "A temporary Draft Desk override must not be described as a trial."); + + activeOverride = Override(1, now.AddDays(-1), null, "Draft Desk"); + var draftIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + Check(draftIndefinite.State == EntitlementState.ActiveOverride + && TrialVisibilityViewModel.FromEntitlement(draftIndefinite, now) is null, + "An indefinite Draft Desk override must not show an expiry banner."); + + activeOverride = Override(4, now.AddDays(-1), now.AddMonths(3), "Author Studio"); + var authorTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + var authorTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(authorTemporary, now); + Check(authorTemporary.EffectiveLevel?.Name == "AuthorStudio" + && authorTemporaryBanner?.StatusLabel.Contains("Author Studio access until", StringComparison.Ordinal) == true, + "A temporary Author Studio override must show its effective access expiry."); + + activeOverride = Override(4, now.AddDays(-1), null, "Author Studio"); + underlying.TrialExpiryDateUTC = now.AddDays(-1); + var authorIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + Check(authorIndefinite.State == EntitlementState.ActiveOverride && authorIndefinite.IsActive + && TrialVisibilityViewModel.FromEntitlement(authorIndefinite, now) is null, + "An expired underlying trial must not compete with an indefinite higher override."); + + underlying.TrialExpiryDateUTC = now.AddDays(20); + activeOverride = Override(4, now.AddDays(-10), now, "Author Studio"); + var expiredFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + Check(expiredFallback.State == EntitlementState.ActiveTrial && expiredFallback.EffectiveLevel?.Name == "DraftDesk", + "An expired override must automatically fall back to the underlying trial state."); + + activeOverride = null; + var removedFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + Check(removedFallback.State == EntitlementState.ActiveTrial && removedFallback.EffectiveLevel?.Name == "DraftDesk", + "A removed override must fall back to the underlying entitlement."); + + underlying = Paid(now, "active"); + activeOverride = Override(1, now.AddDays(-1), now.AddDays(30), "Draft Desk"); + var paidWithOverride = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult(); + Check(paidWithOverride.State == EntitlementState.ActiveOverride && paidWithOverride.EffectiveLevel?.Name == "DraftDesk" + && paidWithOverride.UnderlyingSubscription?.StripeStatus == "active", + "An administrative override must control effective access while preserving underlying paid billing state."); + + var root = FindRepositoryRoot(); + var projectService = File.ReadAllText(Path.Combine(root, "PlotLine", "Services", "CoreServices.cs")); + var projectView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Projects", "Index.cshtml")); + var adminView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Admin", "Subscriptions.cshtml")); + Check(projectService.Contains("FromEntitlement(entitlement", StringComparison.Ordinal) + && !projectService.Contains("TrialVisibilityViewModel.FromSubscription", StringComparison.Ordinal), + "The Projects dashboard must build its banner from effective entitlement."); + Check(projectView.Contains("@trial.Description", StringComparison.Ordinal) + && !projectView.Contains("Your 30-day trial expires", StringComparison.Ordinal), + "The Projects dashboard must not hard-code contradictory trial wording."); + Check(!adminView.Contains("Change trial expiry", StringComparison.Ordinal) + && adminView.Contains("sole administrator control", StringComparison.Ordinal), + "The separate administrative trial-expiry control must be removed."); + Check(typeof(AdminController).GetMethod("ExtendTrial") is null + && typeof(ISubscriptionRepository).GetMethod("ExtendTrialAsync") is null, + "The removed trial-expiry panel must not leave a callable application endpoint or repository mutation path."); + } + public static void EnforcementAndAdminSecurity() { var sql = File.ReadAllText(Path.Combine(FindRepositoryRoot(), "PlotLine", "Sql", "201_SubscriptionEntitlementEnforcement.sql")); @@ -152,6 +244,25 @@ internal static class SubscriptionEntitlementTests MaxStorageMB = 5120, MaxCollaborators = 3 }; + private static SubscriptionOverride Override(int levelId, DateTime start, DateTime? expiry, string displayName) => new() + { + SubscriptionOverrideID = 9, + UserID = 7, + SubscriptionLevelID = levelId, + StartDateUTC = start, + ExpiryDateUTC = expiry, + Reason = "Complimentary access", + LevelDisplayName = displayName + }; + + private static SubscriptionOverride? ActiveAt(SubscriptionOverride? candidate, DateTime utcNow) + => candidate is not null + && candidate.RevokedDateUTC is null + && candidate.StartDateUTC <= utcNow + && (!candidate.ExpiryDateUTC.HasValue || candidate.ExpiryDateUTC.Value > utcNow) + ? candidate + : null; + private static SubscriptionLevel Level(int id, string name, string display, int maxBooks, bool stripe) => new() { SubscriptionLevelID = id, Name = name, DisplayName = display, MaxBooks = maxBooks, diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index d05f51c1..74db343a 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -88,6 +88,7 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ToolbarTestUser(int.Parse(services.GetRequiredService().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!))); builder.Services.AddAuthentication("ReviewFixture").AddCookie("ReviewFixture",options=>{options.Events.OnRedirectToLogin=c=>{c.Response.StatusCode=401;return Task.CompletedTask;};options.Events.OnRedirectToAccessDenied=c=>{c.Response.StatusCode=403;return Task.CompletedTask;};}); + builder.Services.AddSingleton(new StoryCalendarService(new FakeTimelineRepository(CalendarNavigationTests.Data()))); var app = builder.Build(); app.UseWritingSolverReviewBoundary(); app.Urls.Add("http://127.0.0.1:5238"); @@ -121,6 +122,8 @@ internal static class ToolbarBrowserHost }; var action = new ActionContext(context, new RouteData(), new ActionDescriptor()); var view = context.RequestServices.GetRequiredService().GetView(null, context.Request.Query["healthDetail"] == "true" ? "/Views/PlotLineWorkspace/_Health.cshtml" : "/Views/PlotLineWorkspace/_NarrativeMap.cshtml", false); + if (!view.Success || view.View is null) + throw new InvalidOperationException($"Fixture view could not be resolved: {string.Join(", ", view.SearchedLocations)}"); using var writer = new StringWriter(); var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; await view.View.RenderAsync(new ViewContext(action, view.View, viewData, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); @@ -213,6 +216,8 @@ internal static class ToolbarBrowserHost Days = Enumerable.Range(0, 7).Select(day => new StoryCalendarDayViewModel { Date = new DateOnly(2026, 9, 28).AddDays(week * 7 + day), IsInSelectedMonth = week * 7 + day >= 3 }).ToList() }).ToList() }; + if (context.Request.Query["page"] == "calendar-test") + calendar = (await context.RequestServices.GetRequiredService().GetAsync(7, null, null, null))!; if (context.Request.Query["marketing"] == "true") { calendar.DatedScenes = PublicWebsiteFixtures.CalendarScenes(); @@ -222,6 +227,8 @@ internal static class ToolbarBrowserHost calendar.LatestStoryDate = new DateOnly(2026, 10, 24); } var surface = dashboardPage || context.Request.Query["page"] == "relationships" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); + if (context.Request.Query["page"] == "calendar-test") + surface = "
" + surface + "
"; if (timelinePage) { surface = """ diff --git a/PlotLine/Controllers/AdminController.cs b/PlotLine/Controllers/AdminController.cs index 4eb21992..6903b15a 100644 --- a/PlotLine/Controllers/AdminController.cs +++ b/PlotLine/Controllers/AdminController.cs @@ -74,29 +74,6 @@ public sealed class AdminController( return View(model); } - [HttpPost("subscriptions/trial")] - [ValidateAntiForgeryToken] - public async Task ExtendTrial(AdminTrialExtensionForm form) - { - if (!ModelState.IsValid || currentUser.UserId is not int administratorUserId) - { - TempData["AdminError"] = "Enter a valid trial expiry date and reason."; - return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); - } - - try - { - await subscriptionRepository.ExtendTrialAsync(form.UserID, DateTime.SpecifyKind(form.TrialExpiryDateUTC, DateTimeKind.Utc), administratorUserId, form.Reason); - TempData["AdminMessage"] = "Trial expiry updated. The change was recorded in the subscription audit log."; - } - catch (Exception ex) - { - logger.LogWarning(ex, "Administrator {AdministratorUserID} could not extend trial for user {UserID}.", administratorUserId, form.UserID); - TempData["AdminError"] = ex.Message; - } - return RedirectToAction(nameof(Subscriptions), new { userId = form.UserID }); - } - [HttpPost("subscriptions/override")] [ValidateAntiForgeryToken] public async Task SaveSubscriptionOverride(AdminSubscriptionOverrideForm form) diff --git a/PlotLine/Controllers/ManageAccountController.cs b/PlotLine/Controllers/ManageAccountController.cs index 12c00b31..9450b041 100644 --- a/PlotLine/Controllers/ManageAccountController.cs +++ b/PlotLine/Controllers/ManageAccountController.cs @@ -36,7 +36,7 @@ public sealed class ManageAccountController( { User = user, Subscription = subscription, - Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow), + Trial = TrialVisibilityViewModel.FromEntitlement(entitlement, DateTime.UtcNow), HasPaidBillingRisk = await subscriptions.HasPaidBillingRiskAsync(user.UserID), Entitlement = entitlement }); @@ -109,7 +109,7 @@ public sealed class ManageAccountController( { User = user, CurrentSubscription = subscription, - Trial = TrialVisibilityViewModel.FromSubscription(subscription, DateTime.UtcNow), + Trial = TrialVisibilityViewModel.FromEntitlement(entitlement, DateTime.UtcNow), Usage = subscription is null ? null : await subscriptions.GetUsageSummaryAsync(user.UserID), AvailableLevels = await subscriptions.GetActiveSubscriptionLevelsAsync(), Entitlement = entitlement diff --git a/PlotLine/Controllers/PricingController.cs b/PlotLine/Controllers/PricingController.cs index 5db2b389..c5d36344 100644 --- a/PlotLine/Controllers/PricingController.cs +++ b/PlotLine/Controllers/PricingController.cs @@ -59,16 +59,17 @@ public sealed class PricingController( ] }); - UserSubscriptionDetail? currentSubscription = null; + EffectiveEntitlement? entitlement = null; if (currentUser.UserId is int userId) { - currentSubscription = await subscriptions.GetCurrentSubscriptionAsync(userId); + entitlement = await subscriptions.GetEffectiveEntitlementAsync(userId); } return View(new PricingViewModel { Plans = await subscriptions.GetActiveSubscriptionLevelsAsync(), - CurrentSubscriptionLevelID = currentSubscription?.SubscriptionLevelID, + CurrentSubscriptionLevelID = entitlement?.EffectiveLevel?.SubscriptionLevelID, + UsesAdministrativeOverride = entitlement?.UsesAdministrativeOverride == true, IsSignedIn = currentUser.UserId.HasValue }); } diff --git a/PlotLine/Data/SubscriptionRepository.cs b/PlotLine/Data/SubscriptionRepository.cs index 1f1f23df..85166302 100644 --- a/PlotLine/Data/SubscriptionRepository.cs +++ b/PlotLine/Data/SubscriptionRepository.cs @@ -28,7 +28,6 @@ public interface ISubscriptionRepository Task TryReserveBookSlotsAsync(int userId, int requestedSlots, DateTime utcNow); Task ReleaseBookSlotReservationAsync(Guid reservationId); Task> SearchUsersAsync(string? search, int maximumRows = 50); - Task ExtendTrialAsync(int userId, DateTime trialExpiryDateUtc, int administratorUserId, string reason); Task SaveOverrideAsync(int userId, int subscriptionLevelId, DateTime startDateUtc, DateTime? expiryDateUtc, string reason, int administratorUserId); Task RevokeOverrideAsync(int userId, int administratorUserId, string reason); } @@ -234,14 +233,6 @@ public sealed class SubscriptionRepository(ISqlConnectionFactory connectionFacto 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(); diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 482560ec..3f7e0229 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -388,7 +388,7 @@ public sealed class StoryCalendarService(ITimelineRepository timelineRepository) NextStoryMonth = selectedMonth.HasValue ? AdjacentStoryMonth(datedScenes, selectedMonth.Value, previous: false) : null, FirstStoryMonth = earliestDate.HasValue ? FirstOfMonth(earliestDate.Value) : null, BookOptions = BuildBookOptions(timeline.Books, bookId), - MonthOptions = BuildMonthOptions(earliestDate, latestDate, selectedMonth), + MonthOptions = BuildMonthOptions(datedScenes, selectedMonth), Weeks = weeks, DatedScenes = datedScenes, UnplacedScenes = unplacedScenes, @@ -505,47 +505,31 @@ public sealed class StoryCalendarService(ITimelineRepository timelineRepository) return items; } - private static IReadOnlyList BuildMonthOptions(DateOnly? earliest, DateOnly? latest, DateOnly? selectedMonth) + private static IReadOnlyList BuildMonthOptions( + IReadOnlyList datedScenes, DateOnly? selectedMonth) { - if (!earliest.HasValue || !latest.HasValue) + // Thread/plot events inherit their story date from their owning scene; their + // CreatedDate/UpdatedDate are audit timestamps, never calendar dates. + var months = StoryMonths(datedScenes).ToHashSet(); + if (selectedMonth.HasValue) { - return []; + months.Add(FirstOfMonth(selectedMonth.Value)); } - var options = new List(); - var firstMonth = FirstOfMonth(earliest.Value); - var lastMonth = FirstOfMonth(latest.Value); - var normalizedSelectedMonth = selectedMonth.HasValue ? FirstOfMonth(selectedMonth.Value) : (DateOnly?)null; - - if (normalizedSelectedMonth.HasValue && normalizedSelectedMonth.Value < firstMonth) - { - options.Add(BuildMonthOption(normalizedSelectedMonth.Value, selected: true)); - } - - for (var month = firstMonth; month <= lastMonth; month = month.AddMonths(1)) - { - options.Add(BuildMonthOption(month, normalizedSelectedMonth == month)); - } - - if (normalizedSelectedMonth.HasValue && normalizedSelectedMonth.Value > lastMonth) - { - options.Add(BuildMonthOption(normalizedSelectedMonth.Value, selected: true)); - } - - return options; + return months.OrderBy(month => month) + .Select(month => BuildMonthOption(month, selectedMonth == month)).ToList(); } + private static IEnumerable StoryMonths(IReadOnlyList datedScenes) + => datedScenes.Where(scene => scene.StoryDate.HasValue) + .Select(scene => FirstOfMonth(scene.StoryDate!.Value)).Distinct().OrderBy(date => date); + private static SelectListItem BuildMonthOption(DateOnly month, bool selected) => new(month.ToString("MMMM yyyy", UkCulture), month.ToString("yyyy-MM", CultureInfo.InvariantCulture), selected); private static DateOnly? AdjacentStoryMonth(IReadOnlyList datedScenes, DateOnly selectedMonth, bool previous) { - var months = datedScenes - .Where(scene => scene.StoryDate.HasValue) - .Select(scene => FirstOfMonth(scene.StoryDate!.Value)) - .Distinct() - .OrderBy(date => date) - .ToList(); + var months = StoryMonths(datedScenes); var adjacent = previous ? months.Where(date => date < selectedMonth).Cast().LastOrDefault() : months.Where(date => date > selectedMonth).Cast().FirstOrDefault(); @@ -719,11 +703,12 @@ public sealed class ProjectService( .GroupBy(book => book.ProjectID) .ToDictionary(group => group.Key, group => group.ToList()); + var entitlement = await subscriptions.GetEffectiveEntitlementAsync(currentUser.UserId.Value); return new ProjectIndexViewModel { ActiveProjects = activeProjects.Select(project => ToIndexCard(project, booksByProject)).ToList(), ArchivedProjects = archivedProjects.Select(project => ToIndexCard(project, booksByProject)).ToList(), - Trial = TrialVisibilityViewModel.FromSubscription(await subscriptions.GetCurrentSubscriptionAsync(currentUser.UserId.Value), DateTime.UtcNow), + Trial = TrialVisibilityViewModel.FromEntitlement(entitlement, DateTime.UtcNow), OnboardingNudge = await onboarding.GetDashboardNudgeAsync(), StoryIntelligence = await storyIntelligence.GetDashboardAsync() }; diff --git a/PlotLine/ViewModels/AuthViewModels.cs b/PlotLine/ViewModels/AuthViewModels.cs index c93bf05a..4c4dd77d 100644 --- a/PlotLine/ViewModels/AuthViewModels.cs +++ b/PlotLine/ViewModels/AuthViewModels.cs @@ -34,10 +34,22 @@ public sealed class TrialVisibilityViewModel public int ProgressPercentage { get; init; } public bool IsExpired { get; init; } public int? WarningThresholdDays { get; init; } + public bool IsAdministrativeOverride { get; init; } + public bool ShowProgress { get; init; } - public string StatusLabel => IsExpired - ? "Trial expired" - : DaysRemaining == 1 ? "1 day remaining" : $"{DaysRemaining} days remaining"; + public string Eyebrow => IsAdministrativeOverride ? "Current access" : "Free trial status"; + + public string StatusLabel => IsAdministrativeOverride + ? $"{PlanName} access until {ExpiryDateUtc:d MMMM yyyy}" + : IsExpired + ? "Trial expired" + : DaysRemaining == 1 ? "1 day remaining" : $"{DaysRemaining} days remaining"; + + public string Description => IsAdministrativeOverride + ? $"Your {PlanName} access is available until {ExpiryDateUtc:d MMMM yyyy}." + : IsExpired + ? $"Your {PlanName} trial ended on {ExpiryDateUtc:d MMMM yyyy}. Your existing work remains available to read and export." + : $"Your 30-day {PlanName} trial expires on {ExpiryDateUtc:d MMMM yyyy}."; public string WarningCssClass => WarningThresholdDays switch { @@ -48,9 +60,27 @@ public sealed class TrialVisibilityViewModel _ => "trial-status--steady" }; - public static TrialVisibilityViewModel? FromSubscription(UserSubscriptionDetail? subscription, DateTime utcNow) + public static TrialVisibilityViewModel? FromEntitlement(EffectiveEntitlement? entitlement, DateTime utcNow) { - if (subscription is null) + if (entitlement is null) + { + return null; + } + + if (entitlement.State == EntitlementState.ActiveOverride) + { + var activeOverride = entitlement.ActiveOverride; + var level = entitlement.EffectiveLevel; + if (activeOverride?.ExpiryDateUTC is not DateTime overrideExpiry || level is null) + { + return null; + } + + return Build(level.DisplayName, activeOverride.StartDateUTC, overrideExpiry, utcNow, isAdministrativeOverride: true); + } + + var subscription = entitlement.UnderlyingSubscription; + if (subscription is null || entitlement.State is not (EntitlementState.ActiveTrial or EntitlementState.ExpiredTrial)) { return null; } @@ -62,8 +92,16 @@ public sealed class TrialVisibilityViewModel return null; } - var start = subscription.StartDateUTC; - var expiry = subscription.TrialExpiryDateUTC ?? start.AddDays(TrialDurationDays); + return Build( + entitlement.EffectiveLevel?.DisplayName ?? subscription.DisplayName, + entitlement.TrialStartDateUTC ?? subscription.StartDateUTC, + entitlement.TrialExpiryDateUTC ?? subscription.StartDateUTC.AddDays(TrialDurationDays), + utcNow, + isAdministrativeOverride: false); + } + + private static TrialVisibilityViewModel Build(string planName, DateTime start, DateTime expiry, DateTime utcNow, bool isAdministrativeOverride) + { var totalDays = Math.Max(1, (int)Math.Ceiling((expiry - start).TotalDays)); var rawRemaining = (int)Math.Ceiling((expiry - utcNow).TotalDays); var daysRemaining = Math.Max(0, rawRemaining); @@ -72,13 +110,15 @@ public sealed class TrialVisibilityViewModel return new TrialVisibilityViewModel { - PlanName = subscription.DisplayName, + PlanName = planName, StartDateUtc = start, ExpiryDateUtc = expiry, DaysRemaining = daysRemaining, DaysElapsed = daysElapsed, ProgressPercentage = progress, IsExpired = utcNow >= expiry, + IsAdministrativeOverride = isAdministrativeOverride, + ShowProgress = !isAdministrativeOverride, WarningThresholdDays = daysRemaining <= 1 ? 1 : daysRemaining <= 3 ? 3 : daysRemaining <= 7 ? 7 @@ -93,6 +133,7 @@ public sealed class PricingViewModel public IReadOnlyList Plans { get; set; } = []; public int? CurrentSubscriptionLevelID { get; set; } public bool IsSignedIn { get; set; } + public bool UsesAdministrativeOverride { get; set; } } public sealed class AdminSubscriptionsViewModel @@ -105,16 +146,6 @@ public sealed class AdminSubscriptionsViewModel public IReadOnlyList Levels { get; set; } = []; } -public sealed class AdminTrialExtensionForm -{ - [Range(1, int.MaxValue)] - public int UserID { get; set; } - [Required] - public DateTime TrialExpiryDateUTC { get; set; } - [Required, StringLength(1000)] - public string Reason { get; set; } = string.Empty; -} - public sealed class AdminSubscriptionOverrideForm { [Range(1, int.MaxValue)] diff --git a/PlotLine/Views/Admin/Subscriptions.cshtml b/PlotLine/Views/Admin/Subscriptions.cshtml index 111008c6..30e02e37 100644 --- a/PlotLine/Views/Admin/Subscriptions.cshtml +++ b/PlotLine/Views/Admin/Subscriptions.cshtml @@ -32,11 +32,12 @@

@Model.SelectedUser.Email

-

Paid / underlying plan

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

+

Underlying plan

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

Billing status

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

-

Effective access

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

-

Trial start

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

-

Trial expiry

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

+

Effective access

@(entitlement.EffectiveLevel?.DisplayName ?? "Read only") — @(entitlement.UsesAdministrativeOverride ? "Administrative override" : entitlement.State.ToString())

+

Underlying trial start

@(underlying?.IsTrial == true ? underlying.StartDateUTC.ToString("d MMMM yyyy 'UTC'") : "Not applicable")

+

Underlying trial expiry

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

+

Override expiry

@(entitlement.ActiveOverride is null ? "Not active" : entitlement.ActiveOverride.ExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "Never")

Books

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

@if (entitlement.ActiveOverride is not null) @@ -45,8 +46,16 @@
}
-
-

Change trial expiry

-

Administrative access override

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

-
+
+

Administrative access override

+

This is the sole administrator control for temporary or indefinite complimentary access. It does not change Stripe or the underlying application trial.

+
+ +
+
+
+
+
+
+
} diff --git a/PlotLine/Views/ManageAccount/Index.cshtml b/PlotLine/Views/ManageAccount/Index.cshtml index 427e5e53..8fcbdaa4 100644 --- a/PlotLine/Views/ManageAccount/Index.cshtml +++ b/PlotLine/Views/ManageAccount/Index.cshtml @@ -75,57 +75,60 @@
-

Free trial status

+

@trial.Eyebrow

@trial.StatusLabel

Upgrade
-

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

-
-
-
+

@trial.Description

+ @if (trial.ShowProgress) + { +
+
+
+ }
}
-

Current plan

+

Current access

+

@(Model.Entitlement?.EffectiveLevel?.DisplayName ?? "Read only")

+
+
+

Underlying plan

@subscription.DisplayName

-

Trial start

-

@(trial is null ? "Not on trial" : FormatDate(trial.StartDateUtc))

+

Access expiry

+

@(Model.Entitlement?.ActiveOverride?.ExpiryDateUTC is DateTime overrideExpiry ? FormatDate(overrideExpiry) : Model.Entitlement?.UsesAdministrativeOverride == true ? "No expiry" : trial is null ? "Not applicable" : FormatDate(trial.ExpiryDateUtc))

-

Trial expiry

-

@(trial is null ? "Not on trial" : FormatDate(trial.ExpiryDateUtc))

-
-
-

Days remaining

-

@(trial is null ? "Not on trial" : trial.StatusLabel)

+

Access source

+

@(Model.Entitlement?.UsesAdministrativeOverride == true ? "Complimentary access" : Model.Entitlement?.IsTrial == true ? "Application trial" : "Subscription")

Books

-

@FormatLimit(subscription.MaxBooks)

+

@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxBooks ?? 0)

Storage

-

@FormatStorage(subscription.MaxStorageMB)

+

@FormatStorage(Model.Entitlement?.EffectiveLevel?.MaxStorageMB ?? 0)

Chapters per book

-

@FormatLimit(subscription.MaxChaptersPerBook)

+

@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxChaptersPerBook ?? 0)

Scenes per book

-

@FormatLimit(subscription.MaxScenesPerBook)

+

@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxScenesPerBook ?? 0)

Characters per project

-

@FormatLimit(subscription.MaxCharactersPerProject)

+

@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxCharactersPerProject ?? 0)

Collaborators

-

@subscription.MaxCollaborators

+

@(Model.Entitlement?.EffectiveLevel?.MaxCollaborators ?? 0)

} diff --git a/PlotLine/Views/ManageAccount/Subscription.cshtml b/PlotLine/Views/ManageAccount/Subscription.cshtml index 43ae96ec..ef28d607 100644 --- a/PlotLine/Views/ManageAccount/Subscription.cshtml +++ b/PlotLine/Views/ManageAccount/Subscription.cshtml @@ -4,6 +4,7 @@ var subscription = Model.CurrentSubscription; var trial = Model.Trial; var usage = Model.Usage; + var effectiveLevel = Model.Entitlement?.EffectiveLevel; }