Commit completed calendar navigation and subscription override updates

This commit is contained in:
Nick Beckley 2026-11-02 16:51:32 +00:00
parent 5d2a12de48
commit 5d2e080539
22 changed files with 438 additions and 173 deletions

View File

@ -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)});

View File

@ -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)});

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(subscription),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(activeOverride),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)),
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
nameof(ISubscriptionRepository.GetOwnedBookCountAsync) => Task.FromResult(ownedBooks),
_ => DefaultTask(method)
@ -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<int, SubscriptionLevel>
{
[1] = Level(1, "DraftDesk", "Draft Desk", 2, false),
[4] = Level(4, "AuthorStudio", "Author Studio", 999999, true)
};
var repository = Proxy<ISubscriptionRepository>((method, args) => method switch
{
nameof(ISubscriptionRepository.GetSubscriptionForEntitlementAsync) => Task.FromResult<UserSubscriptionDetail?>(underlying),
nameof(ISubscriptionRepository.GetActiveOverrideAsync) => Task.FromResult(ActiveAt(activeOverride, (DateTime)args![1]!)),
nameof(ISubscriptionRepository.GetSubscriptionLevelAsync) => Task.FromResult<SubscriptionLevel?>(levels[(int)args![0]!]),
_ => DefaultTask(method)
});
var service = new SubscriptionService(repository, Proxy<IUserFileRepository>((method, _) => DefaultTask(method)));
var genuineTrial = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var genuineBanner = TrialVisibilityViewModel.FromEntitlement(genuineTrial, now);
Check(genuineTrial.State == EntitlementState.ActiveTrial && genuineBanner is { IsAdministrativeOverride: false },
"A genuine Draft Desk application trial must retain trial presentation when no override exists.");
Check(genuineBanner!.Description.Contains("30-day Draft Desk trial", StringComparison.Ordinal),
"Only a genuine application trial should use 30-day trial wording.");
activeOverride = Override(1, now.AddDays(-1), now.AddDays(60), "Draft Desk");
var draftTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var draftTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(draftTemporary, now);
Check(draftTemporary.EffectiveLevel?.Name == "DraftDesk" && draftTemporaryBanner is { IsAdministrativeOverride: true },
"A temporary Draft Desk override must be effective access, not an extension of the underlying trial.");
Check(!draftTemporaryBanner!.Description.Contains("trial", StringComparison.OrdinalIgnoreCase)
&& !draftTemporaryBanner.Description.Contains("30-day", StringComparison.OrdinalIgnoreCase),
"A temporary Draft Desk override must not be described as a trial.");
activeOverride = Override(1, now.AddDays(-1), null, "Draft Desk");
var draftIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(draftIndefinite.State == EntitlementState.ActiveOverride
&& TrialVisibilityViewModel.FromEntitlement(draftIndefinite, now) is null,
"An indefinite Draft Desk override must not show an expiry banner.");
activeOverride = Override(4, now.AddDays(-1), now.AddMonths(3), "Author Studio");
var authorTemporary = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
var authorTemporaryBanner = TrialVisibilityViewModel.FromEntitlement(authorTemporary, now);
Check(authorTemporary.EffectiveLevel?.Name == "AuthorStudio"
&& authorTemporaryBanner?.StatusLabel.Contains("Author Studio access until", StringComparison.Ordinal) == true,
"A temporary Author Studio override must show its effective access expiry.");
activeOverride = Override(4, now.AddDays(-1), null, "Author Studio");
underlying.TrialExpiryDateUTC = now.AddDays(-1);
var authorIndefinite = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(authorIndefinite.State == EntitlementState.ActiveOverride && authorIndefinite.IsActive
&& TrialVisibilityViewModel.FromEntitlement(authorIndefinite, now) is null,
"An expired underlying trial must not compete with an indefinite higher override.");
underlying.TrialExpiryDateUTC = now.AddDays(20);
activeOverride = Override(4, now.AddDays(-10), now, "Author Studio");
var expiredFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(expiredFallback.State == EntitlementState.ActiveTrial && expiredFallback.EffectiveLevel?.Name == "DraftDesk",
"An expired override must automatically fall back to the underlying trial state.");
activeOverride = null;
var removedFallback = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(removedFallback.State == EntitlementState.ActiveTrial && removedFallback.EffectiveLevel?.Name == "DraftDesk",
"A removed override must fall back to the underlying entitlement.");
underlying = Paid(now, "active");
activeOverride = Override(1, now.AddDays(-1), now.AddDays(30), "Draft Desk");
var paidWithOverride = service.GetEffectiveEntitlementAsync(7, now).GetAwaiter().GetResult();
Check(paidWithOverride.State == EntitlementState.ActiveOverride && paidWithOverride.EffectiveLevel?.Name == "DraftDesk"
&& paidWithOverride.UnderlyingSubscription?.StripeStatus == "active",
"An administrative override must control effective access while preserving underlying paid billing state.");
var root = FindRepositoryRoot();
var projectService = File.ReadAllText(Path.Combine(root, "PlotLine", "Services", "CoreServices.cs"));
var projectView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Projects", "Index.cshtml"));
var adminView = File.ReadAllText(Path.Combine(root, "PlotLine", "Views", "Admin", "Subscriptions.cshtml"));
Check(projectService.Contains("FromEntitlement(entitlement", StringComparison.Ordinal)
&& !projectService.Contains("TrialVisibilityViewModel.FromSubscription", StringComparison.Ordinal),
"The Projects dashboard must build its banner from effective entitlement.");
Check(projectView.Contains("@trial.Description", StringComparison.Ordinal)
&& !projectView.Contains("Your 30-day trial expires", StringComparison.Ordinal),
"The Projects dashboard must not hard-code contradictory trial wording.");
Check(!adminView.Contains("Change trial expiry", StringComparison.Ordinal)
&& adminView.Contains("sole administrator control", StringComparison.Ordinal),
"The separate administrative trial-expiry control must be removed.");
Check(typeof(AdminController).GetMethod("ExtendTrial") is null
&& typeof(ISubscriptionRepository).GetMethod("ExtendTrialAsync") is null,
"The removed trial-expiry panel must not leave a callable application endpoint or repository mutation path.");
}
public static void EnforcementAndAdminSecurity()
{
var sql = File.ReadAllText(Path.Combine(FindRepositoryRoot(), "PlotLine", "Sql", "201_SubscriptionEntitlementEnforcement.sql"));
@ -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,

View File

@ -88,6 +88,7 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
builder.Services.AddScoped<ICurrentUserService>(services => new ToolbarTestUser(int.Parse(services.GetRequiredService<IHttpContextAccessor>().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<IStoryCalendarService>(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<ICompositeViewEngine>().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<ITempDataProvider>()), 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<IStoryCalendarService>().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 = "<div data-story-calendar-root>" + surface + "</div><script src='/js/story-calendar.js'></script>";
if (timelinePage)
{
surface = """

View File

@ -74,29 +74,6 @@ public sealed class AdminController(
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)

View File

@ -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

View File

@ -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
});
}

View File

@ -28,7 +28,6 @@ public interface ISubscriptionRepository
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);
}
@ -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();

View File

@ -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<SelectListItem> BuildMonthOptions(DateOnly? earliest, DateOnly? latest, DateOnly? selectedMonth)
private static IReadOnlyList<SelectListItem> BuildMonthOptions(
IReadOnlyList<StoryCalendarSceneViewModel> 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<SelectListItem>();
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<DateOnly> StoryMonths(IReadOnlyList<StoryCalendarSceneViewModel> 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<StoryCalendarSceneViewModel> 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<DateOnly?>().LastOrDefault()
: months.Where(date => date > selectedMonth).Cast<DateOnly?>().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()
};

View File

@ -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<SubscriptionLevel> 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<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)]

View File

@ -32,11 +32,12 @@
<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">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">Effective access</p><p><strong>@(entitlement.EffectiveLevel?.DisplayName ?? "Read only")</strong> — @(entitlement.UsesAdministrativeOverride ? "Administrative override" : entitlement.State.ToString())</p></div>
<div class="col-md-4"><p class="eyebrow">Underlying trial start</p><p>@(underlying?.IsTrial == true ? underlying.StartDateUTC.ToString("d MMMM yyyy 'UTC'") : "Not applicable")</p></div>
<div class="col-md-4"><p class="eyebrow">Underlying trial expiry</p><p>@(underlying?.TrialExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "Not set")</p></div>
<div class="col-md-4"><p class="eyebrow">Override expiry</p><p>@(entitlement.ActiveOverride is null ? "Not active" : entitlement.ActiveOverride.ExpiryDateUTC?.ToString("d MMMM yyyy 'UTC'") ?? "Never")</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)
@ -45,8 +46,16 @@
<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>
<section class="edit-panel">
<h2>Administrative access override</h2>
<p class="muted">This is the sole administrator control for temporary or indefinite complimentary access. It does not change Stripe or the underlying application trial.</p>
<form asp-action="SaveSubscriptionOverride" method="post" class="row g-3">
<input type="hidden" name="UserID" value="@Model.SelectedUser.UserID" />
<div class="col-md-6"><label class="form-label">Plan level</label><select class="form-select" name="SubscriptionLevelID" required>@foreach (var level in Model.Levels) { <option value="@level.SubscriptionLevelID" selected="@(entitlement.ActiveOverride?.SubscriptionLevelID == level.SubscriptionLevelID)">@level.DisplayName</option> }</select></div>
<div class="col-md-6"><label class="form-label">Starts (UTC)</label><input class="form-control" type="datetime-local" name="StartDateUTC" value="@((entitlement.ActiveOverride?.StartDateUTC ?? DateTime.UtcNow).ToString("yyyy-MM-ddTHH:mm"))" required /></div>
<div class="col-md-6"><label class="form-label">Optional expiry (UTC)</label><input class="form-control" type="datetime-local" name="ExpiryDateUTC" value="@(entitlement.ActiveOverride?.ExpiryDateUTC?.ToString("yyyy-MM-ddTHH:mm"))" /></div>
<div class="col-md-12"><label class="form-label">Reason</label><textarea class="form-control" name="Reason" required maxlength="1000"></textarea></div>
<div class="col-md-12"><button class="btn btn-primary" type="submit">@(entitlement.ActiveOverride is null ? "Grant override" : "Update override")</button></div>
</form>
</section>
}

View File

@ -75,57 +75,60 @@
<div class="trial-status-panel @trial.WarningCssClass">
<div class="trial-status-panel__heading">
<div>
<p class="eyebrow">Free trial status</p>
<p class="eyebrow">@trial.Eyebrow</p>
<h3>@trial.StatusLabel</h3>
</div>
<a class="btn btn-outline-primary btn-sm" asp-action="Subscription">Upgrade</a>
</div>
<p>Your 30-day @trial.PlanName trial expires on @FormatDate(trial.ExpiryDateUtc).</p>
<div class="trial-progress" aria-label="Trial progress">
<div class="trial-progress__bar" style="width: @trial.ProgressPercentage%"></div>
</div>
<p>@trial.Description</p>
@if (trial.ShowProgress)
{
<div class="trial-progress" aria-label="Trial progress">
<div class="trial-progress__bar" style="width: @trial.ProgressPercentage%"></div>
</div>
}
</div>
}
<div class="row g-3">
<div class="col-md-4">
<p class="eyebrow">Current plan</p>
<p class="eyebrow">Current access</p>
<p>@(Model.Entitlement?.EffectiveLevel?.DisplayName ?? "Read only")</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Underlying plan</p>
<p>@subscription.DisplayName</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Trial start</p>
<p>@(trial is null ? "Not on trial" : FormatDate(trial.StartDateUtc))</p>
<p class="eyebrow">Access expiry</p>
<p>@(Model.Entitlement?.ActiveOverride?.ExpiryDateUTC is DateTime overrideExpiry ? FormatDate(overrideExpiry) : Model.Entitlement?.UsesAdministrativeOverride == true ? "No expiry" : trial is null ? "Not applicable" : FormatDate(trial.ExpiryDateUtc))</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Trial expiry</p>
<p>@(trial is null ? "Not on trial" : FormatDate(trial.ExpiryDateUtc))</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Days remaining</p>
<p>@(trial is null ? "Not on trial" : trial.StatusLabel)</p>
<p class="eyebrow">Access source</p>
<p>@(Model.Entitlement?.UsesAdministrativeOverride == true ? "Complimentary access" : Model.Entitlement?.IsTrial == true ? "Application trial" : "Subscription")</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Books</p>
<p>@FormatLimit(subscription.MaxBooks)</p>
<p>@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxBooks ?? 0)</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Storage</p>
<p>@FormatStorage(subscription.MaxStorageMB)</p>
<p>@FormatStorage(Model.Entitlement?.EffectiveLevel?.MaxStorageMB ?? 0)</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Chapters per book</p>
<p>@FormatLimit(subscription.MaxChaptersPerBook)</p>
<p>@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxChaptersPerBook ?? 0)</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Scenes per book</p>
<p>@FormatLimit(subscription.MaxScenesPerBook)</p>
<p>@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxScenesPerBook ?? 0)</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Characters per project</p>
<p>@FormatLimit(subscription.MaxCharactersPerProject)</p>
<p>@FormatLimit(Model.Entitlement?.EffectiveLevel?.MaxCharactersPerProject ?? 0)</p>
</div>
<div class="col-md-4">
<p class="eyebrow">Collaborators</p>
<p>@subscription.MaxCollaborators</p>
<p>@(Model.Entitlement?.EffectiveLevel?.MaxCollaborators ?? 0)</p>
</div>
</div>
}

View File

@ -4,6 +4,7 @@
var subscription = Model.CurrentSubscription;
var trial = Model.Trial;
var usage = Model.Usage;
var effectiveLevel = Model.Entitlement?.EffectiveLevel;
}
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
@ -32,10 +33,14 @@
@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
<strong>Current access: @(Model.Entitlement.EffectiveLevel?.DisplayName ?? "Read only")</strong>
@if (Model.Entitlement.UsesAdministrativeOverride)
{
<span> Access ends @(Model.Entitlement.ActiveOverride?.ExpiryDateUTC?.ToString("d MMMM yyyy") ?? "only when removed").</span>
<span> — access @(Model.Entitlement.ActiveOverride?.ExpiryDateUTC is DateTime expiry ? $"until {expiry:d MMMM yyyy}" : "has no expiry").</span>
}
else
{
<span> — @Model.Entitlement.Reason</span>
}
</div>
}
@ -50,50 +55,53 @@
<div class="trial-status-panel @trial.WarningCssClass">
<div class="trial-status-panel__heading">
<div>
<p class="eyebrow">Free trial status</p>
<p class="eyebrow">@trial.Eyebrow</p>
<h3>@trial.StatusLabel</h3>
</div>
<a class="btn btn-primary btn-sm" asp-controller="Pricing" asp-action="Index">Upgrade</a>
</div>
<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__bar" style="width: @trial.ProgressPercentage%"></div>
</div>
<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>
<p>@trial.Description</p>
@if (trial.ShowProgress)
{
<div class="trial-progress" aria-label="Trial progress">
<div class="trial-progress__bar" style="width: @trial.ProgressPercentage%"></div>
</div>
<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 class="row g-3">
<div class="col-md-4">
<p class="eyebrow">Plan</p>
<p>@subscription.DisplayName</p>
<p class="eyebrow">Current access</p>
<p>@(effectiveLevel?.DisplayName ?? "Read only")</p>
</div>
<div class="col-md-8">
<p class="eyebrow">Description</p>
<p>@(string.IsNullOrWhiteSpace(subscription.Description) ? "No description available." : subscription.Description)</p>
<p>@(string.IsNullOrWhiteSpace(effectiveLevel?.Description) ? "No description available." : effectiveLevel.Description)</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Status</p>
<p>@(string.IsNullOrWhiteSpace(subscription.StripeStatus) ? (subscription.IsActive ? "Active" : "Inactive") : subscription.StripeStatus)</p>
<p class="eyebrow">Underlying plan</p>
<p>@subscription.DisplayName</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Billing interval</p>
<p>@(string.IsNullOrWhiteSpace(subscription.BillingInterval) ? "Not set" : subscription.BillingInterval)</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Trial</p>
<p>@(trial is null ? "No" : "30-day free trial")</p>
<p class="eyebrow">Billing status</p>
<p>@(string.IsNullOrWhiteSpace(subscription.StripeStatus) ? (subscription.IsTrial ? "Application trial" : subscription.IsActive ? "Active" : "Inactive") : subscription.StripeStatus)</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Trial start</p>
<p>@(trial is null ? "Not set" : FormatDate(trial.StartDateUtc))</p>
<p class="eyebrow">Access source</p>
<p>@(Model.Entitlement?.UsesAdministrativeOverride == true ? "Complimentary access" : Model.Entitlement?.IsTrial == true ? "Application trial" : "Paid subscription")</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Trial expiry</p>
<p>@(trial is null ? FormatDate(subscription.TrialExpiryDateUTC) : FormatDate(trial.ExpiryDateUtc))</p>
<p class="eyebrow">Access expiry</p>
<p>@(Model.Entitlement?.ActiveOverride?.ExpiryDateUTC is DateTime overrideExpiry ? FormatDate(overrideExpiry) : Model.Entitlement?.UsesAdministrativeOverride == true ? "No expiry" : Model.Entitlement?.TrialExpiryDateUTC is DateTime trialExpiry ? FormatDate(trialExpiry) : FormatDate(subscription.EndDateUTC))</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Days remaining</p>
<p>@(trial is null ? "Not on trial" : trial.StatusLabel)</p>
<p class="eyebrow">Underlying trial expiry</p>
<p>@FormatDate(subscription.TrialExpiryDateUTC)</p>
</div>
<div class="col-md-3">
<p class="eyebrow">Started</p>
@ -150,7 +158,7 @@
<tbody>
<tr>
<td>Books</td>
<td>@FormatUsage(usage.BooksUsed, subscription.MaxBooks, "books")</td>
<td>@FormatUsage(usage.BooksUsed, effectiveLevel?.MaxBooks ?? 0, "books")</td>
</tr>
<tr>
<td>Storage</td>
@ -158,19 +166,19 @@
</tr>
<tr>
<td>Collaborators</td>
<td>@FormatUsage(usage.CollaboratorsUsed, subscription.MaxCollaborators, "collaborators")</td>
<td>@FormatUsage(usage.CollaboratorsUsed, effectiveLevel?.MaxCollaborators ?? 0, "collaborators")</td>
</tr>
<tr>
<td>Highest chapters in a book</td>
<td>@FormatUsage(usage.HighestChaptersInBook, subscription.MaxChaptersPerBook, "chapters")</td>
<td>@FormatUsage(usage.HighestChaptersInBook, effectiveLevel?.MaxChaptersPerBook ?? 0, "chapters")</td>
</tr>
<tr>
<td>Highest scenes in a book</td>
<td>@FormatUsage(usage.HighestScenesInBook, subscription.MaxScenesPerBook, "scenes")</td>
<td>@FormatUsage(usage.HighestScenesInBook, effectiveLevel?.MaxScenesPerBook ?? 0, "scenes")</td>
</tr>
<tr>
<td>Highest characters in a project</td>
<td>@FormatUsage(usage.HighestCharactersInProject, subscription.MaxCharactersPerProject, "characters")</td>
<td>@FormatUsage(usage.HighestCharactersInProject, effectiveLevel?.MaxCharactersPerProject ?? 0, "characters")</td>
</tr>
</tbody>
</table>

View File

@ -106,7 +106,7 @@
else
{
<a class="marketing-btn marketing-btn--primary" asp-controller="Pricing" asp-action="Checkout" asp-route-id="@plan.SubscriptionLevelID" asp-route-billingInterval="Monthly">
@(isCurrent ? "Current plan" : "Choose this plan")
@(isCurrent ? (Model.UsesAdministrativeOverride ? "Current access" : "Current plan") : "Choose this plan")
</a>
@if (plan.AnnualPricePence.HasValue)
{

View File

@ -20,22 +20,18 @@
{
<section class="trial-dashboard-banner @trial.WarningCssClass"
data-trial-banner
data-trial-banner-key="projects:@trial.ExpiryDateUtc.ToString("yyyyMMdd")"
aria-label="Trial status">
data-trial-banner-key="projects:@trial.PlanName:@trial.ExpiryDateUtc.ToString("yyyyMMdd")"
aria-label="Current access status">
<div class="trial-dashboard-banner__body">
<p class="eyebrow">Free trial status</p>
<h2>@trial.StatusLabel on @trial.PlanName</h2>
@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>
}
<p class="eyebrow">@trial.Eyebrow</p>
<h2>@trial.StatusLabel</h2>
<p>@trial.Description</p>
</div>
<div class="trial-dashboard-banner__actions">
<a class="btn btn-primary btn-sm" asp-controller="ManageAccount" asp-action="Subscription">Upgrade</a>
@if (!trial.IsAdministrativeOverride)
{
<a class="btn btn-primary btn-sm" asp-controller="ManageAccount" asp-action="Subscription">Upgrade</a>
}
<button class="btn btn-outline-secondary btn-sm" type="button" data-trial-banner-dismiss>Dismiss</button>
</div>
</section>

View File

@ -19,17 +19,17 @@
</div>
</div>
<section class="card mb-3 story-calendar-filter">
<section class="card mb-3 story-calendar-filter" data-pwa-context data-pwa-scope="Calendar" data-pwa-responsive="true" data-pwa-priority="10">
<div class="card-body">
<form asp-action="ApplyFilters" method="post" class="row g-2 align-items-end" data-story-calendar-filter data-story-calendar-index-url="@Url.Action("Index", "StoryCalendar")">
<form asp-action="ApplyFilters" method="post" class="row g-2 align-items-end" data-pwa-fields="stacked" data-story-calendar-filter data-story-calendar-index-url="@Url.Action("Index", "StoryCalendar")">
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
<div class="col-md-5 col-lg-4">
<label class="form-label" for="bookId">Book <help-icon key="storyCalendar.filters.book" /></label>
<select class="form-select" id="bookId" name="bookId" asp-items="Model.BookOptions"></select>
<select class="form-select" id="bookId" name="bookId" data-pwa-label="Book" asp-items="Model.BookOptions"></select>
</div>
<div class="col-md-4 col-lg-3">
<label class="form-label" for="month">Month <help-icon key="storyCalendar.filters.month" /></label>
<select class="form-select" id="month" name="month" disabled="@(!Model.MonthOptions.Any())">
<select class="form-select" id="month" name="month" data-pwa-label="Month" disabled="@(!Model.MonthOptions.Any())">
@if (!Model.MonthOptions.Any())
{
<option value="">No dated scenes</option>
@ -43,9 +43,6 @@
}
</select>
</div>
<div class="col-md-3 col-lg-2">
<button class="btn btn-primary w-100" type="submit">Apply</button>
</div>
</form>
</div>
</section>

View File

@ -672,3 +672,22 @@ html[data-app-theme="plotdirector"] .app-layout :is(.warning-filter-panel,.analy
html[data-app-theme="plotdirector"] .app-layout input[type="range"] { accent-color: var(--pd-accent); }
/* The house theme anchors the picker; six alternatives remain balanced below it. */
.pd-theme-picker [data-app-theme-choice="plotdirector"] { grid-column: 1 / -1; justify-content: center; }
/* Calendar controls use the shared ribbon form; retain the range and statistics. */
html[data-standalone="true"] .story-calendar-heading {
margin-bottom: .5rem;
gap: .5rem;
}
html[data-standalone="true"] .story-calendar-heading .lead-text {
margin-bottom: 0;
}
html[data-standalone="true"] .story-calendar-shell {
gap: .5rem;
}
html[data-standalone="true"] .story-calendar-toolbar .button-row {
flex-wrap: wrap;
gap: .35rem;
}
html[data-standalone="true"] .story-calendar-toolbar .button-row .btn {
width: auto;
}

View File

@ -368,7 +368,7 @@
if (!form.querySelector('select, input:not([type="hidden"]), textarea')) return false;
const scopeLabel = region.dataset.pwaScope || (form.querySelector('select') ? 'Scope' : 'Find');
const target = group(scopeLabel, 10, region.dataset.pwaCompact === 'true').element;
target.parentElement.dataset.essential = 'true';
target.parentElement.dataset.essential = String(region.dataset.pwaResponsive !== 'true');
return renderForm(form, target);
}));
region.querySelectorAll('[data-pwa-context-status]').forEach(source => {

View File

@ -68,7 +68,7 @@
return true;
} catch {
root.removeAttribute("aria-busy");
showCalendarNotice("The calendar could not be loaded. Use the link or Apply button to retry.", "error");
showCalendarNotice("The calendar could not be loaded. Refresh the page or change a filter to retry.", "error");
return false;
}
};

View File

@ -12,13 +12,14 @@ Active books in active projects owned by the user count toward `MaxBooks`. Archi
`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.
1. Calculate the genuine underlying application-trial or paid-subscription state.
2. If an active, non-revoked administrative override has started and its optional expiry has not arrived, its selected plan is the effective PlotDirector access.
3. Otherwise use the genuine underlying entitlement: active application trial, active paid subscription, or read-only access for an expired/ended/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.
An override may select any existing plan, including Draft Desk. Its own optional expiry is the only date controlling that complimentary access. An indefinite override remains effective until revoked. The underlying trial may expire while a higher override remains active without changing effective access.
Stripe state remains commercial state. `SubscriptionOverride` never updates Stripe identifiers, price IDs, status, or billing periods.
## Enforcement
@ -45,12 +46,16 @@ Subscription administration is under `/admin/subscriptions` and the existing `Ad
Administrators can:
- set an application-managed trial expiry;
- grant an existing level from a UTC start until an optional UTC expiry;
- update an active override using the same plan/start/optional-expiry/reason form;
- revoke an override.
There is deliberately no separate administrative trial-extension control. Draft Desk with an override expiry represents temporary complimentary Draft Desk access; Draft Desk without an override expiry represents indefinite complimentary access until removal. Genuine trial fields remain stored as underlying billing/application state and are not rewritten by 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.
Dashboard and account access banners are built from `EffectiveEntitlement`. A genuine application trial may use 30-day trial wording. A temporary override is described as plan access until its actual override expiry, and an indefinite override has no expiry warning. Pages must not derive access messaging directly from `TrialExpiryDateUTC`.
## 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.