diff --git a/PlotLine.Tests/Browser/context-saved-data-development.cjs b/PlotLine.Tests/Browser/context-saved-data-development.cjs
new file mode 100644
index 00000000..0b3280ff
--- /dev/null
+++ b/PlotLine.Tests/Browser/context-saved-data-development.cjs
@@ -0,0 +1,44 @@
+// Real Development UI, normal writer authentication, and registered disposable data only.
+const assert=require('node:assert/strict'),{open}=require('./dev-acceptance.cjs');
+let session,stage='login';
+(async()=>{try{
+ session=await open();const p=session.page;const project=await session.project();
+ const place=await session.create('Locations','?projectId='+project,{LocationName:'Acceptance room',Description:'Original description'});
+ const book=await session.create('Books','?projectId='+project,{BookTitle:'Context acceptance one',BookNumber:1});
+ const otherBook=await session.create('Books','?projectId='+project,{BookTitle:'Context acceptance two',BookNumber:2});
+ const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Context chapter one',ChapterNumber:1});
+ const otherChapter=await session.create('Chapters','?bookId='+otherBook,{ChapterTitle:'Context chapter two',ChapterNumber:1});
+ async function scene(chapter,title){await session.goto('/Scenes/Create?chapterId='+chapter);await p.locator('#SceneTitle').fill(title);await p.locator('#PrimaryLocationID').selectOption(String(place));await p.getByRole('button',{name:'Create scene',exact:true}).click();await p.waitForURL('**/Scenes/Edit/*');return Number(new URL(p.url()).pathname.split('/').at(-1));}
+ const sceneId=await scene(chapter,'Held acceptance scene'),otherScene=await scene(otherChapter,'Isolated acceptance scene');
+ stage='map creation';await session.goto('/Maps?projectId='+project);await p.locator('#mapsWelcomeNew').click();await p.locator('#mapsNewForm [name=Name]').fill('Acceptance geometry');await p.locator('#mapsNewForm [name=Starter]').selectOption('land');await p.locator('#mapsNewForm button[type=submit]').click();await p.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.features.length>0&&!window.PlotDirectorMapWorkspace.busy);const map=await p.evaluate(()=>PlotDirectorMapWorkspace.document.map.mapID);
+ stage='floor plan creation';await session.goto('/FloorPlans?projectId='+project);const create=p.locator('form[action="/FloorPlans/Create"]');await create.locator('[name=Name]').fill('Acceptance plan');await create.locator('[name=LocationID]').selectOption(String(place));await create.locator('button[type=submit]').click();await p.waitForURL('**/FloorPlans/Edit/*');const plan=Number(new URL(p.url()).pathname.split('/').at(-1));
+ const context=p.context(),a=await context.newPage(),b=await context.newPage(),c=await context.newPage(),reads=[];
+ for(const page of [a,b,c])page.on('request',r=>{const path=new URL(r.url()).pathname;if(path.startsWith('/SpatialContext/')||path.includes('/Context/Tabs/'))reads.push({page,path});});
+ const url=(bk,ch,sc)=>`https://dev.plotdirector.com/Writing/Context?projectId=${project}&bookId=${bk}&chapterId=${ch}&sceneId=${sc}&pinned=true`;
+ const setTab=(page,i,tool)=>page.selectOption(`[data-context-pane="${i}"] [data-context-tab]`,tool);
+ await a.goto(url(book,chapter,sceneId));await a.selectOption('[data-context-layout]','columns');await setTab(a,0,'maps');await setTab(a,1,'floorplans');
+ await a.locator('[data-context-pane="0"] [data-spatial-resource]').selectOption(String(map));await a.locator('[data-context-pane="1"] [data-spatial-resource]').selectOption(String(plan));
+ await a.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document);
+ await a.locator('[data-floor-grid]').first().waitFor();
+ await b.goto(url(book,chapter,sceneId));await b.selectOption('[data-context-layout]','columns');await setTab(b,0,'locations');await setTab(b,1,'overview');await b.getByRole('heading',{name:'Acceptance room',exact:true}).waitFor();
+ await c.goto(url(otherBook,otherChapter,otherScene));await c.locator('[data-context-tab-fragment]').waitFor();
+ await Promise.all([a,b,c].map(page=>page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected')));
+ await a.locator('[data-context-pane="0"] [data-spatial-zoom="in"]').click();await a.locator('[data-context-pane="1"] [data-spatial-zoom="in"]').click();await a.waitForTimeout(400);
+ const snapshot=()=>a.evaluate(()=>({position:{...document.querySelector('[data-context-workspace]').contextController.position},view:{...document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.view},floor:document.querySelector('[data-spatial-floor]').value,transform:document.querySelector('[data-spatial-floor-world]').style.transform}));
+ const before=await snapshot();
+ stage='committed geometry save and relevant refresh';await session.goto(`/Maps?projectId=${project}&id=${map}`);await p.locator('[data-feature-id]').first().click();const width=p.locator('[data-field=width]').first();const savedWidth=Number(await width.inputValue())+37;reads.length=0;await width.fill(String(savedWidth));await p.waitForTimeout(300);assert.equal(reads.length,0,'unsaved geometry emits no saved-data read');
+ await p.locator('#mapsSave').click();await p.waitForFunction(()=>!PlotDirectorMapWorkspace.dirty&&!PlotDirectorMapWorkspace.busy);
+ await a.waitForFunction(w=>document.querySelector('iframe')?.contentWindow.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await a.waitForTimeout(300);
+ assert.equal(reads.filter(r=>r.path==='/SpatialContext/Floor').length,0);assert.equal(reads.filter(r=>r.page===c).length,0,'project-wide geometry does not refresh unrelated Overview');assert.deepEqual(await snapshot(),before);
+ stage='failed save does not invalidate';reads.length=0;const failed=await p.evaluate(async()=>{const doc=structuredClone(PlotDirectorMapWorkspace.document);doc.map.revision=-1;const token=document.querySelector('[name=__RequestVerificationToken]').value;return (await fetch('/Maps/Save',{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':token},body:JSON.stringify(doc)})).status;});assert(failed>=400);await a.waitForTimeout(400);assert.equal(reads.length,0);
+ stage='floor layout persistence and viewport retention';await session.goto('/FloorPlans/Edit/'+plan);const floorWidth=p.locator('[data-floor-width]').first();await floorWidth.evaluate(e=>{for(let node=e.parentElement;node;node=node.parentElement)if(node.tagName==='DETAILS')node.open=true;});const savedFloorWidth=Number(await floorWidth.inputValue())+1;await floorWidth.fill(String(savedFloorWidth));reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/FloorPlans/SaveLayout')&&r.status()===200),p.locator('[data-save-layout-button]').first().click()]);await a.waitForFunction(w=>Number(document.querySelector('[data-floor-grid]').dataset.gridWidth)===w,savedFloorWidth);await a.waitForTimeout(300);assert.equal(reads.filter(r=>r.path==='/SpatialContext/Map').length,0);assert.equal(reads.filter(r=>r.page===b||r.page===c).length,0);assert.deepEqual(await snapshot(),before);
+ stage='held location saved-data update';await session.goto('/Locations/Edit/'+place);await p.locator('[name=Description]').fill('Saved description after refresh');await p.locator('form.pd-record-form button[type=submit]').first().click();await p.waitForURL('**/Locations/Details/*');await b.getByText('Saved description after refresh',{exact:true}).waitFor();assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId);
+ stage='date-only save targets Overview and preserves book isolation';await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);const exact=await p.locator('[name=TimeModeID] option').evaluateAll(options=>options.find(o=>/exact/i.test(o.textContent))?.value);assert(exact);await p.locator('[name=TimeModeID]').selectOption(exact);await p.locator('[name=StartDateTime]').fill('2030-05-06T10:00');reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/Scenes/SaveSceneDetails')&&r.status()===200),p.getByRole('button',{name:'Save details',exact:true}).click()]);await b.waitForFunction(()=>document.querySelector('[data-context-pane="1"]').textContent.includes('2030'));await b.waitForTimeout(300);assert.equal(reads.filter(r=>r.page===a||r.page===c).length,0,'date-only save does not refresh spatial or other-book panes');
+ stage='book-scoped intent and isolation';await session.goto('/Scenes/Edit/'+sceneId);reads.length=0;await session.post('/Scenes/SaveScenePurpose',{SceneID:sceneId,ScenePurposeNotes:'Saved acceptance purpose',SceneOutcomeNotes:'Saved acceptance outcome'});await b.waitForTimeout(700);assert.equal(reads.filter(r=>r.page===c).length,0);assert.equal(reads.filter(r=>r.page===a).length,0,'intent does not refresh spatial panes');
+ stage='existing main window navigation';await p.waitForTimeout(600);const held=b.url();await b.getByRole('link',{name:'Location Details',exact:true}).click();await p.waitForURL('**/Locations/Details/'+place);assert.equal(b.url(),held);assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId);
+ await session.close();session=null;
+ stage='fresh normal login and durable reload';session=await open();await session.goto(`/Maps?projectId=${project}&id=${map}`);await session.page.waitForFunction(w=>window.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await session.goto('/FloorPlans/Edit/'+plan);assert.equal(Number(await session.page.locator('[data-floor-width]').first().inputValue()),savedFloorWidth);await session.goto('/Locations/Edit/'+place);assert.equal(await session.page.locator('[name=Description]').inputValue(),'Saved description after refresh');await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);assert.match(await session.page.locator('[name=StartDateTime]').inputValue(),/^2030-05-06T10:00/);await session.goto('/Scenes/ScenePurposeEditor?sceneId='+sceneId);assert.equal(await session.page.locator('[name=ScenePurposeNotes]').inputValue(),'Saved acceptance purpose');
+ console.log(JSON.stringify({passed:true,project,book,otherBook,sceneId,map,plan,checks:['real committed map geometry','unsaved and failed saves silent','floor layout and map/floor viewport retention','held saved location refresh','book isolation','date-only targeting','relevant panels only','existing main navigation','fresh-login persistence'],featureUrl:`https://dev.plotdirector.com/Writing/Context?bookId=${book}&sceneId=${sceneId}&pinned=true`}));
+ }catch{console.error('Development Context acceptance failed at '+stage+'; no credentials logged.');process.exitCode=1;}
+ finally{if(session){try{await session.cleanup();console.log('PASS disposable project cleanup');}catch{console.error('Cleanup incomplete; preserve journal and resume documented scoped cleanup.');process.exitCode=1;}finally{await session.close();}}}
+})();
diff --git a/PlotLine.Tests/Browser/context-saved-data.cjs b/PlotLine.Tests/Browser/context-saved-data.cjs
new file mode 100644
index 00000000..b0264795
--- /dev/null
+++ b/PlotLine.Tests/Browser/context-saved-data.cjs
@@ -0,0 +1,45 @@
+// Actual Context shell, reusable spatial partials and renderers; synthetic read-only fixtures.
+const {chromium}=require('playwright'),assert=require('node:assert/strict');
+const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
+(async()=>{
+ const browser=await chromium.launch();let step='setup';
+ try{
+ const context=await browser.newContext({viewport:{width:1440,height:1000}}),reads=[],writes=[],errors=[];
+ await context.route('**/native-companion/**',r=>r.fulfill({json:[]}));
+ await context.route('**/SharedFocus/**',r=>r.fulfill({json:{}}));
+ await context.route('**/Writing/Context/Position*',r=>r.fulfill({json:{connected:false}}));
+ await context.route('**/Writing/Context/MyWindows*',r=>r.fulfill({json:[]}));
+ await context.route('**/Writing/Context/Tabs/*',r=>{
+ const u=new URL(r.request().url());return r.fulfill({contentType:'text/html',body:`
Saved ${u.pathname.split('/').at(-1)}
`});
+ });
+ context.on('request',r=>{const path=new URL(r.url()).pathname;if(r.method()==='POST'&&!path.startsWith('/hubs/')&&path!=='/NarrativeFocus/Shared/Validate')writes.push(path);if(path.startsWith('/SpatialContext/')||path.includes('/Context/Tabs/'))reads.push({page:r.frame().page(),path});});
+ const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));
+ const tab=(p,i,value)=>p.selectOption(`[data-context-pane="${i}"] [data-context-tab]`,value);
+ const stable=()=>page.waitForTimeout(250);
+ const notify=(p,hints)=>p.evaluate(hints=>{for(const hint of hints)document.querySelector('[data-context-workspace]').contextController.invalidate(hint);},hints);
+ const hint=kind=>({projectId:7,bookId:12,kind,entityId:1});
+ await page.goto(base+'/Writing/Context?pinned=true');await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').waitFor();
+ await page.selectOption('[data-context-layout]','columns');await tab(page,1,'maps');await page.locator('iframe').waitFor();await stable();
+ const before=await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position}));
+ step='map bursts only refresh map, one state read';reads.length=0;
+ await notify(page,Array.from({length:8},()=>hint('maps')));await stable();
+ assert.equal(reads.filter(r=>r.path.includes('/Tabs/')).length,0);
+ assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
+ step='scope isolation';reads.length=0;
+ await notify(page,[{...hint('maps'),projectId:8},{...hint('maps'),bookId:13}]);await stable();assert.equal(reads.length,0);
+ step='unrelated dates do not refresh spatial pane';reads.length=0;
+ await notify(page,[hint('dates')]);await stable();assert.equal(reads.filter(r=>r.path.startsWith('/SpatialContext/')).length,0);assert.equal(reads.filter(r=>r.path.toLowerCase().includes('/tabs/overview')).length,1);
+ step='hidden panel deferred until shown';await tab(page,1,'characters');await stable();reads.length=0;
+ await notify(page,[hint('maps')]);await stable();assert.equal(reads.length,0);
+ await tab(page,1,'maps');await stable();assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
+ step='two visible map panes share state read';await tab(page,0,'maps');await page.locator('[data-context-pane="0"] iframe').waitFor();await stable();reads.length=0;
+ await notify(page,[hint('maps'),hint('maps')]);await stable();assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
+ step='separate windows independently refresh while held';const second=await context.newPage();second.on('pageerror',e=>errors.push(e.message));await second.goto(base+'/Writing/Context?pinned=true');await tab(second,0,'locations');await second.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await stable();reads.length=0;
+ await Promise.all([notify(page,[hint('locations')]),notify(second,[hint('locations')])]);await stable();
+ assert.equal(reads.filter(r=>r.path==='/SpatialContext/State'&&r.page===page).length,1);
+ assert.equal(reads.filter(r=>r.path==='/SpatialContext/State'&&r.page===second).length,1);
+ assert.deepEqual(await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),before);
+ assert.deepEqual(writes,[],'passive refresh never posts a manuscript/Word navigation');assert.deepEqual(errors,[]);
+ console.log('PASS saved-data refresh: category targeting, burst coalescing, project/book isolation, deferred hidden panels, shared split reads, independent held windows, no narrative writes.');
+ }catch(e){console.error('FAIL '+step,e);process.exitCode=1;}finally{await browser.close();}
+})();
diff --git a/PlotLine.Tests/ContextSavedDataTests.cs b/PlotLine.Tests/ContextSavedDataTests.cs
new file mode 100644
index 00000000..536676b9
--- /dev/null
+++ b/PlotLine.Tests/ContextSavedDataTests.cs
@@ -0,0 +1,65 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Abstractions;
+using Microsoft.AspNetCore.Mvc.Filters;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.AspNetCore.SignalR;
+using Microsoft.Extensions.Logging.Abstractions;
+using PlotLine.Hubs;
+using PlotLine.Services;
+using System.Text.Json;
+
+internal static class ContextSavedDataTests
+{
+ public static async Task Run()
+ {
+ var packets = new List();
+ var client = NativeWorkflowTests.Proxy((_, args) =>
+ {
+ if ((string)args![0]! != "ContextInvalidated") throw new Exception("Saved data must not change manuscript position.");
+ packets.Add(JsonSerializer.Serialize(((object?[])args[1]!)[0]));
+ return Task.CompletedTask;
+ });
+ var clients = NativeWorkflowTests.Proxy((_, args) =>
+ {
+ if ((string)args![0]! != NativeCompanionPresenceHub.UserGroup(7)) throw new Exception("Wrong account group.");
+ return client;
+ });
+ var hub = NativeWorkflowTests.Proxy>((_, _) => clients);
+ var accessor = new HttpContextAccessor();
+ var notices = new ContextWorkspaceNotifications(hub, NullLogger.Instance, accessor);
+ var filter = new ContextReferenceInvalidationFilter(notices);
+ foreach (var outcome in new[] { "preview", "saved", "badrequest", "invalid", "response400", "exception" })
+ {
+ accessor.HttpContext = new DefaultHttpContext();
+ var action = new ActionContext(accessor.HttpContext, new RouteData(), new ActionDescriptor());
+ var filters = new List();
+ var controller = new object();
+ var executing = new ActionExecutingContext(action, filters, new Dictionary(), controller);
+ var before = packets.Count;
+ await filter.OnActionExecutionAsync(executing, async () =>
+ {
+ if (outcome != "preview")
+ {
+ await notices.Invalidate(7, bookId:12, projectId:3, kind:"maps", entityId:44, entityType:"Map");
+ await notices.Invalidate(7, bookId:12, projectId:3, kind:"maps", entityId:44, entityType:"Map");
+ if (packets.Count != before) throw new Exception("Hint escaped before action completed.");
+ }
+ if (outcome == "invalid") action.ModelState.AddModelError("Name", "Invalid");
+ if (outcome == "response400") accessor.HttpContext.Response.StatusCode = 400;
+ return new ActionExecutedContext(action, filters, controller)
+ {
+ Result = outcome == "badrequest" ? new BadRequestResult() : new JsonResult(new { saved = true }),
+ Exception = outcome == "exception" ? new InvalidOperationException("Synthetic failed save") : null
+ };
+ });
+ if (packets.Count - before != (outcome == "saved" ? 1 : 0)) throw new Exception("Save/failed/preview notification boundary: " + outcome);
+ }
+ using var json = JsonDocument.Parse(packets.Single());
+ var hint = json.RootElement;
+ if (hint.GetProperty("projectId").GetInt32()!=3 || hint.GetProperty("bookId").GetInt32()!=12 ||
+ hint.GetProperty("kind").GetString()!="maps" || hint.GetProperty("entityId").GetInt32()!=44 ||
+ hint.EnumerateObject().Count()!=7) throw new Exception("Hints must contain scoped identifiers only.");
+ accessor.HttpContext = null;
+ }
+}
diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs
index 82552f59..d98e9ec9 100644
--- a/PlotLine.Tests/Program.cs
+++ b/PlotLine.Tests/Program.cs
@@ -217,6 +217,7 @@ if(args.Contains("--discretionary-ai")){await DiscretionaryAiTests.Run();return;
if(args.Contains("--context-names")){await ContextNamesTests.Run();return;}
if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;}
if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;}
+if(args.Contains("--context-saved-data")){await ContextSavedDataTests.Run();return;}
if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();return;}
@@ -239,6 +240,7 @@ var tests = new (string Name, Action Test)[]
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
+ ("Context committed-save notifications and scope",()=>ContextSavedDataTests.Run().GetAwaiter().GetResult()),
("Context main-page navigation safety and delegated link coverage",ContextWorkspaceNavigationTests.Run),
("Bounded opt-in shared focus diagnostics",SharedFocusDiagnosticsTests.Run),
("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run),
diff --git a/PlotLine/Controllers/ChaptersController.cs b/PlotLine/Controllers/ChaptersController.cs
index 5b102767..4fede3fe 100644
--- a/PlotLine/Controllers/ChaptersController.cs
+++ b/PlotLine/Controllers/ChaptersController.cs
@@ -6,7 +6,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class ChaptersController(IChapterService chapters) : Controller
+public sealed class ChaptersController(IChapterService chapters, ContextSavedData savedData) : Controller
{
public async Task Details(int id)
{
@@ -41,6 +41,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
try
{
chapterId = await chapters.SaveAsync(model);
+ await savedData.Chapter(chapterId);
}
catch (SubscriptionLimitException ex) when (model.ChapterID == 0)
{
@@ -67,6 +68,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
public async Task SetScenesPov(int chapterId, int? povCharacterId, bool overwriteAuthor)
{
var updated = await chapters.SetScenesPovAsync(chapterId, povCharacterId, overwriteAuthor);
+ if (updated > 0) await savedData.Chapter(chapterId, "characters");
TempData["ChapterMessage"] = $"POV updated on {updated:N0} scene{(updated == 1 ? string.Empty : "s")}.";
return RedirectToAction(nameof(Details), new { id = chapterId });
}
@@ -77,6 +79,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
{
try
{
+ await savedData.Chapter(id);
await chapters.ArchiveAsync(id);
}
catch (InvalidOperationException ex)
diff --git a/PlotLine/Controllers/CharacterAttributesController.cs b/PlotLine/Controllers/CharacterAttributesController.cs
index d6c74f94..756fc4bb 100644
--- a/PlotLine/Controllers/CharacterAttributesController.cs
+++ b/PlotLine/Controllers/CharacterAttributesController.cs
@@ -71,7 +71,7 @@ public sealed class CharacterAttributesController(IProjectRepository projects,IC
{
var versions=rows.ToDictionary(c=>c.CharacterID,c=>c.UpdatedDate.ToString("O"));
undoToken=protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Protect(JsonSerializer.Serialize(new UndoReceipt(author,projectId,attribute,before.Select(c=>new UndoChange(c.Id,c.Value,c.Sex,versions[c.Id])).ToArray(),DateTime.UtcNow.AddMinutes(10))));
- await notifications.Invalidate(author,projectId:projectId,kind:"characters");
+ foreach(var row in rows) await notifications.Invalidate(author,projectId:projectId,kind:"characters",entityId:row.CharacterID,entityType:"Character");
}
return Json(new {saved=true,characters=rows.Select(CharacterQuickAttributes.Snapshot),undoToken});
}
diff --git a/PlotLine/Controllers/FloorPlansController.cs b/PlotLine/Controllers/FloorPlansController.cs
index 912581d7..ae0d0a94 100644
--- a/PlotLine/Controllers/FloorPlansController.cs
+++ b/PlotLine/Controllers/FloorPlansController.cs
@@ -6,7 +6,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class FloorPlansController(IFloorPlanService floorPlans) : Controller
+public sealed class FloorPlansController(IFloorPlanService floorPlans, ContextSavedData savedData) : Controller
{
public async Task Index(int projectId)
{
@@ -30,6 +30,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var floorPlanId = await floorPlans.SavePlanAsync(model);
+ await savedData.FloorPlan(floorPlanId);
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@@ -50,6 +51,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var floorPlanId = await floorPlans.SavePlanAsync(model);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Floor plan saved.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@@ -62,6 +64,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.SaveLayoutAsync(model);
+ await savedData.FloorPlan(model.FloorPlan.FloorPlanID);
if (isAsyncSave)
{
return Json(new { ok = true, message = "Saved" });
@@ -87,6 +90,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
[ValidateAntiForgeryToken]
public async Task DeletePlan(int id, int projectId)
{
+ await savedData.FloorPlan(id);
await floorPlans.DeletePlanAsync(id);
TempData["FloorPlanMessage"] = "Floor plan deleted.";
return RedirectToAction(nameof(Index), new { projectId });
@@ -99,6 +103,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
await floorPlans.SaveFloorAsync(model);
+ await savedData.FloorPlan(model.FloorPlanID);
TempData["FloorPlanMessage"] = "Floor added.";
}
@@ -110,6 +115,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task DeleteFloor(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.DeleteFloorAsync(floorPlanFloorId);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Floor deleted.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@@ -125,6 +131,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var result = await floorPlans.UploadBackgroundAsync(floorPlanId, floorPlanFloorId, backgroundImage);
+ if (result.Succeeded) await savedData.FloorPlan(floorPlanId);
TempData[result.Succeeded ? "FloorPlanMessage" : "FloorPlanError"] = result.Succeeded
? "Background image uploaded."
: result.ErrorMessage ?? "Background image could not be uploaded.";
@@ -139,6 +146,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.SaveBackgroundSettingsAsync(model);
+ await savedData.FloorPlan(model.FloorPlanID);
if (isAsyncSave)
{
return Json(new { ok = true, message = "Saved" });
@@ -165,6 +173,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task ResetBackground(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.ResetBackgroundAsync(floorPlanId, floorPlanFloorId);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Background position reset.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@@ -174,6 +183,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task RemoveBackground(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.RemoveBackgroundAsync(floorPlanId, floorPlanFloorId);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Background image removed.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@@ -187,6 +197,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
await floorPlans.SaveTransitionAsync(floorPlanId, model);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = model.FloorPlanTransitionID == 0 ? "Transition created." : "Transition updated.";
}
}
@@ -205,6 +216,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.DeleteTransitionAsync(floorPlanId, floorPlanTransitionId);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Transition deleted.";
}
catch (InvalidOperationException ex)
@@ -225,6 +237,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
var floorPlanBlockId = await floorPlans.SaveBlockAsync(model);
+ await savedData.FloorPlan(floorPlanId);
if (isAsyncSave)
{
var block = await floorPlans.GetBlockAsync(floorPlanBlockId);
@@ -288,6 +301,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.LinkBlockLocationAsync(floorPlanId, blockId, roomName);
+ await savedData.FloorPlan(floorPlanId);
return Json(new { ok = true });
}
catch (InvalidOperationException ex)
@@ -301,6 +315,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task DeleteBlock(int floorPlanId, int floorPlanBlockId)
{
await floorPlans.DeleteBlockAsync(floorPlanBlockId);
+ await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Block deleted.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
diff --git a/PlotLine/Controllers/LocationWorkspaceController.cs b/PlotLine/Controllers/LocationWorkspaceController.cs
index 3efbfe1b..0773bea5 100644
--- a/PlotLine/Controllers/LocationWorkspaceController.cs
+++ b/PlotLine/Controllers/LocationWorkspaceController.cs
@@ -115,7 +115,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
UserID = user.UserId, input.Attribute, Changes = JsonSerializer.Serialize(input.Changes), Restore = restore }, commandType: CommandType.StoredProcedure)).ToArray();
string? undoToken = previous.Length == 0 ? null : Protector.Protect(JsonSerializer.Serialize(new Receipt(user.UserId!.Value,
input.ProjectId, input.Attribute, previous, DateTime.UtcNow.AddMinutes(10))));
- if (previous.Length > 0) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations");
+ foreach (var change in previous) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations", entityId: change.Id, entityType: "Location");
return Json(new { saved = true, undoToken, changes = previous.Select(c => new { c.Id, c.Version, value = input.Attribute == "type" && int.TryParse(input.Changes.Single(i => i.Id == c.Id).Value, out var typeId) ? typeId.ToString() : input.Changes.Single(i => i.Id == c.Id).Value }), attribute = input.Attribute });
}
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
@@ -138,7 +138,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
parameters.Add("SourceVersion", sourceVersion, DbType.DateTime2);
parameters.Add("TargetVersion", targetVersion, DbType.DateTime2);
await db.QuerySingleAsync("dbo.Location_WorkspaceMerge", parameters, commandType: CommandType.StoredProcedure);
- await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
+ await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations", entityId: input.TargetId, entityType: "Location");
return Json(new { id = input.TargetId });
}
catch (SqlException e) when (e.Number is 51000 or 51010 or 51011 or 51012)
@@ -154,7 +154,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
{
using var db = connections.CreateConnection();
var id = await db.QuerySingleAsync("dbo.Location_WorkspaceCreate", new { ProjectID = input.ProjectId, UserID = author, input.Name, ParentID = input.ParentId }, commandType: CommandType.StoredProcedure);
- await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
+ await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations", entityId: id, entityType: "Location");
return Json(new { id });
}
catch (SqlException e) when (e.Number is 51010 or 51012)
diff --git a/PlotLine/Controllers/LocationsController.cs b/PlotLine/Controllers/LocationsController.cs
index 70fb082c..1ec8a321 100644
--- a/PlotLine/Controllers/LocationsController.cs
+++ b/PlotLine/Controllers/LocationsController.cs
@@ -7,7 +7,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser) : Controller
+public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser, ContextSavedData savedData) : Controller
{
public async Task Index(int projectId)
{
@@ -77,6 +77,7 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
try
{
await locations.ReparentAsync(projectId, locationId, parentLocationId, expectedParentLocationId);
+ await savedData.Project(projectId, "locations", locationId, "Location");
TempData["GeographyMessage"] = await geography.SubmitAsync(projectId, locationId);
if (IsAjaxRequest())
{
@@ -198,7 +199,9 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
[ValidateAntiForgeryToken]
public async Task ArchiveRelationship(int id, int returnLocationId)
{
+ var location = await locations.GetEditAsync(returnLocationId);
await locations.ArchiveRelationshipAsync(id);
+ if (location is not null) await savedData.Project(location.ProjectID, "locations", id, "Location Relationship");
TempData["ArchiveMessage"] = "Location relationship archived.";
return RedirectToAction(nameof(Details), new { id = returnLocationId });
}
diff --git a/PlotLine/Controllers/MapsController.cs b/PlotLine/Controllers/MapsController.cs
index 8b7673c9..1149e03c 100644
--- a/PlotLine/Controllers/MapsController.cs
+++ b/PlotLine/Controllers/MapsController.cs
@@ -8,7 +8,7 @@ namespace PlotLine.Controllers;
[Authorize]
public sealed class MapsController(MapRepository maps, IProjectRepository projects, ILocationRepository locations,
- IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller
+ IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser, ContextSavedData? savedData = null) : Controller
{
private int UserID => currentUser.UserId!.Value;
public async Task Index(int projectId, int? id, bool detached = false, Guid? featureId = null)
@@ -37,7 +37,9 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
{
if (!await access.CanAccessProjectAsync(model.ProjectID)) return NotFound();
if (!ModelState.IsValid || !MapValidation.Kinds.Contains(model.Kind)) return BadRequest("Choose a map name and kind.");
- try { return Json(new { id = await maps.CreateAsync(model, UserID) }); }
+ try { var id = await maps.CreateAsync(model, UserID);
+ if (savedData is not null) await savedData.Project(model.ProjectID, "maps", id, "Map");
+ return Json(new { id }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
[HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(8_000_000)]
@@ -51,7 +53,12 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
try
{
await maps.SaveAsync(document, UserID);
- return Json(await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID));
+ if (savedData is not null) await savedData.Project(document.Map.ProjectID, "maps", document.Map.MapID, "Map");
+ var saved = await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID);
+ if (savedData is not null && saved is not null)
+ foreach (var feature in saved.Features.Where(f => f.LocationID.HasValue && document.Features.Any(before => before.FeatureID == f.FeatureID && before.CreateLocation)))
+ await savedData.Project(document.Map.ProjectID, "locations", feature.LocationID, "Location");
+ return Json(saved);
}
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
@@ -59,7 +66,8 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
public async Task Delete(int projectId, int id, int revision)
{
if (!await access.CanAccessProjectAsync(projectId)) return NotFound();
- try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); }
+ try { await maps.DeleteAsync(projectId, id, revision, UserID);
+ if (savedData is not null) await savedData.Project(projectId, "maps", id, "Map"); return Json(new { ok = true }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
[HttpGet]
@@ -77,7 +85,8 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
if (!ModelState.IsValid || note is null || note.TravelMethod?.Length > 80 || note.TypicalMinutes is < 1 or > 525600) return BadRequest(new { message = "Check journey annotations." });
var projection = await story.GetAsync(projectId, note.MapID, UserID, scenarioId);
if (projection is null || !projection.Legs.Any(l => l.CharacterID == note.CharacterID && l.FromSceneID == note.FromSceneID && l.ToSceneID == note.ToSceneID)) return NotFound();
- try { await repository.SaveJourneyAsync(projectId, UserID, note); return Json(new { ok = true }); }
+ try { await repository.SaveJourneyAsync(projectId, UserID, note);
+ if (savedData is not null) await savedData.Project(projectId, "maps", note.MapID, "Map"); return Json(new { ok = true }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
diff --git a/PlotLine/Controllers/RelationshipMapController.cs b/PlotLine/Controllers/RelationshipMapController.cs
index 59f41b8e..b0e9b96b 100644
--- a/PlotLine/Controllers/RelationshipMapController.cs
+++ b/PlotLine/Controllers/RelationshipMapController.cs
@@ -8,7 +8,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications) : Controller
+public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications, ContextSavedData? savedData = null) : Controller
{
public async Task Index(int projectId, int? bookId, int? chapterId, int? sceneId, int? focusCharacterId, bool showFullNetwork = false)
{
@@ -120,7 +120,8 @@ public sealed class RelationshipMapController(IRelationshipMapService relationsh
InitialIntensity = model.Intensity, IsReciprocal = model.Mutual, ReaderInitiallyKnows = model.Known, Notes = model.Notes
});
}
- if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships");
+ if (model.SceneID is int scene && savedData is not null) await savedData.Scene(scene, "relationships");
+ else if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships", entityId: existing?.CharacterRelationshipID ?? model.SourceID, entityType: existing is null ? "Character" : "Relationship");
return Ok();
}
}
diff --git a/PlotLine/Controllers/ScenesController.cs b/PlotLine/Controllers/ScenesController.cs
index 31c52514..2d64937d 100644
--- a/PlotLine/Controllers/ScenesController.cs
+++ b/PlotLine/Controllers/ScenesController.cs
@@ -20,7 +20,7 @@ public sealed class ScenesController(
IUploadStorageService uploadStorage,
ICompositeViewEngine viewEngine,
SharedManuscriptFocus? sharedFocus = null,
- ICurrentUserService? currentUser = null) : Controller
+ ICurrentUserService? currentUser = null, ContextSavedData? savedData = null) : Controller
{
private const long MaxAttachmentBytes = 25 * 1024 * 1024;
@@ -58,6 +58,7 @@ public sealed class ScenesController(
try
{
sceneId = await scenes.SaveAsync(model);
+ if (savedData is not null) await savedData.Scene(sceneId, "structure");
}
catch (SubscriptionLimitException ex) when (model.SceneID == 0)
{
@@ -271,6 +272,16 @@ public sealed class ScenesController(
return NotFound();
}
+ var changedKinds = new HashSet();
+ if (current.SceneNumber != model.SceneNumber || current.SceneTitle != model.SceneTitle) changedKinds.Add("structure");
+ if (current.Summary != model.Summary || current.RevisionStatusID != model.RevisionStatusID) changedKinds.Add("overview");
+ if (current.PrimaryLocationID != model.PrimaryLocationID) changedKinds.Add("locations");
+ if (current.POVCharacterID != model.POVCharacterID) changedKinds.Add("characters");
+ if (current.TimeModeID != model.TimeModeID || current.TimeConfidenceID != model.TimeConfidenceID ||
+ current.StartDateTime != model.StartDateTime || current.EndDateTime != model.EndDateTime ||
+ current.DurationAmount != model.DurationAmount || current.DurationUnitID != model.DurationUnitID ||
+ current.RelativeTimeText != model.RelativeTimeText) changedKinds.Add("dates");
+
current.SceneNumber = model.SceneNumber;
current.SceneTitle = model.SceneTitle;
current.RevisionStatusID = model.RevisionStatusID;
@@ -286,6 +297,7 @@ public sealed class ScenesController(
await scenes.SaveAsync(current);
await scenes.UpdatePovCharacterAsync(model.SceneID, model.POVCharacterID);
+ if (savedData is not null) foreach (var kind in changedKinds) await savedData.Scene(model.SceneID, kind);
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -328,6 +340,7 @@ public sealed class ScenesController(
current.SceneOutcomeNotes = model.SceneOutcomeNotes;
await scenes.SaveAsync(current);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "intent");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -366,6 +379,7 @@ public sealed class ScenesController(
}
await scenes.SaveAsync(current);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "metrics");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -424,6 +438,7 @@ public sealed class ScenesController(
if (row.Remove)
{
await characters.DeleteSceneCharacterAsync(row.SceneCharacterID);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
continue;
}
@@ -443,6 +458,7 @@ public sealed class ScenesController(
EmotionalState = row.EmotionalState,
KnowledgeNotes = row.KnowledgeNotes
});
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
if (addCharacterId > 0)
@@ -452,6 +468,7 @@ public sealed class ScenesController(
model.NewCharacter.ReturnProjectID = current.ReturnProjectID;
model.NewCharacter.ReturnBookID = current.ReturnBookID;
await characters.AddSceneCharacterAsync(model.NewCharacter);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
var updatedBeforePov = await scenes.GetEditAsync(model.SceneID);
@@ -467,6 +484,7 @@ public sealed class ScenesController(
}
await scenes.UpdatePovCharacterAsync(model.SceneID, model.POVCharacterID);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -510,6 +528,7 @@ public sealed class ScenesController(
current.PrimaryLocationID = model.PrimaryLocationID;
await scenes.SaveAsync(current);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "locations");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -582,6 +601,7 @@ public sealed class ScenesController(
if (row.Remove)
{
await assets.DeleteAssetEventAsync(row.AssetEventID);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
}
}
@@ -593,6 +613,7 @@ public sealed class ScenesController(
model.NewAssetEvent.ReturnProjectID = current.ReturnProjectID;
model.NewAssetEvent.ReturnBookID = current.ReturnBookID;
await assets.AddAssetEventAsync(model.NewAssetEvent);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@@ -642,6 +663,7 @@ public sealed class ScenesController(
if (note.Remove)
{
await writerWorkspace.DeleteNoteAsync(note.SceneNoteID);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
continue;
}
@@ -667,6 +689,7 @@ public sealed class ScenesController(
IsPinned = note.IsPinned,
IsResolved = note.IsResolved
});
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var hasNewNoteContent = !string.IsNullOrWhiteSpace(model.NewNote.NoteTitle)
@@ -685,6 +708,7 @@ public sealed class ScenesController(
model.NewNote.SceneID = model.SceneID;
await writerWorkspace.SaveNoteAsync(model.NewNote);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@@ -729,6 +753,7 @@ public sealed class ScenesController(
if (item.Remove)
{
await writerWorkspace.DeleteChecklistItemAsync(item.SceneChecklistItemID);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
continue;
}
@@ -746,12 +771,14 @@ public sealed class ScenesController(
IsCompleted = item.IsCompleted,
SortOrder = item.SortOrder
});
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
if (!string.IsNullOrWhiteSpace(model.NewChecklistItem.ItemText))
{
model.NewChecklistItem.SceneID = model.SceneID;
await writerWorkspace.SaveChecklistItemAsync(model.NewChecklistItem);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@@ -786,6 +813,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveSceneWorkflowAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@@ -816,6 +844,7 @@ public sealed class ScenesController(
try
{
await scenes.ArchiveAsync(id);
+ if (savedData is not null) await savedData.Chapter(chapterId, "structure");
}
catch (InvalidOperationException ex)
{
@@ -837,6 +866,7 @@ public sealed class ScenesController(
public async Task MoveUp(int id, int chapterId)
{
await scenes.MoveAsync(id, "Up");
+ if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return RedirectToAction("Details", "Chapters", new { id = chapterId });
}
@@ -845,6 +875,7 @@ public sealed class ScenesController(
public async Task MoveDown(int id, int chapterId)
{
await scenes.MoveAsync(id, "Down");
+ if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return RedirectToAction("Details", "Chapters", new { id = chapterId });
}
@@ -855,6 +886,7 @@ public sealed class ScenesController(
try
{
await plots.AddThreadEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "threads");
}
catch (InvalidOperationException ex)
{
@@ -881,6 +913,7 @@ public sealed class ScenesController(
try
{
await plots.UpdateThreadEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "threads");
}
catch (InvalidOperationException ex)
{
@@ -905,6 +938,7 @@ public sealed class ScenesController(
public async Task DeleteThreadEvent(int id, int sceneId, int? projectId, int? bookId)
{
await plots.DeleteThreadEventAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "threads");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(sceneId);
@@ -918,6 +952,7 @@ public sealed class ScenesController(
public async Task AddAssetEvent(AssetEventCreateViewModel model)
{
await assets.AddAssetEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -926,6 +961,7 @@ public sealed class ScenesController(
public async Task DeleteAssetEvent(int id, int sceneId, int? projectId, int? bookId)
{
await assets.DeleteAssetEventAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "assets");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -934,6 +970,7 @@ public sealed class ScenesController(
public async Task AddAssetCustodyEvent(AssetCustodyCreateViewModel model)
{
await assets.AddCustodyEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -942,6 +979,7 @@ public sealed class ScenesController(
public async Task AddSceneAssetLocation(SceneAssetLocationCreateViewModel model)
{
await locations.SaveSceneAssetLocationAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "locations");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -950,6 +988,7 @@ public sealed class ScenesController(
public async Task DeleteSceneAssetLocation(int id, int sceneId, int? projectId, int? bookId)
{
await locations.DeleteSceneAssetLocationAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "locations");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -958,6 +997,7 @@ public sealed class ScenesController(
public async Task DeleteAssetCustodyEvent(int id, int sceneId, int? projectId, int? bookId)
{
await assets.DeleteCustodyEventAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "assets");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -968,6 +1008,7 @@ public sealed class ScenesController(
try
{
await characters.AddSceneCharacterAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
catch (InvalidOperationException ex)
{
@@ -982,6 +1023,7 @@ public sealed class ScenesController(
public async Task UpdateSceneCharacter(SceneCharacterEditViewModel model)
{
await characters.UpdateSceneCharacterAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -990,6 +1032,7 @@ public sealed class ScenesController(
public async Task DeleteSceneCharacter(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteSceneCharacterAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "characters");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -1000,6 +1043,7 @@ public sealed class ScenesController(
try
{
await characters.AcceptSceneCharacterSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: false);
@@ -1025,6 +1069,7 @@ public sealed class ScenesController(
try
{
await characters.RejectSceneCharacterSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: false);
@@ -1050,6 +1095,7 @@ public sealed class ScenesController(
try
{
await assets.AcceptSceneAssetSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "assets");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@@ -1075,6 +1121,7 @@ public sealed class ScenesController(
try
{
await assets.RejectSceneAssetSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "assets");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@@ -1100,6 +1147,7 @@ public sealed class ScenesController(
try
{
await locations.AcceptSceneLocationSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "locations");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@@ -1125,6 +1173,7 @@ public sealed class ScenesController(
try
{
await locations.RejectSceneLocationSuggestionAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "locations");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@@ -1148,6 +1197,7 @@ public sealed class ScenesController(
public async Task AddSceneDependency(SceneDependencyCreateViewModel model)
{
await scenes.AddDependencyAsync(model);
+ if (savedData is not null) await savedData.Scene(model.CurrentSceneID, "structure");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(model.CurrentSceneID);
@@ -1161,6 +1211,7 @@ public sealed class ScenesController(
public async Task DeleteSceneDependency(int id, int sceneId, int? projectId, int? bookId)
{
await scenes.DeleteDependencyAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "structure");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(sceneId);
@@ -1183,6 +1234,7 @@ public sealed class ScenesController(
public async Task ConfirmMove(SceneMoveRequestViewModel model)
{
await scenes.MoveToChapterAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
if (TryGetLocalReturnUrl(model.ReturnUrl, out var returnUrl))
{
return LocalRedirect(returnUrl);
@@ -1196,6 +1248,7 @@ public sealed class ScenesController(
public async Task RenumberChapter(int chapterId, int? projectId, int? bookId, int? sceneId)
{
await scenes.RenumberChapterAsync(chapterId);
+ if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return sceneId.HasValue
? RedirectForScene(sceneId.Value, projectId, bookId)
: RedirectToAction("Details", "Chapters", new { id = chapterId });
@@ -1244,6 +1297,7 @@ public sealed class ScenesController(
}
await characters.AddAttributeEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneCharacterAttributesRefreshJsonAsync(model.SceneID);
@@ -1277,6 +1331,7 @@ public sealed class ScenesController(
}
await characters.UpdateAttributeEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneCharacterAttributesRefreshJsonAsync(model.SceneID);
@@ -1290,6 +1345,7 @@ public sealed class ScenesController(
public async Task AddCharacterKnowledge(CharacterKnowledgeCreateViewModel model)
{
await characters.AddKnowledgeAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(model.SceneID);
@@ -1303,6 +1359,7 @@ public sealed class ScenesController(
public async Task UpdateCharacterKnowledge(CharacterKnowledgeCreateViewModel model)
{
await characters.UpdateKnowledgeAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(model.SceneID);
@@ -1316,6 +1373,7 @@ public sealed class ScenesController(
public async Task DeleteCharacterKnowledge(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteKnowledgeAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(sceneId);
@@ -1331,6 +1389,7 @@ public sealed class ScenesController(
try
{
await characters.AddRelationshipEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "relationships");
}
catch (InvalidOperationException ex)
{
@@ -1355,6 +1414,7 @@ public sealed class ScenesController(
public async Task UpdateRelationshipEvent(RelationshipEventCreateViewModel model)
{
await characters.UpdateRelationshipEventAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "relationships");
if (IsAjaxRequest())
{
return await ScenePeopleContinuityRefreshJsonAsync(model.SceneID);
@@ -1368,6 +1428,7 @@ public sealed class ScenesController(
public async Task DeleteRelationshipEvent(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteRelationshipEventAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "relationships");
if (IsAjaxRequest())
{
return await ScenePeopleContinuityRefreshJsonAsync(sceneId);
@@ -1381,6 +1442,7 @@ public sealed class ScenesController(
public async Task SaveWorkflow(SceneWorkflowEditViewModel model)
{
await writerWorkspace.SaveSceneWorkflowAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -1395,6 +1457,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveNoteAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -1403,6 +1466,7 @@ public sealed class ScenesController(
public async Task DeleteNote(int id, int sceneId, int? projectId, int? bookId)
{
await writerWorkspace.DeleteNoteAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "structure");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -1417,6 +1481,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveChecklistItemAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@@ -1425,6 +1490,7 @@ public sealed class ScenesController(
public async Task DeleteChecklistItem(int id, int sceneId, int? projectId, int? bookId)
{
await writerWorkspace.DeleteChecklistItemAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "structure");
return RedirectForScene(sceneId, projectId, bookId);
}
@@ -1497,6 +1563,7 @@ public sealed class ScenesController(
}
var attachmentId = await writerWorkspace.SaveAttachmentAsync(model);
+ if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
if (fileSizeBytes > 0 && !string.IsNullOrWhiteSpace(model.FilePath))
{
await storage.TrackSceneAttachmentAsync(
@@ -1528,6 +1595,7 @@ public sealed class ScenesController(
public async Task DeleteAttachment(int id, int sceneId, int? projectId, int? bookId, string? filePath)
{
await writerWorkspace.DeleteAttachmentAsync(id);
+ if (savedData is not null) await savedData.Scene(sceneId, "structure");
await storage.MarkDeletedByStoragePathAsync(filePath);
uploadStorage.TryDeleteFile(filePath, "uploads/scenes");
if (IsAjaxRequest())
diff --git a/PlotLine/Controllers/TimelineController.cs b/PlotLine/Controllers/TimelineController.cs
index c50f0a1a..5f779dd6 100644
--- a/PlotLine/Controllers/TimelineController.cs
+++ b/PlotLine/Controllers/TimelineController.cs
@@ -7,7 +7,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class TimelineController(ITimelineService timeline) : Controller
+public sealed class TimelineController(ITimelineService timeline, ContextSavedData savedData) : Controller
{
public async Task Index([FromQuery] TimelineFilterViewModel filter)
{
@@ -103,6 +103,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
public async Task DropMoveScene(TimelineSceneDropMoveViewModel model)
{
var summary = await timeline.MoveSceneByDropAsync(model);
+ if (summary is not null) await savedData.Scene(model.SceneID);
if (summary is not null)
{
TempData["TimelineDragMessage"] = $"Scene moved. Validation found {summary.WarningCount} warning{(summary.WarningCount == 1 ? "" : "s")}.";
@@ -115,15 +116,21 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
public async Task DropCharacter(TimelineSceneCharacterDropViewModel model)
{
if (Request.Headers.Accept.ToString().Contains("application/json"))
- return await SaveSceneDropAsync(() => timeline.AddCharacterByDropAsync(model));
- await RunDropActionAsync(() => timeline.AddCharacterByDropAsync(model), "Character added to scene.");
+ return await SaveSceneDropAsync(() => SaveAndNotify(() => timeline.AddCharacterByDropAsync(model), model.SceneID, "characters"));
+ await RunDropActionAsync(() => SaveAndNotify(() => timeline.AddCharacterByDropAsync(model), model.SceneID, "characters"), "Character added to scene.");
return RedirectToAction(nameof(Index), new { projectId = model.ReturnProjectID, bookId = model.ReturnBookID, selectedSceneId = model.SceneID });
}
[HttpPost]
[ValidateAntiForgeryToken]
public Task DropLocation(TimelineSceneLocationDropViewModel model) =>
- SaveSceneDropAsync(() => timeline.AddLocationByDropAsync(model));
+ SaveSceneDropAsync(() => SaveAndNotify(() => timeline.AddLocationByDropAsync(model), model.SceneID, "locations"));
+
+ private async Task SaveAndNotify(Func action, int sceneId, string kind)
+ {
+ await action();
+ await savedData.Scene(sceneId, kind);
+ }
private async Task SaveSceneDropAsync(Func action)
{
@@ -144,7 +151,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
[ValidateAntiForgeryToken]
public async Task DropAssetEvent(TimelineAssetEventDropViewModel model)
{
- await RunDropActionAsync(() => timeline.AddAssetEventByDropAsync(model), "Asset event added to scene.");
+ await RunDropActionAsync(() => SaveAndNotify(() => timeline.AddAssetEventByDropAsync(model), model.SceneID, "assets"), "Asset event added to scene.");
return RedirectToAction(nameof(Index), new { projectId = model.ReturnProjectID, bookId = model.ReturnBookID, selectedSceneId = model.SceneID });
}
@@ -160,7 +167,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
[ValidateAntiForgeryToken]
public async Task DropLocationRelationship(TimelineLocationRelationshipDropViewModel model)
{
- await RunDropActionAsync(() => timeline.AddLocationRelationshipByDropAsync(model), "Location relationship saved.");
+ await RunDropActionAsync(async () => { await timeline.AddLocationRelationshipByDropAsync(model); await savedData.Project(model.ProjectID, "locations", model.FromLocationID, "Location"); }, "Location relationship saved.");
return RedirectToAction(nameof(Index), new { projectId = model.ProjectID, bookId = model.ReturnBookID });
}
diff --git a/PlotLine/Controllers/WriterAuthoringController.cs b/PlotLine/Controllers/WriterAuthoringController.cs
index 475245af..c094971c 100644
--- a/PlotLine/Controllers/WriterAuthoringController.cs
+++ b/PlotLine/Controllers/WriterAuthoringController.cs
@@ -4,16 +4,17 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
using PlotLine.Services.Writer;
+using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize]
-public sealed class WriterAuthoringController(IWriterAuthoringService authoring):Controller
+public sealed class WriterAuthoringController(IWriterAuthoringService authoring, ContextSavedData savedData):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet] public async Task Inspect(int bookId,int chapterId,int? sceneId){Response.Headers.CacheControl="no-store";try{return PartialView("~/Views/Writer/_WriterAuthoring.cshtml",await authoring.Read(Actor,bookId,chapterId,sceneId));}catch(SqlException e)when(e.Number==51000){return NotFound();}catch(KeyNotFoundException){return NotFound();}}
[HttpPost,ValidateAntiForgeryToken]
public async Task Save(int bookId,int chapterId,int? sceneId,string kind,int entityId,string version){
var values=AuthoringSchema.Fields(kind).ToDictionary(f=>f.Name,f=>(string?)Request.Form[f.Name].ToString());
- try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);return Json(new{success=true});}
+ try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);await savedData.Chapter(chapterId, kind is "Chapter" or "Scene" or "Goals" ? "intent" : "structure", sceneId);return Json(new{success=true});}
catch(AuthoringConflictException e){return Conflict(new{message=e.Message});}
catch(KeyNotFoundException){return NotFound();}
catch(ArgumentException e){return BadRequest(new{message=e.Message});}
diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs
index 186764b4..bf97ea4c 100644
--- a/PlotLine/Controllers/WriterController.cs
+++ b/PlotLine/Controllers/WriterController.cs
@@ -12,7 +12,7 @@ namespace PlotLine.Controllers;
public sealed class WriterController(
IWriterWorkspaceService writerWorkspace,
IWritingScheduleService writingSchedule,
- IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null, INarrativeFocus? narrativeFocus=null) : Controller
+ IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null, INarrativeFocus? narrativeFocus=null, ContextSavedData? savedData=null) : Controller
{
public Task Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false)
{
@@ -480,6 +480,7 @@ public sealed class WriterController(
public async Task SaveChapterGoal(ChapterGoalEditViewModel model)
{
await writerWorkspace.SaveChapterGoalAsync(model);
+ if (savedData is not null) await savedData.Chapter(model.ChapterID, "intent");
if (string.Equals(Request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
return Json(new { ok = true });
return RedirectToAction(nameof(Chapter), new { id = model.ChapterID });
diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs
index 7099e79c..d6b41e53 100644
--- a/PlotLine/Program.cs
+++ b/PlotLine/Program.cs
@@ -304,6 +304,7 @@ public class Program
builder.Services.AddSingleton();
builder.Services.Configure>(options => options.MaximumReceiveMessageSize = 16384);
builder.Services.AddSingleton();
+ builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddScoped();
builder.Services.AddScoped();
diff --git a/PlotLine/Services/CharacterWorkspace.cs b/PlotLine/Services/CharacterWorkspace.cs
index 6089bfb7..50d4259e 100644
--- a/PlotLine/Services/CharacterWorkspace.cs
+++ b/PlotLine/Services/CharacterWorkspace.cs
@@ -58,10 +58,10 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR
var frame=await Operation(input.CharacterID,input.RelationshipID,input.EventID,input.Action,ct);if(input.Version!=frame.Version)throw new InvalidOperationException("This relationship or its history changed. Cancel and reopen to review current values.");if(input.Action is "archive" or "event-remove"&&!input.Confirmed)throw new ArgumentException("Confirm the identified removal.");if(input.Notes?.Length>4000||input.Intensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");
if(input.Action.StartsWith("event-")&&frame.Event?.ProtectedSource==true)throw new ArgumentException("This event has source/review dependencies. Manage it through its source workflow.");
try{await reader.Change(input,user.UserId!.Value,ct);}catch(SqlException ex)when(ex.Number==51020){throw new UnauthorizedAccessException();}catch(SqlException ex)when(ex.Number==51021){throw new InvalidOperationException(ex.Message);}catch(SqlException ex)when(ex.Number==51022){throw new ArgumentException(ex.Message);}
- var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");
+ var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships",entityId:input.RelationshipID,entityType:"Relationship");
}
public async Task AddForm(int id,CancellationToken ct,InitialRelationshipEditViewModel? input=null)
{var model=await Header(id,null,ct);if(!model.WorkspaceCanEdit)throw new UnauthorizedAccessException();var lookup=await characters.GetLookupsAsync(model.Project.ProjectID);model.RelationshipTypeOptions=lookup.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray();model.RelationshipStateOptions=lookup.RelationshipStates.Select(t=>new SelectListItem(t.StateName,t.RelationshipStateID.ToString())).ToArray();model.BookOptions=(await books.ListByProjectAsync(model.Project.ProjectID)).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();if(input!=null){model.NewInitialRelationship=input;var target=await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value);if(target?.ProjectID==model.Project.ProjectID)model.CharacterOptions=[new(target.CharacterName,target.CharacterID.ToString())];}return model;}
public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct)
- {var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");}
+ {var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;var relationshipID=await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships",entityId:relationshipID,entityType:"Relationship");}
}
diff --git a/PlotLine/Services/Context/ContextCharacterEditing.cs b/PlotLine/Services/Context/ContextCharacterEditing.cs
index 6ab508b9..1e40f407 100644
--- a/PlotLine/Services/Context/ContextCharacterEditing.cs
+++ b/PlotLine/Services/Context/ContextCharacterEditing.cs
@@ -108,7 +108,7 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
}
await characters.UpdateSceneCharacterAsync(edit);
}
- await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID);
+ await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID,kind:"characters",entityId:input.CharacterID,entityType:"Character");
}finally{mutex.Release();}
}
}
diff --git a/PlotLine/Services/Context/ContextRelationshipEditing.cs b/PlotLine/Services/Context/ContextRelationshipEditing.cs
index db9ec19b..55ec1b66 100644
--- a/PlotLine/Services/Context/ContextRelationshipEditing.cs
+++ b/PlotLine/Services/Context/ContextRelationshipEditing.cs
@@ -57,12 +57,13 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
if(input.Intensity is <1 or >10||input.Notes?.Length>4000)throw new ArgumentException("Intensity must be 1–10 and notes at most 4,000 characters.");
if(r!=null&&(r.CharacterAID!=input.SourceID||r.CharacterBID!=input.TargetID||r.RelationshipTypeID!=input.TypeID||r.IsReciprocal!=input.Mutual))throw new ArgumentException("Use the full Relationships Editor to change the pair, type or direction of an existing relationship.");
if(r==null&&frame.Data.Relationships.Any(x=>!x.IsArchived&&x.RelationshipTypeID==input.TypeID&&((x.CharacterAID==input.SourceID&&x.CharacterBID==input.TargetID)||(x.IsReciprocal&&x.CharacterAID==input.TargetID&&x.CharacterBID==input.SourceID))))throw new ArgumentException("This relationship already exists. Correct its recorded state or use the full editor.");
- if(input.Mode=="initial")await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes});
+ int changedID;
+ if(input.Mode=="initial")changedID=await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes});
else{
var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID};
- if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit);
+ changedID=frame.Event==null?await characters.AddRelationshipEventAsync(edit):await characters.UpdateRelationshipEventAsync(edit);
}
- await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID,kind:"relationships");
+ await notifications.Invalidate(user.UserId!.Value,bookId:input.Mode=="initial"?null:input.BookID,projectId:frame.ProjectID,kind:"relationships",entityId:changedID,entityType:input.Mode=="initial"?"Relationship":"Relationship Event");
}finally{mutex.Release();}
}
}
diff --git a/PlotLine/Services/Context/ContextSpatial.cs b/PlotLine/Services/Context/ContextSpatial.cs
index 8146b821..e85538a6 100644
--- a/PlotLine/Services/Context/ContextSpatial.cs
+++ b/PlotLine/Services/Context/ContextSpatial.cs
@@ -60,14 +60,14 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse
private async Task