From 448f35b5837c50c9ff4766b4fb3391b4fd096c65 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 2 Nov 2026 20:10:00 +0000 Subject: [PATCH] Add Maps Story Mode and evidence-based spatial manuscript projections --- Docs/Maps_Stage1.md | 2 + Docs/Maps_Stage2.md | 83 ++++ .../Browser/maps-story-dev-smoke.cjs | 44 ++ PlotLine.Tests/Browser/maps-story-engine.cjs | 21 + PlotLine.Tests/Browser/maps-story.cjs | 52 +++ PlotLine.Tests/Browser/package.json | 3 +- PlotLine.Tests/MapStoryDevFixture.cs | 45 ++ PlotLine.Tests/MapStoryTests.cs | 106 +++++ PlotLine.Tests/MapTests.cs | 2 +- PlotLine.Tests/Program.cs | 19 + PlotLine.Tests/Sql/210_MapStoryAssertions.sql | 44 ++ PlotLine.Tests/Sql/210_MapStoryFixture.sql | 82 ++++ PlotLine.Tests/ToolbarBrowserHost.cs | 8 +- PlotLine/Controllers/MapsController.cs | 19 + PlotLine/Data/MapStoryRepository.cs | 33 ++ PlotLine/Data/ProjectBackupRepository.cs | 2 + PlotLine/Models/MapStoryModels.cs | 100 +++++ PlotLine/Models/ProjectBackupModels.cs | 1 + PlotLine/Program.cs | 2 + PlotLine/Services/MapStoryService.cs | 172 ++++++++ PlotLine/Sql/210_MapStoryMode.sql | 408 ++++++++++++++++++ .../211_MapJourneyArchivedSceneRestore.sql | 245 +++++++++++ PlotLine/Views/FloorPlans/Edit.cshtml | 7 + PlotLine/Views/Maps/Index.cshtml | 17 +- PlotLine/wwwroot/css/maps-workspace.css | 3 + .../wwwroot/js/application-page-context.js | 2 +- PlotLine/wwwroot/js/maps-story-engine.js | 35 ++ PlotLine/wwwroot/js/maps-story.js | 170 ++++++++ PlotLine/wwwroot/js/maps-workspace.js | 16 +- 29 files changed, 1729 insertions(+), 14 deletions(-) create mode 100644 Docs/Maps_Stage2.md create mode 100644 PlotLine.Tests/Browser/maps-story-dev-smoke.cjs create mode 100644 PlotLine.Tests/Browser/maps-story-engine.cjs create mode 100644 PlotLine.Tests/Browser/maps-story.cjs create mode 100644 PlotLine.Tests/MapStoryDevFixture.cs create mode 100644 PlotLine.Tests/MapStoryTests.cs create mode 100644 PlotLine.Tests/Sql/210_MapStoryAssertions.sql create mode 100644 PlotLine.Tests/Sql/210_MapStoryFixture.sql create mode 100644 PlotLine/Data/MapStoryRepository.cs create mode 100644 PlotLine/Models/MapStoryModels.cs create mode 100644 PlotLine/Services/MapStoryService.cs create mode 100644 PlotLine/Sql/210_MapStoryMode.sql create mode 100644 PlotLine/Sql/211_MapJourneyArchivedSceneRestore.sql create mode 100644 PlotLine/wwwroot/js/maps-story-engine.js create mode 100644 PlotLine/wwwroot/js/maps-story.js diff --git a/Docs/Maps_Stage1.md b/Docs/Maps_Stage1.md index 68e26e9c..a78c5577 100644 --- a/Docs/Maps_Stage1.md +++ b/Docs/Maps_Stage1.md @@ -1,5 +1,7 @@ # Maps Stage 1 +This records the Stage 1 baseline. Story Mode is now extended by [Maps Stage 2](Maps_Stage2.md). + Maps is a project-scoped spatial writing workspace. The direct `/Maps` address offers your active projects; it never selects another author’s project. Open **World → Maps**, choose a map, or create one. The project selector supplies `projectId` to `/Maps`; selected maps add `id`. ## Author workflows diff --git a/Docs/Maps_Stage2.md b/Docs/Maps_Stage2.md new file mode 100644 index 00000000..6da74672 --- /dev/null +++ b/Docs/Maps_Stage2.md @@ -0,0 +1,83 @@ +# Maps Stage 2: Story geography + +Development entry: https://dev.plotdirector.com/Maps. Choose a project and map, then Story. Geography, map revision, and dirty state do not change during Story navigation. Unsaved Create edits must be saved or undone before loading a canonical Story projection; Story never saves them implicitly. + +## Lenses and navigation + +- **Overview:** restrained per-feature scene counts, geographical concentration, and neutral unused canonical Location details. No scene-marker flood. Terrain without a canonical Location is not judged as unused story geography. +- **Scene:** searchable scene selection, previous/next in canonical manuscript order, chapter/book context, summary, characters, Plot Lines, Location resolution, and direct existing Scene editor links. Missing Location, unmapped Location, and activity on another map level are distinct states. Navigation focuses the map calmly without animation. +- **Character:** up to three compared characters, letters A/B/C, different line patterns, numbered stops, and an ordered textual journey. A → B → A retains both visits. Repeated connections aggregate their drawn lines; individual movements remain inspectable in Details. Unknown/unmapped stops break drawn connections. A journey line is story movement, never a claim of a straight route, physical scale, or use of a nearby road. +- **Chapter:** geographical footprint, counts, scene sequence and navigation, including unmapped/no-Location scenes. +- **Plot Line:** union of up to three selected canonical Plot Lines, counts/concentration, scenes, and honest gaps. Membership comes from `IPlotLineWorkspaceRepository` contributions, not a competing definition. Unrelated mapped places fade while geographical context remains. +- **Time:** confirmed dated events with previous/next dated-event navigation. Shows **Last known**, never “currently here”. Unknown latest evidence does not fall back to an older mapped Location. Unmapped last-known Locations stay unmapped. No interpolation occurs between scenes. Date-only events do not gain clock precision; ambiguous positions within a day or at the same timestamp remain unknown. Undated, estimated or implied times do not create confirmed time positions. Up to eight significant characters get default markers; the textual list covers everyone, or selected characters can narrow the view. + +Book scope and alternative Scenario order are available. Scenario scene order and proposed chapter assignment come from the same Plot Lines Workspace projection. Scene/map links preserve selected scene and Scenario context. The manuscript editor, Timeline and Plot Lines Workspace remain their canonical editors; Maps adds none of those editing systems. + +## Location and hierarchy evidence + +Canonical Location IDs are the join. Map aliases and coincident names do not establish associations. The resolver first uses exact placed representations on the current map, then explicit canonical Location ancestors. Descendant maps can aggregate activity through their explicit parent-feature links. Exact detail-map destinations remain discoverable. Ancestor-only representations provide navigation to that map, without inventing a position on the current canvas. Provisional pieces stay identified as planning geography. + +Location Details include scene counts, description where recorded, chapter count, characters, Plot Lines, first/last scoped appearances, scene links, detail-map links and Floor Plans. Unmapped/no-Location inspection is in Details. “Place this Location in Create” starts an explicit placement interaction; it does not automatically place or create anything. + +Scene events use restrained generic scene markers. No battle/death/clue classification is inferred from prose or titles. + +## Character and timing evidence + +Physical-presence catalogue values allow scene Location fallback. Explicit character Location/exit Location takes precedence. Mentioned-only and off-screen membership is not physical-position evidence; unknown presence does not inherit a scene Location. Explicit exit Locations use a confirmed scene end timestamp, and never acquire a scene-start timestamp when an end time is absent. + +Travel context has these levels: + +0. No explicit spatial relationship: no distance/time inference. +1. Explicit relative direction/distance: contextual only. +2. Explicit measured distance/unit: distance context only. +3. An explicit typical duration plus confirmed exact appearance timestamps at exact, established endpoints: a possible timing observation when elapsed time is shorter. + +Canonical ancestor aggregation, provisional geography, unknown endpoints, date-only/estimated times and negative elapsed intervals do not support strong timing observations. Canvas spacing, relative categories, routes and transport methods never establish speed or measured distance. + +Stage 1 textual durations are parsed only when wholly expressed in supported numeric hours/minutes syntax, e.g. `3h 30m`, `2 hours` or `90 minutes`. Vague/descriptive prose stays context. A leg can instead hold an explicit numeric typical duration in minutes. Wording is **Possible travel timing to review**, with evidence and originating/destination scene links. The author may have intended portals, unusual transport or off-page movement. Observations are quiet until requested. + +A leg can explicitly associate one existing path and an optional descriptive method (Walk/Horse/Car/Train/Boat/Air/custom). These annotations are shared author data, independent of geography revisions. Emptying all fields clears them. No route is chosen automatically. A normal geography save retains the association; removing the referenced path detaches it while preserving method/duration. + +## Floor Plans + +A canonical Scene → Floor Plan association opens the existing occupancy view at that scene and its initial floor. The Floor Plan uses its existing scene selector/occupancy code, not a new interior renderer. A back link restores map Story/scene/Scenario context. A merely linked Floor Plan remains discoverable but does not falsely place an unrelated scene inside it. No Floor Plan geometry or occupancy facts are modified by navigation. + +## Architecture, persistence and permissions + +`StoryMap_Story` returns batched canonical scenes ordered by `NarrativeSceneOrder`, characters, appearances, Locations, map hierarchy/features/relationships and Floor Plans. `MapStoryComposer` builds cached ID/hierarchy resolution, ordered stops, legs and evidence. `MapStoryService` uses three repository calls (source, canonical Plot Lines projection, Scenario choices), independent of marker/scene count, plus access checks. No story facts are copied into map tables. + +`maps-story-engine.js` supplies pure filtering, density and last-known projections. `maps-story.js` owns a keyed SVG Story layer above Stage 1 geography, progressive ribbon controls and the existing Details pane. Selection updates do not rebuild the base SVG or geography nodes. Density and grouped connections avoid rendering one geography marker per appearance. Last-known comparisons use author wall-clock values rather than converting story chronology to browser time zones. + +Migrations are `210_MapStoryMode.sql` and `211_MapJourneyArchivedSceneRestore.sql`. The latter preserves annotations for archived canonical scenes during restore. Migration 210 adds only `MapJourneyNotes` and related procedures/cleanup. The table is keyed by map/character/from-scene/to-scene; no duplicate Scene/Character/Location/Plot Line tables exist. Stored procedures validate project membership and route/appearance ownership. Scene/Character deletion cleans annotations without introducing conflicting SQL Server cascade paths. Project/map deletion and JSON backup/restore include annotations. Restores validate project boundaries; the existing geography revision invalidation remains intact. + +Controller authorization and project access checks apply to every endpoint; stored procedures repeat the check. Journey writes also require antiforgery and the existing shared subscription edit enforcement. Metadata does not update `StoryMaps.Revision`. Reading/filtering/navigating Story is not a write. + +Last lens, compared characters/Plot Lines and Story layer visibility are browser-local per-user/per-project/per-map preferences. They are presentation preferences, not manuscript facts. Refresh Story reloads canonical data. Returning via browser history also refreshes a restored Story page. + +## PWA, readability and responsiveness + +Story selectors/actions use existing contextual ribbon forms/commands. Less frequent scope/comparison choices collapse into menus. The native searchable picker handles long PWA selectors. Web mode retains a compact fixed-height Story toolbar. There is no duplicate ribbon inside the canvas. Lens/selection changes keep the canvas and Details layout stable. Story overlays have a visibility control, visible keyboard focus, textual evidence, non-colour sequence/letter/line-pattern distinctions and no animated flights. The Stage 1 working palette remains readable across application themes. Create/Explore remain the same editors/navigation modes. + +## Verification and operational commands + +- `dotnet build PlotLine.slnx` +- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj` +- Focused: `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --maps-story` +- Development SQL: `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --maps-story-database` after migrations 210 and 211. Creates new fixtures inside an outer transaction and rolls them all back; never restores an existing project. +- Browser host: `PD_BROWSER_FIXTURE_URL=http://127.0.0.1:5247 dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host`. +- `npm --prefix PlotLine.Tests/Browser run test:maps-story`; set `PD_MAPS_STORY_TEST_URL` if using another fixture host. +- Stage 1: `PD_MAPS_TEST_URL=http://127.0.0.1:5247 npm --prefix PlotLine.Tests/Browser run test:maps`. +- Authenticated live acceptance: provision a dedicated Development identity through `--dev-browser-identity`; use `--maps-story-dev-fixture `, then `node PlotLine.Tests/Browser/maps-story-dev-smoke.cjs `. The helper verifies Development and makes a copy-only backup before provisioning. Clean up through the dedicated identity's normal account-deletion workflow. Do not use a real author's project for fixture writes. + +Coverage includes ID-only matching, honest gaps, hierarchy/Floor Plans, canonical and Scenario ordering, repeated visits, character-specific Locations, mention/unknown semantics, evidence thresholds, exit timestamps, source immutability, access, bounded batch counts, 500 scenes/30 characters/5,000 appearances, durable annotations, deleted routes/scenes, project backup/restore, all six web/PWA lenses, keyed DOM retention, unchanged revisions and Stage 1 regression workflows. + +## Deliberate limits and Stage 3 recommendations + +- One explicitly selected path per leg; route chains are deferred. +- Generic scene/event markers; no inferred event taxonomy or standalone duplicate event editor. +- No transport simulation, interpolation, speed assumptions or “impossible journey” claims. +- Observation acknowledgement/dismissal persistence is deferred; observations are requested explicitly. +- View preferences are browser-local, not server-synchronised. +- Scene changes reload on navigation/explicit refresh, not continuous background polling. + +Stage 3 can add detached workspace support, cross-device view preferences, route chains, optimistic concurrency for shared journey annotations, and further clustering/list virtualisation. Preserve Location-ID evidence, canonical manuscript membership/order, conservative time semantics, immutable geography during observation, and the separate Floor Plan workspace. diff --git a/PlotLine.Tests/Browser/maps-story-dev-smoke.cjs b/PlotLine.Tests/Browser/maps-story-dev-smoke.cjs new file mode 100644 index 00000000..bd6957a5 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-story-dev-smoke.cjs @@ -0,0 +1,44 @@ +// Explicit Development-only acceptance. Uses a dedicated normal account and owned fixture project. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const [identityPath,fixturePath]=process.argv.slice(2); +if(!identityPath?.startsWith('/tmp/pd-dev-browser-')||!fixturePath?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated Development identity and fixture files required.'); +const identity=JSON.parse(fs.readFileSync(identityPath,'utf8')),f=JSON.parse(fs.readFileSync(fixturePath,'utf8')),base='https://dev.plotdirector.com'; +if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Development fixture identity required.'); +(async()=>{const browser=await chromium.launch();try{ + const context=await browser.newContext({viewport:{width:1800,height:1100}}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(20000); + await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('form[action="/Account/Login"] button[type=submit]').click()]); + const rootURL=`${base}/Maps?projectId=${f.ProjectID}&id=${f.MapID}&mode=story`; + const before=await(await context.request.get(`${base}/Maps/State?projectId=${f.ProjectID}&id=${f.MapID}`)).json(); + async function ready(p){await p.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);} + async function group(p,locator){for(const menu of await locator.locator('xpath=ancestor::details').all())if(await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();} + async function choose(p,id,value,pwa=false){const source=p.locator('#'+id);if(pwa){const label=await source.getAttribute('aria-label'),proxy=p.locator('[data-pwa-context-controls]').getByRole('combobox',{name:label,exact:true,includeHidden:true}).or(p.locator('[data-pwa-context-controls]').getByRole('listbox',{name:label,exact:true,includeHidden:true}));await group(p,proxy);await proxy.selectOption(String(value));}else await source.selectOption(String(value));} + async function action(p,id,pwa=false){const node=pwa?p.locator(`[data-pwa-context-controls] [data-command-identity="handler:${id}"]`):p.locator('#'+id);await group(p,node);await node.click();} + await page.goto(rootURL);await ready(page);assert.equal(await page.evaluate(()=>window.PlotDirectorStoryOverlay.data.scenes.length),6);assert.equal(await page.locator('#mapsStoryLayer >g').count(),2); + await choose(page,'mapStoryLens','scene');await choose(page,'mapStoryScene',f.SceneAID);await action(page,'mapStoryNext');assert.match(await page.locator('#mapsDetailContent').innerText(),/Hill arrival/);await action(page,'mapStoryNext');assert.match(await page.locator('#mapsDetailContent').innerText(),/Harbour revisit/);await action(page,'mapStoryPrevious');assert.match(await page.locator('#mapsDetailContent').innerText(),/Hill arrival/); + assert.equal(await page.locator(`a[href="/Scenes/Edit/${f.SceneBID}"]`).count(),1); + await choose(page,'mapStoryLens','character');await choose(page,'mapStoryCharacter1',f.CharacterID);await choose(page,'mapStoryCharacter2',f.CompareCharacterID);assert.match(await page.locator('#mapsDetailContent').innerText(),/Ari/);assert.match(await page.locator('#mapsDetailContent').innerText(),/Bea/);assert.match(await page.locator('#mapsDetailContent').innerText(),/3\. Harbour/); + await page.locator('.maps-story-leg').first().focus();await page.keyboard.press('Enter');assert.match(await page.locator('#mapsDetailContent').innerText(),/Possible travel timing to review/); + await page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Author-selected travel context")')}).locator('summary').click(); + await page.locator('#mapStoryJourneyForm [name=routeFeatureID]').selectOption(f.RouteFeatureID);await page.locator('#mapStoryJourneyForm [name=travelMethod]').fill('Boat');await page.locator('#mapStoryJourneyForm [name=typicalMinutes]').fill('180');await page.locator('#mapStoryJourneyForm button[type=submit]').click();await page.waitForFunction(()=>window.PlotDirectorStoryOverlay.data.legs.some(l=>l.note?.travelMethod==='Boat')); + assert(await page.evaluate(route=>window.PlotDirectorStoryOverlay.data.legs.some(l=>l.note?.routeFeatureID===route),f.RouteFeatureID)); + await choose(page,'mapStoryLens','chapter');await choose(page,'mapStoryChapter',f.ChapterID);assert.match(await page.locator('#mapsDetailContent').innerText(),/3 scenes/); + await choose(page,'mapStoryLens','plot');await choose(page,'mapStoryPlot1',f.PlotLineID);assert.equal(await page.locator('#mapsStoryLayer >g').count(),1);assert.match(await page.locator('#mapsDetailContent').innerText(),/100%/); + await choose(page,'mapStoryLens','time');await choose(page,'mapStoryCharacter1',0);await choose(page,'mapStoryCharacter2',0);await choose(page,'mapStoryTime','2026-01-01T09:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/Last known: Hill town/);await choose(page,'mapStoryTime','2026-01-01T10:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/latest confirmed appearance has no known Location/); + await choose(page,'mapStoryLens','overview');await action(page,'mapStoryGaps');assert.match(await page.locator('#mapsDetailContent').innerText(),/Unmapped town/);assert.match(await page.locator('#mapsDetailContent').innerText(),/No Location assigned/); + await page.locator(`[data-story-place="${f.UnmappedLocationID}"]`).click();assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.mode),'create');assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false,'resolving a gap never places it automatically');await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('explore'));assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false); + await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await ready(page);await choose(page,'mapStoryLens','scene');await choose(page,'mapStoryScene',f.DetailSceneID); + const floorLink=page.locator(`a[href*="/FloorPlans/Edit/${f.FloorPlanID}?storySceneId=${f.DetailSceneID}"]`);assert.equal(await floorLink.count(),1);await floorLink.click();await page.waitForURL(/\/FloorPlans\/Edit/);await page.locator('.floor-plan-editor--occupancy').waitFor();assert.equal(await page.locator('[data-occupancy-scene-select]').inputValue(),String(f.DetailSceneID)); + await page.getByRole('link',{name:'← Back to map Story Mode'}).click();await ready(page);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.mode),'story'); + await page.locator(`#mapsDetailContent a[href*="id=${f.ChildMapID}&mode=story"]`).click();await ready(page);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.map.parentMapID),f.MapID);assert.match(await page.locator('#mapsDetailContent').innerText(),/House room/); + const parent=page.locator(`#mapsBreadcrumbs a[href*="id=${f.MapID}&mode=story"]`);await parent.click();await ready(page);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.mode),'story'); + await page.locator('a[href="/Scenes/Edit/'+f.DetailSceneID+'"]').click();await page.waitForURL('**/Scenes/Edit/'+f.DetailSceneID);assert(await page.locator('main').isVisible());await page.goto(rootURL);await ready(page); + const denied=await context.request.get(`${base}/Maps/Story?projectId=${f.ProjectID}&id=-1`);assert.equal(denied.status(),404);const scenario=await context.request.get(`${base}/Maps/Story?projectId=${f.ProjectID}&id=${f.MapID}&scenarioId=-1`);assert.equal(scenario.status(),404); + const csrf=await context.request.post(`${base}/Maps/Journey?projectId=${f.ProjectID}`,{data:{mapID:f.MapID,characterID:f.CharacterID,fromSceneID:f.SceneAID,toSceneID:f.SceneBID}});assert.equal(csrf.status(),400); + const pwaContext=await browser.newContext({viewport:{width:1800,height:1100},storageState:await context.storageState()});await pwaContext.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const app=await pwaContext.newPage();app.on('pageerror',e=>errors.push(e.message));await app.goto(rootURL);await ready(app); + assert(await app.locator('#mapsStoryToolbar').isHidden());assert(await app.locator('.maps-toolbar').isHidden());const bounds=await app.locator('#mapsCanvas').boundingBox(); + await choose(app,'mapStoryLens','character',true);await choose(app,'mapStoryCharacter1',f.CharacterID,true);await choose(app,'mapStoryCharacter2',f.CompareCharacterID,true);assert.match(await app.locator('#mapsDetailContent').innerText(),/Bea/);await choose(app,'mapStoryLens','chapter',true);await choose(app,'mapStoryChapter',f.ChapterID,true);await choose(app,'mapStoryLens','plot',true);await choose(app,'mapStoryPlot1',f.PlotLineID,true);await choose(app,'mapStoryLens','time',true);await choose(app,'mapStoryTime','2026-01-01T09:30:00',true);assert.match(await app.locator('#mapsDetailContent').innerText(),/Last known/);assert.deepEqual(await app.locator('#mapsCanvas').boundingBox(),bounds,'PWA lens changes preserve canvas geometry'); + await choose(app,'mapStoryLens','character',true);await app.screenshot({path:'/tmp/maps-story-development-pwa.png'});await page.screenshot({path:'/tmp/maps-story-development-web.png'}); + for(const width of [1440,800,390]){await app.setViewportSize({width,height:1100});assert(await app.locator('#mapsApp').evaluate(e=>e.scrollWidth<=e.clientWidth+1),'responsive workspace must not overflow at '+width);} + const after=await(await context.request.get(`${base}/Maps/State?projectId=${f.ProjectID}&id=${f.MapID}`)).json();assert.deepEqual(after,before,'all Story navigation and travel annotation save must leave geography and revision unchanged');assert.deepEqual(errors,[]); + console.log('PASS authenticated Development Maps Story: six lenses, scene/editor navigation, character comparison/revisits, explicit saved route/method/time, chronology/unknown semantics, honest gaps, child/ancestor maps, Floor Plan occupancy/back navigation, PWA/responsive layout, CSRF/scenario access and unchanged geography revision.');await context.close();await pwaContext.close(); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/maps-story-engine.cjs b/PlotLine.Tests/Browser/maps-story-engine.cjs new file mode 100644 index 00000000..98b81ec5 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-story-engine.cjs @@ -0,0 +1,21 @@ +const assert=require('node:assert/strict'),E=require('../../PlotLine/wwwroot/js/maps-story-engine'); +const loc=(id,featureID)=>({locationID:id,featureID,status:id?(featureID?'Exact':'Unmapped'):'No Location'}); +const data={characters:[{characterID:1,name:'A'},{characterID:2,name:'B'},{characterID:3,name:'Unknown'}],scenes:[ + {sceneID:90,narrativeOrder:1,bookID:1,chapterID:1,plotLineIDs:[5],startDateTime:'2026-01-01T09:00:00',timePrecision:'Timestamp',position:loc(1,'a')}, + {sceneID:10,narrativeOrder:2,bookID:1,chapterID:1,plotLineIDs:[6],startDateTime:'2026-01-01T10:00:00',timePrecision:'Timestamp',position:loc(2,'b')}, + {sceneID:70,narrativeOrder:3,bookID:1,chapterID:2,plotLineIDs:[5],startDateTime:'2026-01-01T11:00:00',timePrecision:'Timestamp',position:loc(1,'a')}, + {sceneID:20,narrativeOrder:4,bookID:1,chapterID:2,plotLineIDs:[],startDateTime:'2026-01-01T12:00:00',timePrecision:'Timestamp',position:loc(null,null)}, + {sceneID:80,narrativeOrder:5,bookID:1,chapterID:2,plotLineIDs:[5],startDateTime:'2026-01-01T13:00:00',timePrecision:'Timestamp',position:loc(3,null)} +]};data.stops=data.scenes.map((s,i)=>({characterID:1,sceneID:s.sceneID,sequence:i+1,position:s.position}));data.stops.push({characterID:2,sceneID:90,sequence:1,position:loc(2,'b')}); +const before=JSON.stringify(data),base={lens:'overview',bookID:0,chapterID:0,plotIDs:[],mapping:'all',planning:'all'}; +assert.deepEqual(E.filterScenes(data,{...base,lens:'plot',plotIDs:[5]}).map(s=>s.sceneID),[90,70,80]); +assert.deepEqual(E.filterScenes(data,{...base,lens:'chapter',chapterID:1}).map(s=>s.sceneID),[90,10]); +assert.deepEqual(E.filterScenes(data,{...base,mapping:'unmapped'}).map(s=>s.sceneID),[80]);assert.deepEqual(E.filterScenes(data,{...base,mapping:'missing'}).map(s=>s.sceneID),[20]); +assert.deepEqual(E.journeys(data,[1],data.scenes).map(s=>s.position.locationID),[1,2,1,null,3]);assert.equal(E.density(data.scenes).get('a').length,2); +let at=E.timePositions(data,'2026-01-01T10:30:00');assert.equal(at[0].position.locationID,2);assert.equal(at[1].position.locationID,2);assert.equal(at[2].position,null); +at=E.timePositions(data,'2026-01-01T12:30:00');assert.equal(at[0].position,null,'latest unknown appearance must not fall back to an older mapped position'); +at=E.timePositions(data,'2026-01-01T13:30:00');assert.equal(at[0].position.status,'Unmapped','last known unmapped Location is not replaced by older mapped geography'); +assert.equal(JSON.stringify(data),before,'lenses/time projections do not mutate source data'); +const day=JSON.parse(before);day.scenes[1].timePrecision='Day';day.scenes[1].startDateTime='2026-01-01T00:00:00';assert.equal(E.timePositions(day,'2026-01-01T10:30:00')[0].position,null,'date-only uncertainty does not gain clock precision'); +const same=JSON.parse(before);same.scenes[1].startDateTime=same.scenes[0].startDateTime;assert.equal(E.timePositions(same,'2026-01-01T09:30:00')[0].position,null,'simultaneous conflicting positions remain unknown'); +console.log('PASS Maps Story pure lenses, repeated visits, density, last-known/unknown time semantics and source immutability'); diff --git a/PlotLine.Tests/Browser/maps-story.cjs b/PlotLine.Tests/Browser/maps-story.cjs new file mode 100644 index 00000000..71a1c4f4 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-story.cjs @@ -0,0 +1,52 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'); +const base=process.env.PD_MAPS_STORY_TEST_URL||'http://127.0.0.1:5247'; +(async()=>{const browser=await chromium.launch();try{ + for(const pwa of [false,true]){ + const context=await browser.newContext({viewport:{width:1800,height:1100}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); + const page=await context.newPage(),errors=[];page.setDefaultTimeout(12000);page.on('pageerror',e=>errors.push(e.message));let reads=0,geographyWrites=0,annotation=null; + let fixture=await(await context.request.get(base+'/map-story-fixture')).json(); + await page.route('**/Maps/Story?**',route=>{reads++;return route.fulfill({json:fixture});}); + await page.route('**/Maps/Save',route=>{geographyWrites++;return route.fulfill({status:500,json:{message:'Story must never save geography'}});}); + await page.route('**/Maps/Journey?**',route=>{annotation=route.request().postDataJSON();const leg=fixture.legs.find(l=>l.characterID===annotation.characterID&&l.fromSceneID===annotation.fromSceneID&&l.toSceneID===annotation.toSceneID);leg.note=annotation;return route.fulfill({json:{ok:true}});}); + await page.goto(base+'/fixture?page=maps&story=true');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + const geography=await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)); + async function menuFor(locator){const menus=locator.locator('xpath=ancestor::details[@data-compact]');for(const menu of await menus.all())if(await menu.getAttribute('data-compact')==='true'&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();} + async function clickSource(id){if(pwa){const proxy=page.locator(`[data-pwa-context-controls] [data-command-identity="handler:${id}"]`);if(await proxy.count()){await menuFor(proxy);await proxy.click();return;}}const source=page.locator('#'+id),menu=source.locator('xpath=ancestor::details[1]');if(await menu.count()&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();await source.click();} + async function choose(id,value){if(pwa){const label=await page.locator('#'+id).getAttribute('aria-label');const host=page.locator('[data-pwa-context-controls]'),field=host.getByRole('combobox',{name:label,exact:true,includeHidden:true}).or(host.getByRole('listbox',{name:label,exact:true,includeHidden:true}));await menuFor(field);await field.selectOption(String(value));}else await page.locator('#'+id).selectOption(String(value));} + await page.locator('button[data-mode=story]').evaluate(el=>el.click());await page.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data); + const canvas=page.locator('#mapsCanvas'),bounds=await canvas.boundingBox();assert.equal(await page.locator('#mapsStoryLayer >g').count(),2,'overview is restrained density, not one marker per scene'); + await page.evaluate(()=>{window.__baseSVG=document.getElementById('mapsCanvas');window.__basePiece=document.querySelector('#mapsScene [data-feature-id]');}); + await choose('mapStoryLens','scene');await choose('mapStoryScene',90);assert.match(await page.locator('#mapsDetailContent').innerText(),/Harbour morning/);await clickSource('mapStoryNext');assert.match(await page.locator('#mapsDetailContent').innerText(),/Hill arrival/);await clickSource('mapStoryPrevious');assert.match(await page.locator('#mapsDetailContent').innerText(),/Harbour morning/); + assert.equal(await page.locator('a[href="/Scenes/Edit/90"]').count(),1,'map to canonical scene editor'); + await choose('mapStoryScene',20);assert.match(await page.locator('#mapsDetailContent').innerText(),/No Location assigned/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),0,'unknown scene has no fake map position');assert.equal(await page.locator('.maps-feature.is-selected').count(),0,'previous scene highlight is cleared for unknown geography'); + await choose('mapStoryScene',80);assert.match(await page.locator('#mapsDetailContent').innerText(),/Unmapped/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),0,'matching feature names do not create associations'); + await choose('mapStoryScene',30);assert.equal(await page.locator('a[href*="id=2&mode=story"]').count(),1,'child map navigation');assert.equal(await page.locator('a[href*="/FloorPlans/Edit/101?storySceneId=30"]').count(),1,'Floor Plan occupancy context'); + await choose('mapStoryLens','character');await choose('mapStoryCharacter1',1);await choose('mapStoryCharacter2',2); + const journeyText=await page.locator('#mapsDetailContent').innerText();assert.match(journeyText,/Ari/);assert.match(journeyText,/Bea/);assert.match(journeyText,/1\. Harbour/);assert.match(journeyText,/3\. Harbour/);assert.match(journeyText,/Unknown/);assert(await page.locator('.maps-story-leg').count()>=2); + await page.locator('.maps-story-leg').first().focus();await page.keyboard.press('Enter');assert.match(await page.locator('#mapsDetailContent').innerText(),/journey leg/);assert.match(await page.locator('#mapsDetailContent').innerText(),/126 kilometres/);assert.match(await page.locator('#mapsDetailContent').innerText(),/Possible travel timing to review/); + await page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Author-selected travel context")')}).locator('summary').click();await page.locator('#mapStoryJourneyForm [name=travelMethod]').fill('Boat');await page.locator('#mapStoryJourneyForm [name=typicalMinutes]').fill('180');await page.locator('#mapStoryJourneyForm button[type=submit]').click();await page.waitForFunction(()=>window.PlotDirectorStoryOverlay.data.legs.some(l=>l.note?.travelMethod==='Boat'));assert.equal(annotation.travelMethod,'Boat'); + await choose('mapStoryLens','chapter');await choose('mapStoryChapter',11);assert.match(await page.locator('#mapsDetailContent').innerText(),/3 scenes/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),2); + await choose('mapStoryLens','plot');await choose('mapStoryPlot1',5);assert.match(await page.locator('#mapsDetailContent').innerText(),/67%/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),1);assert(await page.locator('#mapsScene .map-story-muted').count()>=1,'unrelated geography fades rather than disappears'); + await choose('mapStoryLens','time');await choose('mapStoryCharacter1',0);await choose('mapStoryCharacter2',0);await choose('mapStoryTime','2026-01-01T09:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/Last known: Hill town/);assert.match(await page.locator('#mapsDetailContent').innerText(),/Unknown person/);assert.match(await page.locator('#mapsDetailContent').innerText(),/position between scenes is not established/); + await choose('mapStoryTime','2026-01-01T10:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/latest confirmed appearance has no known Location/); + await choose('mapStoryLens','overview');await clickSource('mapStoryGaps');assert.match(await page.locator('#mapsDetailContent').innerText(),/Unmapped town/);assert.match(await page.locator('#mapsDetailContent').innerText(),/No Location assigned/); + await clickSource('mapStoryObservations');assert.match(await page.locator('#mapsDetailContent').innerText(),/Possible travel timing to review/); + assert.deepEqual(await canvas.boundingBox(),bounds,'lens changes and selections do not shift the canvas'); + assert(await page.evaluate(()=>window.__baseSVG===document.getElementById('mapsCanvas')&&window.__basePiece===document.querySelector('#mapsScene [data-feature-id]')),'base canvas and keyed geography nodes are retained'); + assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);await canvas.focus();await page.keyboard.press('Control+s');await page.keyboard.press('Delete');assert.equal(geographyWrites,0);assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);assert.equal(reads,2,'one source projection plus one explicit annotation refresh, no per-stop requests'); + await clickSource('mapStoryLayer');assert(await page.locator('#mapsStoryLayer').isHidden());await clickSource('mapStoryLayer'); + if(pwa)assert(await page.locator('#mapsStoryToolbar').isHidden()); + await page.screenshot({path:`/tmp/maps2-${pwa?'pwa':'web'}.png`}); + await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('create'));assert(await page.locator('#mapsLibrary').isVisible());assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography); + fixture=JSON.parse(JSON.stringify(fixture));const prototype=fixture.scenes[0],pa=fixture.scenes[0].position,pb=fixture.scenes[1].position; + fixture.characters=Array.from({length:30},(_,i)=>({characterID:i+1,name:'Person '+(i+1),importance:i%10})); + fixture.scenes=Array.from({length:500},(_,i)=>({...prototype,sceneID:1000+i,narrativeOrder:i+1,sceneTitle:'Scene '+i,sceneNumber:i+1,position:i%2?pa:pb,primaryLocationID:(i%2?pa:pb).locationID,startDateTime:new Date(Date.UTC(2026,0,1,0,i)).toISOString().slice(0,19),characterIDs:[],plotLineIDs:[]})); + fixture.stops=fixture.scenes.flatMap((s,i)=>Array.from({length:10},(_,j)=>({characterID:(i+j)%30+1,sceneID:s.sceneID,sequence:i+1,position:s.position,observedAt:s.startDateTime,timePrecision:'Timestamp',evidence:'Fixture presence'}))); + const previous=new Map();fixture.legs=[];for(const stop of fixture.stops){const p=previous.get(stop.characterID);if(p)fixture.legs.push({characterID:stop.characterID,fromSceneID:p.sceneID,toSceneID:stop.sceneID,from:p.position,to:stop.position,evidenceLevel:0,timingObservation:false});previous.set(stop.characterID,stop);} + await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await page.evaluate(()=>window.PlotDirectorStoryOverlay.refresh());await page.waitForFunction(()=>window.PlotDirectorStoryOverlay.data.scenes.length===500);await choose('mapStoryLens','scene');await choose('mapStoryScene',1499);assert.match(await page.locator('#mapsDetailContent').innerText(),/Scene 499/); + const elapsed=await page.evaluate(()=>{const start=performance.now();for(let i=0;i<50;i++)window.PlotDirectorStoryOverlay.chooseScene(1000+i);return performance.now()-start;});assert(elapsed<5000,'scene navigation remains practical with 500 scenes/5,000 appearances'); + await choose('mapStoryLens','character');await choose('mapStoryCharacter1',1);await choose('mapStoryCharacter2',2);assert(await page.locator('.maps-story-leg').count()<=4,'repeated movements aggregate their lines while preserving individual stops/leg Details'); + assert.equal(geographyWrites,0);assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);console.log(`Maps Story ${pwa?'PWA':'web'} scale: 500 scenes, 5,000 appearances; 50 scene changes in ${elapsed.toFixed(0)}ms.`); + assert.deepEqual(errors,[]);console.log(`PASS Maps Story ${pwa?'PWA':'web'}: six lenses, manuscript navigation, repeated visits/comparison, travel context, evidence, hierarchy/Floor Plan links, honest gaps, stable keyed canvas and unchanged geography/revision`);await context.close(); + } +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index 70bf2ccb..aa507ad0 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -19,7 +19,8 @@ "test:relationships": "node relationship-workspace.cjs", "test:relationships-ribbon": "node relationships-ribbon.cjs", "test:relationship-focus": "node relationship-focus-stability.cjs", - "test:maps": "node maps-engine.cjs && node maps-workspace.cjs" + "test:maps": "node maps-engine.cjs && node maps-workspace.cjs", + "test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs" }, "devDependencies": { "chart.js": "4.4.9", diff --git a/PlotLine.Tests/MapStoryDevFixture.cs b/PlotLine.Tests/MapStoryDevFixture.cs new file mode 100644 index 00000000..c346d1e5 --- /dev/null +++ b/PlotLine.Tests/MapStoryDevFixture.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using System.Text.Json; +using Dapper; +using Microsoft.Data.SqlClient; + +internal static class MapStoryDevFixture +{ + public static async Task RunAsync(string[] args) + { + if(!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException("Development fixtures run on the Linux development host"); + if(args.Length!=3 || !args[1].StartsWith("/tmp/pd-dev-browser-") || !args[2].StartsWith("/tmp/pd-dev-browser-")) throw new InvalidOperationException("Use --maps-story-dev-fixture dedicated-identity.json new-fixture.json"); + using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var root=identity.RootElement; + if(root.GetProperty("Database").GetString()!="PlotDirector_Development" || !root.GetProperty("Email").GetString()!.StartsWith("pwa-browser-")) throw new InvalidOperationException("Dedicated Development identity required"); + var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var p in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(p); + using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable"); + var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('\"','\''); + if(new SqlConnectionStringBuilder(raw).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); + using var db=new SqlConnection(raw);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); + var userID=root.GetProperty("UserID").GetInt32();if(!await db.ExecuteScalarAsync("SELECT CONVERT(bit,CASE WHEN EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@userID AND Email=@email) THEN 1 ELSE 0 END)",new{userID,email=root.GetProperty("Email").GetString()}))throw new InvalidOperationException("Fixture identity mismatch"); + // Provisioning follows an explicit copy-only backup just like migrations; no existing manuscript is edited. + var backup=$"/var/opt/mssql/backup/maps-story-fixture-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak"; + await db.ExecuteAsync("BACKUP DATABASE [PlotDirector_Development] TO DISK=@backup WITH COPY_ONLY,CHECKSUM",new{backup},commandTimeout:180); + var file=new FileInfo(backup.Replace("/var/opt/mssql/","/sql/mssql/"));if(!file.Exists||file.Length==0)throw new InvalidOperationException("Backup file missing"); + using var rows=await db.QueryMultipleAsync(await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryFixture.sql"),new{UserID=userID},commandTimeout:180); + object? fixture=null;while(!rows.IsConsumed)foreach(var row in await rows.ReadAsync())if(((IDictionary)row).ContainsKey("MapID"))fixture=row; + if(fixture is null)throw new InvalidOperationException("Fixture was not returned"); + await using var output=new FileStream(args[2],new FileStreamOptions{Mode=FileMode.CreateNew,Access=FileAccess.Write,UnixCreateMode=UnixFileMode.UserRead|UnixFileMode.UserWrite});await JsonSerializer.SerializeAsync(output,fixture); + Console.WriteLine("Dedicated Maps Story fixture created in Development; private fixture IDs written. Cleanup uses the dedicated identity's normal account deletion workflow."); + } + public static async Task DatabaseAsync() + { + if(!OperatingSystem.IsLinux())throw new PlatformNotSupportedException(); + var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var p in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(p); + using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable"); + var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('\"','\''); + if(new SqlConnectionStringBuilder(raw).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); + using var db=new SqlConnection(raw);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong database"); + var userID=await db.ExecuteScalarAsync("SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE IsActive=1 AND AccessRole='Owner'"); + var sql="BEGIN TRAN;\n"+await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryFixture.sql")+"\n"+await File.ReadAllTextAsync("PlotLine.Tests/Sql/210_MapStoryAssertions.sql"); + using var rows=await db.QueryMultipleAsync(sql,new{UserID=userID},commandTimeout:180); + var passed=false;while(!rows.IsConsumed)foreach(var row in await rows.ReadAsync()){var values=(IDictionary)row;if(values.TryGetValue("Result",out var message)){Console.WriteLine(message);passed=true;}} + if(!passed)throw new InvalidOperationException("No database assertion result returned"); + } + +} diff --git a/PlotLine.Tests/MapStoryTests.cs b/PlotLine.Tests/MapStoryTests.cs new file mode 100644 index 00000000..bb2b4cc1 --- /dev/null +++ b/PlotLine.Tests/MapStoryTests.cs @@ -0,0 +1,106 @@ +using System.Reflection; +using System.Text.Json; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; + +internal static class MapStoryTests +{ + public static readonly Guid A = Guid.Parse("00000000-0000-0000-0000-000000000001"), B = Guid.Parse("00000000-0000-0000-0000-000000000002"), Child = Guid.Parse("00000000-0000-0000-0000-000000000003"); + static void Check(bool ok,string message) { if(!ok) throw new InvalidOperationException(message); } + public static MapStoryData Fixture() + { + var ids = new[] { 90, 10, 70, 20, 80, 30 }; + int?[] locations = [10,20,10,null,30,40]; + return new() { + Maps = [new() { MapID=1,ProjectID=7,Name="Story region",Kind="Region",Revision=12 },new() {MapID=2,ProjectID=7,Name="House detail",Kind="Local Area",ParentMapID=1,ParentFeatureID=A}], + Features = [new() {MapID=1,FeatureID=A,Name="Map alias A",LocationID=10,X=-200,Y=0,IsProvisional=false,FloorPlanID=101},new(){MapID=1,FeatureID=B,Name="Map alias B",LocationID=20,X=250,Y=100,IsProvisional=false},new(){MapID=1,Name="Unmapped town",LocationID=null,X=0,Y=300,IsProvisional=false},new(){MapID=2,FeatureID=Child,Name="House room",LocationID=40,IsProvisional=false}], + Relationships=[new() {MapID=1,SourceID=A,TargetID=B,Direction="W",RelativeDistance="Far",MeasuredDistance=126,Unit="kilometres",TypicalTravelTime="3h 30m"}], + Locations=[new(){LocationID=10,ProjectID=7,LocationName="Harbour",Description="A working harbour."},new(){LocationID=20,ProjectID=7,LocationName="Hill town"},new(){LocationID=30,ProjectID=7,LocationName="Unmapped town"},new(){LocationID=40,ParentLocationID=10,ProjectID=7,LocationName="House room"}], + FloorPlans=[new(){FloorPlanID=101,ProjectID=7,LocationID=40,Name="House floor plan"}], + Characters=[new(){CharacterID=1,CharacterName="Ari",CharacterImportance=9},new(){CharacterID=2,CharacterName="Bea",CharacterImportance=8},new(){CharacterID=3,CharacterName="Mentioned person"},new(){CharacterID=4,CharacterName="Unknown person"}], + Scenes=ids.Select((id,i)=>new MapStoryScene{SceneID=id,BookID=9,BookTitle="The crossing",ChapterID=i<3?11:22,ChapterNumber=i<3?1:2,ChapterTitle=i<3?"Departure":"Return",NarrativeOrder=i+1,SceneNumber=i+1,SceneTitle=new[]{"Harbour morning","Hill arrival","Harbour revisit","Unknown interval","Unmapped scene","House discovery"}[i],PrimaryLocationID=locations[i],FloorPlanID=i==5?101:null,StartDateTime=new DateTime(2026,1,1,9,0,0).AddMinutes(i*30),TimeModeName="Exact DateTime",TimeConfidenceName="Confirmed"}).ToList(), + Appearances=ids.Select((id,i)=>new SceneCharacter {SceneCharacterID=i+1,SceneID=id,CharacterID=1,PresenceTypeName="Present"}).Concat([ + new SceneCharacter{SceneCharacterID=20,SceneID=90,CharacterID=2,LocationID=20,PresenceTypeName="Present"}, + new SceneCharacter{SceneCharacterID=21,SceneID=20,CharacterID=2,PresenceTypeName="Unknown"}, + new SceneCharacter{SceneCharacterID=22,SceneID=90,CharacterID=3,PresenceTypeName="Mentioned Only",LocationID=20} + ]).ToList() + }; + } + public static PlotLineWorkspaceData Plots() => new() { + PlotLines=[new(){PlotLineID=5,ProjectID=7,PlotLineName="The search"},new(){PlotLineID=6,ProjectID=7,PlotLineName="The return"}], + Contributions=[new(){PlotLineID=5,SceneID=90},new(){PlotLineID=5,SceneID=70},new(){PlotLineID=5,SceneID=80},new(){PlotLineID=6,SceneID=10},new(){PlotLineID=6,SceneID=30}] + }; + public static MapsViewModel Workspace() + { + var f=Fixture();return new(){Project=new(){ProjectID=7,ProjectName="Story map fixture"},Maps=f.Maps,Locations=f.Locations,FloorPlans=f.FloorPlans, + Document=new(){Map=f.Maps[0],Features=f.Features.Where(x=>x.MapID==1).ToList(),Relationships=f.Relationships}}; + } + public static void ProjectionAndEvidence() + { + var input=Fixture();var geography=JsonSerializer.Serialize(new{input.Maps,input.Features,input.Relationships}); + var p=MapStoryComposer.Compose(input,Plots(),1); + Check(p.Scenes.Select(s=>s.SceneID).SequenceEqual([90,10,70,20,80,30]),"Scene IDs must not replace canonical manuscript order."); + Check(p.Scenes[0].Position.FeatureID==A&&p.Scenes[1].Position.FeatureID==B,"Join canonical Location IDs, despite map aliases."); + Check(p.Scenes[4].Position.Status=="Unmapped"&&p.Scenes[4].Position.FeatureID is null,"Matching names must never infer association."); + Check(p.Scenes[3].Position.Status=="No Location","No Location differs from unmapped."); + Check(p.Scenes[5].Position.FeatureID==A&&p.Scenes[5].Position.Status=="Ancestor location"&&p.Scenes[5].Position.DetailMapID==2,"Canonical ancestor and explicit detailed map must be preserved."); + Check(p.Scenes[5].Position.FloorPlanID==101,"Floor Plan link must follow explicit hierarchy."); + Check(p.Scenes[0].PlotLineIDs.SequenceEqual([5])&&p.Scenes[1].PlotLineIDs.SequenceEqual([6]),"Membership comes from canonical workspace contributions."); + var stops=p.Stops.Where(x=>x.CharacterID==1).ToList(); + Check(stops.Select(s=>s.Position.LocationID).SequenceEqual(new int?[]{10,20,10,null,30,40}),"A→B→A revisits and unknown gaps must remain in sequence."); + Check(!p.Stops.Any(s=>s.CharacterID==3),"Mention-only membership is not location evidence."); + Check(p.Stops.Single(s=>s.CharacterID==2&&s.SceneID==90).Position.LocationID==20,"Explicit character Location overrides scene Location."); + Check(p.Stops.Single(s=>s.CharacterID==2&&s.SceneID==20).Position.LocationID is null,"Unknown appearance does not inherit a scene position."); + var leg=p.Legs.First(l=>l.CharacterID==1); + Check(leg.TimingObservation&&leg.EvidenceLevel==3&&leg.TypicalMinutes==210&&leg.ElapsedMinutes==30&&leg.MeasuredDistance==126,"Confirmed times and explicit duration support a gentle observation."); + Check(p.Legs.Single(l=>l.CharacterID==1&&l.FromSceneID==10).Direction=="E","Reverse relationship direction is contextual and explicit."); + Check(p.Legs.Where(l=>l.From.LocationID is null||l.To.LocationID is null).All(l=>!l.TimingObservation),"Unknown gaps cannot create travel claims."); + Check(JsonSerializer.Serialize(new{input.Maps,input.Features,input.Relationships})==geography,"Projection must not mutate geography or revisions."); + var f=Fixture();f.Relationships.Clear();f.Features[1].X=100000; + Check(MapStoryComposer.Compose(f,Plots(),1).Legs.All(l=>!l.TimingObservation&&l.MeasuredDistance is null),"Canvas spacing never establishes distance or travel time."); + f=Fixture();f.Relationships[0].TypicalTravelTime=null; + Check(MapStoryComposer.Compose(f,Plots(),1).Legs.All(l=>!l.TimingObservation),"Distance alone is not travel duration."); + f=Fixture();f.Scenes[1].TimeModeName="Exact Date"; + Check(!MapStoryComposer.Compose(f,Plots(),1).Legs.First().TimingObservation,"Date-only evidence cannot support minute-level claims."); + f=Fixture();f.Scenes[1].TimeConfidenceName="Estimated"; + Check(!MapStoryComposer.Compose(f,Plots(),1).Legs.First().TimingObservation,"Estimated time cannot support a strong observation."); + f=Fixture();f.Features[0].IsProvisional=true; + Check(!MapStoryComposer.Compose(f,Plots(),1).Legs.First().TimingObservation,"Planning geography does not silently establish travel facts."); + Check(MapStoryComposer.ParseMinutes("3h 30m")==210&&MapStoryComposer.ParseMinutes("2 hours")==120&&MapStoryComposer.ParseMinutes("possibly two hours") is null&&MapStoryComposer.ParseMinutes("2 hours by portal") is null,"Only explicit supported duration syntax is parsed."); + f=Fixture();f.Appearances[0].ExitLocationID=20;f.Scenes[0].EndDateTime=new DateTime(2026,1,1,11,0,0); + var exit=MapStoryComposer.Compose(f,Plots(),1).Stops.First();Check(exit.ObservedAt==f.Scenes[0].EndDateTime&&exit.TimePrecision=="Timestamp","An explicit exit Location is observed at scene end, never backdated to scene start."); + f.Scenes[0].EndDateTime=null;Check(MapStoryComposer.Compose(f,Plots(),1).Stops.First().TimePrecision is null,"Exit Location without an end time cannot acquire a timestamp."); + var resolver=MapStoryComposer.Resolver(Fixture(),2); + Check(resolver(20).Status=="On ancestor map"&&resolver(20).FeatureID is null,"A detailed map must not fake ancestor positions on its own canvas."); + } + public static void Scale() + { + var input=Fixture();input.Characters=Enumerable.Range(1,30).Select(i=>new Character{CharacterID=i,CharacterName=$"Person {i}",CharacterImportance=i%10}).ToList(); + input.Scenes=Enumerable.Range(1,500).Select(i=>new MapStoryScene{SceneID=1000+i,BookID=9,ChapterID=11,NarrativeOrder=i,SceneNumber=i,SceneTitle=$"Scene {i}",PrimaryLocationID=i%5==0?null:i%3==0?30:i%2==0?10:20,StartDateTime=new DateTime(2026,1,1).AddHours(i),TimeModeName="Exact DateTime",TimeConfidenceName="Confirmed"}).ToList(); + input.Appearances=input.Scenes.SelectMany((scene,index)=>Enumerable.Range(0,10).Select(j=>new SceneCharacter{SceneID=scene.SceneID,CharacterID=(index+j)%30+1,PresenceTypeName="Present"})).ToList(); + var clock=System.Diagnostics.Stopwatch.StartNew();var projection=MapStoryComposer.Compose(input,Plots(),1); + Check(projection.Scenes.Count==500&&projection.Characters.Count==30&&projection.Stops.Count==5000&&projection.Legs.Count==4970,"A substantial manuscript retains every physical appearance and per-character transition."); + Console.WriteLine($"Maps Story scale: 500 scenes, 30 characters, 5,000 appearances in {clock.ElapsedMilliseconds}ms."); + } + public static void SecurityAndBatching() + { + int calls=0; + T Proxy(Func handler) where T:class {var p=DispatchProxy.Create();((StoryPointProxy)(object)p).Handler=handler;return p;} + var denied=Proxy((_,_)=>Task.FromResult(false)); + var repo=Proxy((_,_)=>{calls++;return Task.FromResult(Fixture());}); + var plots=Proxy((_,_)=>{calls++;return Task.FromResult(Plots());}); + var scenarios=Proxy((_,_)=>{calls++;return Task.FromResult>([]);}); + Check(new MapStoryService(repo,plots,scenarios,denied).GetAsync(7,1,4).Result is null&&calls==0,"Denied access must short circuit every batch."); + var allowed=Proxy((_,_)=>Task.FromResult(true)); + Check(new MapStoryService(repo,plots,scenarios,allowed).GetAsync(7,1,4).Result?.Scenes.Count==6&&calls==3,"Query count is fixed: source, canonical memberships and scenario choices, never per-marker."); + calls=0;Check(new MapStoryService(repo,plots,scenarios,allowed).GetAsync(7,1,4,999).Result is null&&calls==1,"Foreign/unknown scenario must fail before loading source or memberships."); + var alternatives=Proxy((_,_)=>Task.FromResult>([new(){ScenarioID=55,ProjectID=7,ScenarioName="Alternative order"}])); + var scenarioPlots=Proxy((_,args)=>{Check((int?)args![2]==55,"Scenario is passed to the canonical Plot Lines projection.");return Task.FromResult(new PlotLineWorkspaceData{AttributionScenes=[new(){SceneID=70,NarrativeOrder=1,BookID=9,ChapterID=22,ChapterNumber=2,ChapterTitle="Return"},new(){SceneID=90,NarrativeOrder=2,BookID=9,ChapterID=22,ChapterNumber=2,ChapterTitle="Return"}]});}); + var alternative=new MapStoryService(repo,scenarioPlots,alternatives,allowed).GetAsync(7,1,4,55).Result!; + Check(alternative.Scenes.Select(s=>s.SceneID).SequenceEqual([70,90])&&alternative.Scenes.All(s=>s.ChapterID==22),"Scenario sequence and proposed chapter footprint must reuse the workspace projection."); + var controller=new PlotLine.Controllers.MapsController(null!,null!,null!,null!,denied,null!); + Check(controller.Story(7,1,null,null!).Result is Microsoft.AspNetCore.Mvc.NotFoundResult,"Story controller enforces access."); + Check(controller.Journey(7,null,new(),null!,null!).Result is Microsoft.AspNetCore.Mvc.NotFoundResult,"Travel annotation controller enforces access."); + } +} diff --git a/PlotLine.Tests/MapTests.cs b/PlotLine.Tests/MapTests.cs index c0337387..bec77b3f 100644 --- a/PlotLine.Tests/MapTests.cs +++ b/PlotLine.Tests/MapTests.cs @@ -39,7 +39,7 @@ internal static class MapTests Check(controller.Save(d).Result is NotFoundResult, "Save must enforce access."); Check(controller.Delete(7, 1, 0).Result is NotFoundResult, "Delete must enforce access."); var posts = typeof(MapsController).GetMethods().Where(m => m.GetCustomAttributes(typeof(HttpPostAttribute), true).Length > 0); - Check(posts.Count() == 3 && posts.All(m => m.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true).Length > 0), "Every mutation needs antiforgery and the shared subscription enforcement filter."); + Check(posts.Count() == 4 && posts.All(m => m.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true).Length > 0), "Every mutation needs antiforgery and the shared subscription enforcement filter."); } private sealed class DeniedAccess : IProjectAccessService { diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index e3909d2b..06ab2ac1 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -54,6 +54,22 @@ if (args.Contains("--dev-browser-identity")) return; } +if (args.Contains("--maps-story-database")) +{ + await MapStoryDevFixture.DatabaseAsync(); return; +} + +if (args.Contains("--maps-story-dev-fixture")) +{ + await MapStoryDevFixture.RunAsync(args); return; +} + +if (args.Contains("--maps-story")) +{ + MapStoryTests.ProjectionAndEvidence(); MapStoryTests.SecurityAndBatching(); MapStoryTests.Scale(); MapTests.ValidationAndAccess(); + Console.WriteLine("PASS focused Maps Story hierarchy, chronology, journey evidence, access and batching"); return; +} + if (args.Contains("--toolbar-browser-host")) { await ToolbarBrowserHost.RunAsync(); @@ -104,6 +120,9 @@ var tests = new (string Name, Action Test)[] ("Writing Solver scoring, multi-select, revision, fallback and graph routes", WritingSolverTests.RoutingAndRevision), ("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation), ("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata), + ("Maps Story projects canonical hierarchy, sequence, journeys and evidence without changing geography", MapStoryTests.ProjectionAndEvidence), + ("Maps Story scales to 500 scenes and 5,000 appearances", MapStoryTests.Scale), + ("Maps Story enforces access and uses bounded repository batches", MapStoryTests.SecurityAndBatching), ("Maps validate rough geometry, relationships, Location intent and access boundaries", MapTests.ValidationAndAccess), ("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), diff --git a/PlotLine.Tests/Sql/210_MapStoryAssertions.sql b/PlotLine.Tests/Sql/210_MapStoryAssertions.sql new file mode 100644 index 00000000..90e717d7 --- /dev/null +++ b/PlotLine.Tests/Sql/210_MapStoryAssertions.sql @@ -0,0 +1,44 @@ +-- Appended to 210_MapStoryFixture.sql within an outer transaction by --maps-story-database. +EXEC dbo.StoryMap_Story @ProjectID=@project,@MapID=@map,@UserID=@UserID; +IF (SELECT COUNT(*) FROM dbo.NarrativeSceneOrder WHERE ProjectID=@project)<>6 THROW 51000,'Fixture manuscript order is incomplete.',1; +EXEC dbo.StoryMap_JourneySave @ProjectID=@project,@MapID=@map,@UserID=@UserID,@CharacterID=@ari,@FromSceneID=@s1,@ToSceneID=@s2,@RouteFeatureID=@road,@TravelMethod='Walk',@TypicalMinutes=180; +IF (SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map)<>1 OR NOT EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map AND TravelMethod='Walk' AND RouteFeatureID=@road AND TypicalMinutes=180) THROW 51000,'Annotations must persist without geography revision changes.',1; +SET @features=(SELECT * FROM dbo.MapFeatures WHERE MapID=@map FOR JSON PATH); +SET @relationships=(SELECT * FROM dbo.MapRelationships WHERE MapID=@map FOR JSON PATH); +EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@UserID,@Revision=1,@Name='Story region',@Kind='Region',@Features=@features,@Relationships=@relationships; +IF NOT EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map AND RouteFeatureID=@road) THROW 51000,'Normal geography save lost an explicit route association.',1; +SET @features=(SELECT * FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID<>@road FOR JSON PATH); +EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@UserID,@Revision=2,@Name='Story region',@Kind='Region',@Features=@features,@Relationships=@relationships; +IF NOT EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map AND RouteFeatureID IS NULL AND TravelMethod='Walk' AND TypicalMinutes=180) THROW 51000,'Deleted routes must detach without replacing author travel context.',1; +EXEC dbo.StoryMap_JourneySave @ProjectID=@project,@MapID=@map,@UserID=@UserID,@CharacterID=@ari,@FromSceneID=@s1,@ToSceneID=@s2; +IF EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map) OR (SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map)<>3 THROW 51000,'Clearing annotations changed geography or retained metadata.',1; +EXEC dbo.StoryMap_JourneySave @ProjectID=@project,@MapID=@map,@UserID=@UserID,@CharacterID=@ari,@FromSceneID=@s1,@ToSceneID=@s2,@TravelMethod='Car',@TypicalMinutes=120; +-- Archiving canonical scenes hides them from active projections but must not break backup restoration. +UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@s2; +DECLARE @json nvarchar(max)=(SELECT 'PlotDirector.ProjectBackup' Format,'1.1' FormatVersion,JSON_QUERY((SELECT * FROM dbo.Projects WHERE ProjectID=@project FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Project, + JSON_QUERY((SELECT + JSON_QUERY((SELECT * FROM dbo.Books WHERE ProjectID=@project FOR JSON PATH)) Books, + JSON_QUERY((SELECT * FROM dbo.Chapters WHERE BookID=@book FOR JSON PATH)) Chapters, + JSON_QUERY((SELECT * FROM dbo.Scenes WHERE ChapterID IN(@chapter1,@chapter2) FOR JSON PATH)) Scenes, + JSON_QUERY((SELECT * FROM dbo.Characters WHERE ProjectID=@project FOR JSON PATH)) Characters, + JSON_QUERY((SELECT * FROM dbo.SceneCharacters WHERE CharacterID IN(@ari,@bea) FOR JSON PATH)) SceneCharacters, + JSON_QUERY((SELECT * FROM dbo.Locations WHERE ProjectID=@project FOR JSON PATH)) Locations, + JSON_QUERY((SELECT * FROM dbo.PlotLines WHERE ProjectID=@project FOR JSON PATH)) PlotLines, + JSON_QUERY((SELECT * FROM dbo.PlotThreads WHERE PlotLineID=@plot FOR JSON PATH)) PlotThreads, + JSON_QUERY((SELECT * FROM dbo.ThreadEvents WHERE PlotThreadID=@thread FOR JSON PATH)) ThreadEvents, + JSON_QUERY((SELECT * FROM dbo.FloorPlans WHERE ProjectID=@project FOR JSON PATH)) FloorPlans, + JSON_QUERY((SELECT * FROM dbo.FloorPlanFloors WHERE FloorPlanID=@floorplan FOR JSON PATH)) FloorPlanFloors, + JSON_QUERY((SELECT * FROM dbo.FloorPlanBlocks WHERE FloorPlanFloorID=@floor FOR JSON PATH)) FloorPlanBlocks, + JSON_QUERY((SELECT * FROM dbo.SceneFloorPlanOccupancy WHERE FloorPlanID=@floorplan FOR JSON PATH)) SceneFloorPlanOccupancy, + JSON_QUERY((SELECT * FROM dbo.StoryMaps WHERE ProjectID=@project FOR JSON PATH)) StoryMaps, + JSON_QUERY((SELECT * FROM dbo.MapFeatures WHERE MapID IN(@map,@child) FOR JSON PATH)) MapFeatures, + JSON_QUERY((SELECT * FROM dbo.MapRelationships WHERE MapID IN(@map,@child) FOR JSON PATH)) MapRelationships, + JSON_QUERY((SELECT * FROM dbo.MapJourneyNotes WHERE MapID IN(@map,@child) FOR JSON PATH)) MapJourneyNotes FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Data FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); +EXEC dbo.ProjectRestore_ApplyFromJson @ProjectID=@project,@JsonData=@json; +IF NOT EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map AND TravelMethod='Car' AND TypicalMinutes=120) THROW 51000,'Project restore lost explicit travel metadata for an archived scene.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@map AND LocationID=@a AND FloorPlanID=@floorplan) THROW 51000,'Story restore lost canonical Location or Floor Plan links.',1; +DELETE dbo.SceneCharacters WHERE SceneID=@s2; +DELETE dbo.Scenes WHERE SceneID=@s2; +IF EXISTS(SELECT 1 FROM dbo.MapJourneyNotes WHERE MapID=@map) THROW 51000,'Deleted scenes left journey metadata.',1; +ROLLBACK; +SELECT 'PASS batched Story source; unchanged map revision; explicit route/method/duration persistence; route removal; backup/restore; scene deletion cleanup (all fixtures rolled back)' Result; diff --git a/PlotLine.Tests/Sql/210_MapStoryFixture.sql b/PlotLine.Tests/Sql/210_MapStoryFixture.sql new file mode 100644 index 00000000..31b3ba50 --- /dev/null +++ b/PlotLine.Tests/Sql/210_MapStoryFixture.sql @@ -0,0 +1,82 @@ +-- Explicit fixture: caller supplies @UserID from a dedicated Development test identity. +-- Run inside an outer transaction and roll it back for database regressions. +SET NOCOUNT ON; SET XACT_ABORT ON; +IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Development fixture only.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@UserID) THROW 51000,'Fixture user unavailable.',1; +BEGIN TRAN; +DECLARE @title nvarchar(200)=N'Maps Story fixture '+CONVERT(nvarchar(36),NEWID()); +EXEC dbo.Project_Save @ProjectName=@title,@UserID=@UserID; +DECLARE @project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@title); +EXEC dbo.Book_Save @ProjectID=@project,@BookTitle='Story geography fixture',@BookNumber=1; +DECLARE @book int=(SELECT BookID FROM dbo.Books WHERE ProjectID=@project); +DECLARE @revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder); +EXEC dbo.Chapter_Save @BookID=@book,@ChapterNumber=1,@ChapterTitle='Departure',@RevisionStatusID=@revision; +EXEC dbo.Chapter_Save @BookID=@book,@ChapterNumber=2,@ChapterTitle='Return',@RevisionStatusID=@revision; +DECLARE @chapter1 int=(SELECT ChapterID FROM dbo.Chapters WHERE BookID=@book AND ChapterNumber=1),@chapter2 int=(SELECT ChapterID FROM dbo.Chapters WHERE BookID=@book AND ChapterNumber=2); +EXEC dbo.Location_Save @ProjectID=@project,@LocationName='Harbour',@Description='A working harbour.'; +EXEC dbo.Location_Save @ProjectID=@project,@LocationName='Hill town'; +EXEC dbo.Location_Save @ProjectID=@project,@LocationName='Unmapped town'; +DECLARE @a int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@project AND LocationName='Harbour'),@b int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@project AND LocationName='Hill town'),@unmapped int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@project AND LocationName='Unmapped town'); +EXEC dbo.Location_Save @ProjectID=@project,@LocationName='House room',@ParentLocationID=@a; +DECLARE @room int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@project AND LocationName='House room'); +INSERT dbo.FloorPlans(ProjectID,LocationID,Name) VALUES(@project,@a,'House floor plan'); +DECLARE @floorplan int=CONVERT(int,SCOPE_IDENTITY()); +INSERT dbo.FloorPlanFloors(FloorPlanID,Name,SortOrder,GridWidth,GridHeight) VALUES(@floorplan,'Ground floor',0,24,16); +DECLARE @floor int=CONVERT(int,SCOPE_IDENTITY()); +INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells,BlockType) VALUES(@floor,@room,2,2,4,3,'Room'); +DECLARE @mode int=(SELECT TimeModeID FROM dbo.TimeModes WHERE TimeModeName='Exact DateTime'),@confidence int=(SELECT TimeConfidenceID FROM dbo.TimeConfidences WHERE TimeConfidenceName='Confirmed'); +DECLARE @i int=1,@chapter int,@location int,@sceneTitle nvarchar(200),@time datetime2,@fp int,@initialFloor int; +WHILE @i<=6 +BEGIN + SET @chapter=CASE WHEN @i<=3 THEN @chapter1 ELSE @chapter2 END; + SET @location=CASE @i WHEN 1 THEN @a WHEN 2 THEN @b WHEN 3 THEN @a WHEN 5 THEN @unmapped WHEN 6 THEN @room END; + SET @sceneTitle=CASE @i WHEN 1 THEN 'Harbour morning' WHEN 2 THEN 'Hill arrival' WHEN 3 THEN 'Harbour revisit' WHEN 4 THEN 'Unknown interval' WHEN 5 THEN 'Unmapped scene' ELSE 'House discovery' END; + SET @time=DATEADD(minute,(@i-1)*30,CONVERT(datetime2,'2026-01-01T09:00:00')); + SET @fp=CASE WHEN @i=6 THEN @floorplan END;SET @initialFloor=CASE WHEN @i=6 THEN @floor END; + EXEC dbo.Scene_Save @ChapterID=@chapter,@SceneNumber=@i,@SceneTitle=@sceneTitle,@TimeModeID=@mode,@StartDateTime=@time,@TimeConfidenceID=@confidence,@RevisionStatusID=@revision,@PrimaryLocationID=@location,@FloorPlanID=@fp,@InitialFloorPlanFloorID=@initialFloor; + SET @i+=1; +END; +EXEC dbo.Character_Save @ProjectID=@project,@CharacterName='Ari',@CharacterImportance=9; +EXEC dbo.Character_Save @ProjectID=@project,@CharacterName='Bea',@CharacterImportance=8; +DECLARE @ari int=(SELECT CharacterID FROM dbo.Characters WHERE ProjectID=@project AND CharacterName='Ari'),@bea int=(SELECT CharacterID FROM dbo.Characters WHERE ProjectID=@project AND CharacterName='Bea'); +DECLARE @presence int=(SELECT PresenceTypeID FROM dbo.PresenceTypes WHERE TypeName='Present'); +DECLARE @scene int; +DECLARE scenes CURSOR LOCAL FAST_FORWARD FOR SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@book ORDER BY ch.ChapterNumber,s.SceneNumber; +OPEN scenes;FETCH NEXT FROM scenes INTO @scene; +WHILE @@FETCH_STATUS=0 +BEGIN + EXEC dbo.SceneCharacter_Save @SceneID=@scene,@CharacterID=@ari,@PresenceTypeID=@presence; + FETCH NEXT FROM scenes INTO @scene; +END; +CLOSE scenes;DEALLOCATE scenes; +DECLARE @s1 int=(SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@book AND s.SceneNumber=1), + @s2 int=(SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@book AND s.SceneNumber=2), + @s3 int=(SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@book AND s.SceneNumber=3), + @s6 int=(SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@book AND s.SceneNumber=6); +EXEC dbo.SceneCharacter_Save @SceneID=@s1,@CharacterID=@bea,@PresenceTypeID=@presence,@LocationID=@b; +EXEC dbo.SceneCharacter_Save @SceneID=@s2,@CharacterID=@bea,@PresenceTypeID=@presence,@LocationID=@a; +EXEC dbo.SceneCharacter_Save @SceneID=@s3,@CharacterID=@bea,@PresenceTypeID=@presence,@LocationID=@b; +INSERT dbo.SceneFloorPlanOccupancy(SceneID,FloorPlanID,FloorPlanFloorID,CharacterID,LocationID) VALUES(@s6,@floorplan,@floor,@ari,@room); +DECLARE @plotType int=(SELECT TOP(1) PlotLineTypeID FROM dbo.PlotLineTypes WHERE IsActive=1 ORDER BY SortOrder),@importance int=(SELECT TOP(1) PlotImportanceID FROM dbo.PlotImportance ORDER BY SortOrder), + @threadType int=(SELECT TOP(1) ThreadTypeID FROM dbo.ThreadTypes ORDER BY SortOrder),@threadStatus int=(SELECT TOP(1) ThreadStatusID FROM dbo.ThreadStatuses ORDER BY SortOrder),@eventType int=(SELECT TOP(1) ThreadEventTypeID FROM dbo.ThreadEventTypes ORDER BY SortOrder),@plotEvent int=(SELECT TOP(1) PlotEventTypeID FROM dbo.PlotEventTypes ORDER BY SortOrder); +EXEC dbo.PlotLine_Save @ProjectID=@project,@PlotLineName='The search',@PlotLineTypeID=@plotType,@PlotImportanceID=@importance,@Colour='#265e83',@IsVisibleOnTimeline=0; +DECLARE @plot int=(SELECT PlotLineID FROM dbo.PlotLines WHERE ProjectID=@project); +EXEC dbo.PlotThread_Save @PlotLineID=@plot,@ThreadTitle='Following the clue',@ThreadTypeID=@threadType,@ThreadStatusID=@threadStatus,@Importance=7; +DECLARE @thread int=(SELECT PlotThreadID FROM dbo.PlotThreads WHERE PlotLineID=@plot); +EXEC dbo.ThreadEvent_Save @PlotThreadID=@thread,@SceneID=@s1,@EventTypeID=@eventType,@PlotEventTypeID=@plotEvent,@EventTitle='Departure'; +EXEC dbo.ThreadEvent_Save @PlotThreadID=@thread,@SceneID=@s3,@EventTypeID=@eventType,@PlotEventTypeID=@plotEvent,@EventTitle='Return'; +EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@UserID,@Name='Story region',@Kind='Region'; +DECLARE @map int=(SELECT MapID FROM dbo.StoryMaps WHERE ProjectID=@project),@fa uniqueidentifier=NEWID(),@fb uniqueidentifier=NEWID(),@road uniqueidentifier=NEWID(); +DECLARE @features nvarchar(max)=(SELECT FeatureID,Name,Type,GeometryClass,Layer,X,Y,Width,Height,Rotation,ZOrder,IsPlaced,IsProvisional,IsLocked,ShowLabel,LabelX,LabelY,LocationID,FloorPlanID,StartFeatureID,EndFeatureID,GeometryJson FROM + (SELECT @fa FeatureID,'Map alias A' Name,'Town' Type,'Marker' GeometryClass,'Places' Layer,-250 X,0 Y,42 Width,42 Height,0 Rotation,40 ZOrder,1 IsPlaced,0 IsProvisional,0 IsLocked,1 ShowLabel,0 LabelX,0 LabelY,@a LocationID,@floorplan FloorPlanID,CAST(NULL AS uniqueidentifier) StartFeatureID,CAST(NULL AS uniqueidentifier) EndFeatureID,'{}' GeometryJson + UNION ALL SELECT @fb,'Map alias B','Town','Marker','Places',250,50,42,42,0,40,1,0,0,1,0,0,@b,NULL,NULL,NULL,'{}' + UNION ALL SELECT NEWID(),'Unmapped town','Town','Marker','Places',0,250,42,42,0,40,1,0,0,1,0,0,NULL,NULL,NULL,NULL,'{}' + UNION ALL SELECT @road,'Author road','Road','Path','Routes',0,0,500,100,0,30,1,0,0,1,0,0,NULL,NULL,@fa,@fb,'{"points":[[-0.5,0],[0.5,0]]}') f FOR JSON PATH); +DECLARE @relationships nvarchar(max)=(SELECT NEWID() RelationshipID,@fa SourceID,@fb TargetID,'W' Direction,'Far' RelativeDistance,126 MeasuredDistance,'kilometres' Unit,'3h 30m' TypicalTravelTime FOR JSON PATH); +EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@map,@UserID=@UserID,@Revision=0,@Name='Story region',@Kind='Region',@Features=@features,@Relationships=@relationships; +EXEC dbo.StoryMap_Create @ProjectID=@project,@UserID=@UserID,@Name='House detail',@Kind='Local Area',@ParentMapID=@map,@ParentFeatureID=@fa; +DECLARE @child int=(SELECT MapID FROM dbo.StoryMaps WHERE ProjectID=@project AND ParentMapID=@map); +SET @features=(SELECT NEWID() FeatureID,'House room' Name,'House' Type,'Marker' GeometryClass,'Places' Layer,0 X,0 Y,42 Width,42 Height,0 Rotation,40 ZOrder,1 IsPlaced,0 IsProvisional,0 IsLocked,1 ShowLabel,0 LabelX,0 LabelY,@room LocationID,@floorplan FloorPlanID,'{}' GeometryJson FOR JSON PATH); +EXEC dbo.StoryMap_Save @ProjectID=@project,@MapID=@child,@UserID=@UserID,@Revision=0,@Name='House detail',@Kind='Local Area',@Features=@features,@Relationships='[]'; +COMMIT; +SELECT @project ProjectID,@map MapID,@child ChildMapID,@s1 SceneAID,@s2 SceneBID,@s3 RevisitSceneID,@s6 DetailSceneID,@ari CharacterID,@bea CompareCharacterID,@plot PlotLineID,@chapter1 ChapterID,@chapter2 SecondChapterID,@floorplan FloorPlanID,@road RouteFeatureID,@a LocationAID,@b LocationBID,@unmapped UnmappedLocationID; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 555f6ad6..1e409888 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -105,6 +105,10 @@ internal static class ToolbarBrowserHost app.UseAuthorization(); app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); app.MapGet("/Projects", () => Results.Redirect("/fixture")); + app.MapGet("/map-story-fixture", () => { + var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1); + projection.UserID=4;return Results.Json(projection); + }); app.MapGet("/plot-map-fixture", async context => { var data = context.Request.Query["marketing"] == "true" ? PublicWebsiteFixtures.PlotMap() @@ -347,11 +351,11 @@ internal static class ToolbarBrowserHost if (context.Request.Query["page"] == "maps") { var map = new StoryMap { MapID = 1, ProjectID = 7, Name = "Working geography", Kind = "Region" }; - surface = await Render("Maps/Index", new MapsViewModel { + surface = await Render("Maps/Index", context.Request.Query["story"] == "true" ? MapStoryTests.Workspace() : new MapsViewModel { Project = model.Project!, Maps = [map], Document = new MapDocument { Map = map }, Locations = [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }] }); - surface += ""; + surface += ""; } surface += await Render("Shared/_ConfirmationDialog"); var initialTheme = appearance.ThemeKey ?? "warm-light"; diff --git a/PlotLine/Controllers/MapsController.cs b/PlotLine/Controllers/MapsController.cs index e9f30bee..9b40b410 100644 --- a/PlotLine/Controllers/MapsController.cs +++ b/PlotLine/Controllers/MapsController.cs @@ -59,4 +59,23 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } + [HttpGet] + public async Task Story(int projectId, int id, int? scenarioId, [FromServices] IMapStoryService story) + { + if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); + var projection = await story.GetAsync(projectId, id, UserID, scenarioId); + return projection is null ? NotFound() : Json(projection); + } + [HttpPost, ValidateAntiForgeryToken] + public async Task Journey(int projectId, int? scenarioId, [FromBody] MapJourneyNote note, + [FromServices] IMapStoryService story, [FromServices] IMapStoryRepository repository) + { + if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); + 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 }); } + catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } + } + } diff --git a/PlotLine/Data/MapStoryRepository.cs b/PlotLine/Data/MapStoryRepository.cs new file mode 100644 index 00000000..7f3e7c74 --- /dev/null +++ b/PlotLine/Data/MapStoryRepository.cs @@ -0,0 +1,33 @@ +using System.Data; +using Dapper; +using PlotLine.Models; +namespace PlotLine.Data; + +public interface IMapStoryRepository +{ + Task GetAsync(int projectId, int mapId, int userId); + Task SaveJourneyAsync(int projectId, int userId, MapJourneyNote note); +} +public sealed class MapStoryRepository(ISqlConnectionFactory connections) : IMapStoryRepository +{ + public async Task GetAsync(int projectId, int mapId, int userId) + { + using var db = connections.CreateConnection(); + using var rows = await db.QueryMultipleAsync("dbo.StoryMap_Story", new { ProjectID = projectId, MapID = mapId, UserID = userId }, commandType: CommandType.StoredProcedure); + var exists = await rows.ReadSingleAsync(); + if (!exists) return null; + return new MapStoryData { + Scenes = (await rows.ReadAsync()).AsList(), Characters = (await rows.ReadAsync()).AsList(), + Appearances = (await rows.ReadAsync()).AsList(), Locations = (await rows.ReadAsync()).AsList(), + Maps = (await rows.ReadAsync()).AsList(), Features = (await rows.ReadAsync()).AsList(), + Relationships = (await rows.ReadAsync()).AsList(), FloorPlans = (await rows.ReadAsync()).AsList(), + JourneyNotes = (await rows.ReadAsync()).AsList() + }; + } + public async Task SaveJourneyAsync(int projectId, int userId, MapJourneyNote note) + { + using var db = connections.CreateConnection(); + await db.ExecuteAsync("dbo.StoryMap_JourneySave", new { ProjectID = projectId, UserID = userId, note.MapID, note.CharacterID, + note.FromSceneID, note.ToSceneID, note.RouteFeatureID, note.TravelMethod, note.TypicalMinutes }, commandType: CommandType.StoredProcedure); + } +} diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index 9a8a81e5..9c3dcd9b 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -85,6 +85,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact data.StoryMaps = (await mapRows.ReadAsync()).ToList(); data.MapFeatures = (await mapRows.ReadAsync()).ToList(); data.MapRelationships = (await mapRows.ReadAsync()).ToList(); + data.MapJourneyNotes = (await mapRows.ReadAsync()).ToList(); } var bookMetadata = (await connection.QueryAsync( @@ -148,6 +149,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact nameof(data.RelationshipEvents), nameof(data.Locations), nameof(data.LocationRelationships), + nameof(data.MapJourneyNotes), nameof(data.StoryMaps), nameof(data.MapFeatures), nameof(data.MapRelationships), diff --git a/PlotLine/Models/MapStoryModels.cs b/PlotLine/Models/MapStoryModels.cs new file mode 100644 index 00000000..40fdcdf6 --- /dev/null +++ b/PlotLine/Models/MapStoryModels.cs @@ -0,0 +1,100 @@ +namespace PlotLine.Models; + +// Projections reference canonical manuscript IDs; none of these are map-owned story facts. +public sealed class MapStoryScene +{ + public int SceneID { get; set; } + public int BookID { get; set; } + public int ChapterID { get; set; } + public int NarrativeOrder { get; set; } + public string BookTitle { get; set; } = ""; + public decimal ChapterNumber { get; set; } + public string ChapterTitle { get; set; } = ""; + public decimal SceneNumber { get; set; } + public string SceneTitle { get; set; } = ""; + public string? Summary { get; set; } + public int? PrimaryLocationID { get; set; } + public int? FloorPlanID { get; set; } + public DateTime? StartDateTime { get; set; } + public DateTime? EndDateTime { get; set; } + public string TimeModeName { get; set; } = ""; + public string TimeConfidenceName { get; set; } = ""; + public string? RelativeTimeText { get; set; } + public string? TimePrecision => TimeConfidenceName == "Confirmed" && StartDateTime.HasValue ? TimeModeName switch { "Exact DateTime" => "Timestamp", "Exact Date" => "Day", _ => null } : null; + public MapStoryLocation Position { get; set; } = new(); + public List CharacterIDs { get; set; } = []; + public List PlotLineIDs { get; set; } = []; +} +public sealed class MapStoryLocation +{ + public int? LocationID { get; set; } + public string? LocationName { get; set; } + public Guid? FeatureID { get; set; } + public int? DetailMapID { get; set; } + public int? FloorPlanID { get; set; } + public string Status { get; set; } = "No Location"; + public bool IsProvisional { get; set; } +} +public sealed class MapStoryStop +{ + public int CharacterID { get; set; } + public int SceneID { get; set; } + public int Sequence { get; set; } + public MapStoryLocation Position { get; set; } = new(); + public string Evidence { get; set; } = ""; + public DateTime? ObservedAt { get; set; } + public string? TimePrecision { get; set; } +} +public sealed class MapJourneyNote +{ + public int MapID { get; set; } + public int CharacterID { get; set; } + public int FromSceneID { get; set; } + public int ToSceneID { get; set; } + public Guid? RouteFeatureID { get; set; } + public string? TravelMethod { get; set; } + public int? TypicalMinutes { get; set; } +} +public sealed class MapStoryLeg +{ + public int CharacterID { get; set; } + public int FromSceneID { get; set; } + public int ToSceneID { get; set; } + public MapStoryLocation From { get; set; } = new(); + public MapStoryLocation To { get; set; } = new(); + public string? Direction { get; set; } + public string? RelativeDistance { get; set; } + public decimal? MeasuredDistance { get; set; } + public string? Unit { get; set; } + public string? TypicalTravelTime { get; set; } + public int? TypicalMinutes { get; set; } + public double? ElapsedMinutes { get; set; } + public int EvidenceLevel { get; set; } + public bool TimingObservation { get; set; } + public MapJourneyNote? Note { get; set; } +} +public sealed class MapStoryData +{ + public List Scenes { get; set; } = []; + public List Characters { get; set; } = []; + public List Appearances { get; set; } = []; + public List Locations { get; set; } = []; + public List Maps { get; set; } = []; + public List Features { get; set; } = []; + public List Relationships { get; set; } = []; + public List FloorPlans { get; set; } = []; + public List JourneyNotes { get; set; } = []; +} +public sealed class MapStoryProjection +{ + public int UserID { get; set; } + public int MapID { get; set; } + public int? ScenarioID { get; set; } + public List Scenes { get; set; } = []; + public List Characters { get; set; } = []; + public List Stops { get; set; } = []; + public List Legs { get; set; } = []; + public List PlotLines { get; set; } = []; + public List Scenarios { get; set; } = []; +} +public sealed record MapStoryPerson(int CharacterID, string Name, int Importance); diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 7cfde999..5afb39ba 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -13,6 +13,7 @@ public sealed class ProjectBackupExport public sealed class ProjectBackupData { + public IReadOnlyList MapJourneyNotes { get; set; } = []; public IReadOnlyList StoryMaps { get; set; } = []; public IReadOnlyList MapFeatures { get; set; } = []; public IReadOnlyList MapRelationships { get; set; } = []; diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 71139f7c..5c9de12e 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -142,6 +142,8 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/MapStoryService.cs b/PlotLine/Services/MapStoryService.cs new file mode 100644 index 00000000..8420102b --- /dev/null +++ b/PlotLine/Services/MapStoryService.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using PlotLine.Data; +using PlotLine.Models; +namespace PlotLine.Services; + +public interface IMapStoryService +{ + Task GetAsync(int projectId, int mapId, int userId, int? scenarioId = null); +} +public sealed class MapStoryService(IMapStoryRepository repository, IPlotLineWorkspaceRepository plots, + IScenarioRepository scenarios, IProjectAccessService access) : IMapStoryService +{ + public async Task GetAsync(int projectId, int mapId, int userId, int? scenarioId = null) + { + if (!await access.CanAccessProjectAsync(projectId)) return null; + var choices = await scenarios.ListAsync(projectId); + if (scenarioId.HasValue && !choices.Any(s => s.ScenarioID == scenarioId && !s.IsArchived)) return null; + var source = await repository.GetAsync(projectId, mapId, userId); + if (source is null) return null; + var membership = await plots.GetAsync(projectId, null, scenarioId); + // Scenario order is supplied by the same projection which owns Plot Lines membership. + if (scenarioId.HasValue) + { + var order = membership.AttributionScenes.ToDictionary(s => s.SceneID); + var titles = source.Scenes.DistinctBy(s => s.BookID).ToDictionary(s => s.BookID, s => s.BookTitle); + source.Scenes = source.Scenes.Where(s => order.ContainsKey(s.SceneID)).ToList(); + foreach (var scene in source.Scenes) { var entry = order[scene.SceneID]; scene.NarrativeOrder = entry.NarrativeOrder; scene.ChapterID = entry.ChapterID; scene.ChapterNumber = entry.ChapterNumber; scene.ChapterTitle = entry.ChapterTitle; scene.BookID = entry.BookID; scene.BookTitle = titles.GetValueOrDefault(entry.BookID) ?? "Book"; } + } + var projection = MapStoryComposer.Compose(source, membership, mapId); + projection.UserID = userId; projection.ScenarioID = scenarioId; projection.Scenarios = choices.Where(s => !s.IsArchived).ToList(); + return projection; + } +} + +public static class MapStoryComposer +{ + // Catalogue/Location hierarchy and explicit parent-feature links are the only spatial evidence. + public static Func Resolver(MapStoryData data, int mapId) + { + var locations = data.Locations.ToDictionary(x => x.LocationID); + var maps = data.Maps.ToDictionary(x => x.MapID); + var current = data.Features.Where(f => f.MapID == mapId).OrderBy(f => f.IsProvisional).ThenBy(f => f.FeatureID).ToList(); + var byLocation = data.Features.Where(f => f.LocationID.HasValue && f.IsPlaced).GroupBy(f => f.LocationID!.Value) + .ToDictionary(g => g.Key, g => g.OrderBy(f => f.IsProvisional).ThenBy(f => f.MapID).ThenBy(f => f.FeatureID).ToList()); + var cache = new Dictionary(); + MapStoryLocation Resolve(int? id) + { + if (!id.HasValue) return new(); + if (cache.TryGetValue(id.Value, out var cached)) return cached; + var result = new MapStoryLocation { LocationID = id, LocationName = locations.GetValueOrDefault(id.Value)?.LocationName, Status = "Unmapped" }; + var chain = new List(); var seen = new HashSet(); int? cursor = id; + while (cursor.HasValue && seen.Add(cursor.Value)) { chain.Add(cursor.Value); cursor = locations.GetValueOrDefault(cursor.Value)?.ParentLocationID; } + foreach (var locationId in chain) + { + var match = current.FirstOrDefault(f => f.IsPlaced && f.LocationID == locationId); + if (match is not null) { Assign(result, match, locationId == id ? "Exact" : "Ancestor location"); break; } + } + { + foreach (var locationId in chain) + { + foreach (var candidate in byLocation.GetValueOrDefault(locationId) ?? []) + { + var pathSeen = new HashSet(); var map = maps.GetValueOrDefault(candidate.MapID); + while (map?.ParentMapID is int parent && pathSeen.Add(map.MapID)) + { + if (parent == mapId) + { + var anchor = current.FirstOrDefault(f => f.FeatureID == map.ParentFeatureID && f.IsPlaced); + if (anchor is not null && !result.FeatureID.HasValue) Assign(result, anchor, "Detail map"); + else if (anchor is null && !result.FeatureID.HasValue) result.Status = "On detail map"; + result.DetailMapID = candidate.MapID; + break; + } + map = maps.GetValueOrDefault(parent); + } + if (result.DetailMapID.HasValue) break; + } + if (result.DetailMapID.HasValue) break; + } + } + if (!result.FeatureID.HasValue && !result.DetailMapID.HasValue) + { + var map = maps.GetValueOrDefault(mapId); var mapSeen = new HashSet(); + while (map?.ParentMapID is int parent && mapSeen.Add(map.MapID)) + { + if (data.Features.Any(f => f.MapID == parent && f.IsPlaced && chain.Contains(f.LocationID ?? -1))) + { result.DetailMapID = parent; result.Status = "On ancestor map"; break; } + map = maps.GetValueOrDefault(parent); + } + } + result.FloorPlanID ??= data.FloorPlans.FirstOrDefault(f => chain.Contains(f.LocationID ?? -1))?.FloorPlanID; + cache[id.Value] = result; return result; + } + return Resolve; + } + private static void Assign(MapStoryLocation result, MapFeature f, string status) + { result.FeatureID = f.FeatureID; result.FloorPlanID = f.FloorPlanID; result.Status = status; result.IsProvisional = f.IsProvisional; } + + public static bool PhysicalAppearance(SceneCharacter appearance) => + appearance.RoleInSceneTypeName != "Mentioned Only" && appearance.PresenceTypeName is not ("Mentioned Only" or "Off-screen"); + private static int? AppearanceLocation(SceneCharacter a, MapStoryScene s) => + a.PresenceTypeName == "Unknown" ? null : a.ExitLocationID ?? a.LocationID ?? + (a.PresenceTypeName is "Present" or "Arrives" or "Leaves" or "Nearby" or "Hidden" or "Overhearing" ? s.PrimaryLocationID : null); + + public static MapStoryProjection Compose(MapStoryData data, PlotLineWorkspaceData plots, int mapId) + { + var resolve = Resolver(data, mapId); + var scenes = data.Scenes.OrderBy(s => s.NarrativeOrder).ThenBy(s => s.SceneID).ToList(); + var byId = scenes.ToDictionary(s => s.SceneID); + var memberships = plots.Contributions.GroupBy(c => c.SceneID).ToDictionary(g => g.Key, g => g.Select(c => c.PlotLineID).Distinct().ToList()); + var appearances = data.Appearances.Where(a => byId.ContainsKey(a.SceneID)).ToList(); + var people = appearances.GroupBy(a => a.SceneID).ToDictionary(g => g.Key, g => g.Select(a => a.CharacterID).Distinct().ToList()); + foreach (var scene in scenes) { scene.Position = resolve(scene.PrimaryLocationID); scene.CharacterIDs = people.GetValueOrDefault(scene.SceneID) ?? []; scene.PlotLineIDs = memberships.GetValueOrDefault(scene.SceneID) ?? []; } + var result = new MapStoryProjection { MapID = mapId, Scenes = scenes, + Characters = data.Characters.OrderByDescending(c => c.CharacterImportance).ThenBy(c => c.CharacterName).Select(c => new MapStoryPerson(c.CharacterID, c.CharacterName, c.CharacterImportance ?? 0)).ToList(), PlotLines = plots.PlotLines.ToList() }; + var relationships = data.Relationships.Where(r => r.MapID == mapId).ToLookup(r => (r.SourceID, r.TargetID)); + var notes = data.JourneyNotes.Where(n => n.MapID == mapId).ToDictionary(n => (n.CharacterID, n.FromSceneID, n.ToSceneID)); + foreach (var group in appearances.Where(PhysicalAppearance).GroupBy(a => a.CharacterID)) + { + var ordered = group.OrderBy(a => byId[a.SceneID].NarrativeOrder).ThenBy(a => a.SceneCharacterID).DistinctBy(a => a.SceneID).ToList(); + MapStoryStop? previous = null; var sequence = 0; + foreach (var a in ordered) + { + var scene = byId[a.SceneID]; var locationId = AppearanceLocation(a, scene); + var stop = new MapStoryStop { CharacterID = a.CharacterID, SceneID = a.SceneID, Sequence = ++sequence, + Position = resolve(locationId), ObservedAt = a.ExitLocationID.HasValue ? scene.EndDateTime : scene.StartDateTime, + TimePrecision = a.ExitLocationID.HasValue && (!scene.EndDateTime.HasValue || scene.EndDateTime < scene.StartDateTime) ? null : scene.TimePrecision, Evidence = locationId.HasValue ? (a.ExitLocationID.HasValue ? "Explicit exit Location" : a.LocationID.HasValue ? "Explicit character Location" : "Scene Location with physical presence") : "Position unknown" }; + result.Stops.Add(stop); + if (previous is not null) + { + var leg = new MapStoryLeg { CharacterID = a.CharacterID, FromSceneID = previous.SceneID, ToSceneID = a.SceneID, From = previous.Position, To = stop.Position, + Note = notes.GetValueOrDefault((a.CharacterID, previous.SceneID, a.SceneID)) }; + // Aggregated ancestors are useful display anchors, not exact endpoints for timing evidence. + var exact = leg.From.Status == "Exact" && leg.To.Status == "Exact" && !leg.From.IsProvisional && !leg.To.IsProvisional; + var relation = exact ? relationships[(leg.From.FeatureID!.Value, leg.To.FeatureID!.Value)].FirstOrDefault() + ?? relationships[(leg.To.FeatureID!.Value, leg.From.FeatureID!.Value)].FirstOrDefault() : null; + if (relation is not null) + { + leg.Direction = relation.SourceID == leg.From.FeatureID ? relation.Direction : Reverse(relation.Direction); + leg.RelativeDistance = relation.RelativeDistance; leg.MeasuredDistance = relation.MeasuredDistance; leg.Unit = relation.Unit; + leg.TypicalTravelTime = relation.TypicalTravelTime; leg.TypicalMinutes = ParseMinutes(relation.TypicalTravelTime); + leg.EvidenceLevel = relation.MeasuredDistance.HasValue ? 2 : 1; + } + if (leg.Note?.TypicalMinutes is int minutes) leg.TypicalMinutes = minutes; + var origin = byId[leg.FromSceneID]; + if (exact && leg.From.LocationID != leg.To.LocationID && previous.TimePrecision == "Timestamp" && stop.TimePrecision == "Timestamp" + && (origin.EndDateTime is null || origin.EndDateTime >= origin.StartDateTime)) + { + leg.ElapsedMinutes = (stop.ObservedAt!.Value - previous.ObservedAt!.Value).TotalMinutes; + if (leg.TypicalMinutes is > 0 && leg.ElapsedMinutes >= 0) + { leg.EvidenceLevel = 3; leg.TimingObservation = leg.ElapsedMinutes < leg.TypicalMinutes; } + } + result.Legs.Add(leg); + } + previous = stop; + } + } + return result; + } + private static string? Reverse(string? d) => d is null ? null : MapValidation.Directions[(Array.IndexOf(MapValidation.Directions, d) + 4) % 8]; + // Deliberately constrained duration syntax; vague/descriptive prose remains context, never timing evidence. + public static int? ParseMinutes(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return null; + var m = Regex.Match(text.Trim(), @"^(?:(?\d+(?:\.\d+)?)\s*(?:h|hours?|hrs?)\s*)?(?:(?\d+(?:\.\d+)?)\s*(?:m|minutes?|mins?)\s*)?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + if (!m.Success || (!m.Groups["h"].Success && !m.Groups["m"].Success)) return null; + var total = (m.Groups["h"].Success ? double.Parse(m.Groups["h"].Value, CultureInfo.InvariantCulture) * 60 : 0) + + (m.Groups["m"].Success ? double.Parse(m.Groups["m"].Value, CultureInfo.InvariantCulture) : 0); + return total is > 0 and <= 525600 ? (int)Math.Ceiling(total) : null; + } +} diff --git a/PlotLine/Sql/210_MapStoryMode.sql b/PlotLine/Sql/210_MapStoryMode.sql new file mode 100644 index 00000000..2acc1e2f --- /dev/null +++ b/PlotLine/Sql/210_MapStoryMode.sql @@ -0,0 +1,408 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.MapJourneyNotes','U') IS NULL +BEGIN + CREATE TABLE dbo.MapJourneyNotes( + MapID int NOT NULL REFERENCES dbo.StoryMaps(MapID) ON DELETE CASCADE, + CharacterID int NOT NULL, FromSceneID int NOT NULL, ToSceneID int NOT NULL, + RouteFeatureID uniqueidentifier NULL, TravelMethod nvarchar(80) NULL, TypicalMinutes int NULL, + CONSTRAINT PK_MapJourneyNotes PRIMARY KEY(MapID,CharacterID,FromSceneID,ToSceneID), + CONSTRAINT CK_MapJourneyNotes CHECK(FromSceneID<>ToSceneID AND (TypicalMinutes IS NULL OR TypicalMinutes BETWEEN 1 AND 525600)) + ); +END; +GO +-- Canonical IDs are validated on write. Cleanup triggers avoid additional cascade paths +-- through the two Scene references and do not block existing project/account deletion. +CREATE OR ALTER TRIGGER dbo.MapJourneyNotes_ScenesDeleted ON dbo.Scenes AFTER DELETE AS +BEGIN + SET NOCOUNT ON; + DELETE n FROM dbo.MapJourneyNotes n WHERE EXISTS(SELECT 1 FROM deleted d WHERE d.SceneID=n.FromSceneID OR d.SceneID=n.ToSceneID); +END; +GO +CREATE OR ALTER TRIGGER dbo.MapJourneyNotes_CharactersDeleted ON dbo.Characters AFTER DELETE AS +BEGIN + SET NOCOUNT ON; + DELETE n FROM dbo.MapJourneyNotes n JOIN deleted d ON d.CharacterID=n.CharacterID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Story @ProjectID int,@MapID int,@UserID int +AS +BEGIN + SET NOCOUNT ON; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + DECLARE @exists bit=CASE WHEN EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE MapID=@MapID AND ProjectID=@ProjectID) THEN 1 ELSE 0 END; + SELECT @exists; + IF @exists=0 RETURN; + SELECT nso.SceneID,nso.BookID,nso.ChapterID,CONVERT(int,nso.GlobalSceneIndex) AS NarrativeOrder, + b.BookTitle,nso.ChapterNumber,nso.ChapterTitle,nso.SceneNumber,s.SceneTitle,s.Summary,s.PrimaryLocationID,s.FloorPlanID, + s.StartDateTime,s.EndDateTime,tm.TimeModeName,tc.TimeConfidenceName,s.RelativeTimeText + INTO #scenes FROM dbo.NarrativeSceneOrder nso JOIN dbo.Scenes s ON s.SceneID=nso.SceneID + JOIN dbo.Books b ON b.BookID=nso.BookID + JOIN dbo.TimeModes tm ON tm.TimeModeID=s.TimeModeID JOIN dbo.TimeConfidences tc ON tc.TimeConfidenceID=s.TimeConfidenceID + WHERE nso.ProjectID=@ProjectID; + SELECT * FROM #scenes ORDER BY NarrativeOrder; + SELECT CharacterID,CharacterName,CharacterImportance FROM dbo.Characters WHERE ProjectID=@ProjectID AND IsArchived=0 ORDER BY CharacterID; + SELECT sc.SceneCharacterID,sc.SceneID,sc.CharacterID,sc.LocationID,sc.EntryLocationID,sc.ExitLocationID, + presence.TypeName AS PresenceTypeName,role.TypeName AS RoleInSceneTypeName + FROM dbo.SceneCharacters sc JOIN #scenes s ON s.SceneID=sc.SceneID + JOIN dbo.Characters ch ON ch.CharacterID=sc.CharacterID AND ch.ProjectID=@ProjectID AND ch.IsArchived=0 + LEFT JOIN dbo.PresenceTypes presence ON presence.PresenceTypeID=sc.PresenceTypeID + LEFT JOIN dbo.CharacterRoleInSceneTypes role ON role.CharacterRoleInSceneTypeID=sc.RoleInSceneTypeID; + SELECT LocationID,ParentLocationID,LocationName,Description FROM dbo.Locations WHERE ProjectID=@ProjectID AND IsArchived=0; + SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision FROM dbo.StoryMaps WHERE ProjectID=@ProjectID; + SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + SELECT * FROM dbo.MapRelationships WHERE MapID=@MapID; + SELECT FloorPlanID,ProjectID,LocationID,Name,Description FROM dbo.FloorPlans WHERE ProjectID=@ProjectID; + SELECT n.MapID,n.CharacterID,n.FromSceneID,n.ToSceneID,f.FeatureID AS RouteFeatureID,n.TravelMethod,n.TypicalMinutes + FROM dbo.MapJourneyNotes n JOIN #scenes a ON a.SceneID=n.FromSceneID JOIN #scenes b ON b.SceneID=n.ToSceneID + JOIN dbo.Characters c ON c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID AND c.IsArchived=0 + LEFT JOIN dbo.MapFeatures f ON f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID + WHERE n.MapID=@MapID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_JourneySave + @ProjectID int,@MapID int,@UserID int,@CharacterID int,@FromSceneID int,@ToSceneID int, + @RouteFeatureID uniqueidentifier=NULL,@TravelMethod nvarchar(80)=NULL,@TypicalMinutes int=NULL +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + BEGIN TRAN; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@MapID AND ProjectID=@ProjectID) + THROW 51000,'Map unavailable.',1; + IF @FromSceneID=@ToSceneID OR NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@CharacterID AND ProjectID=@ProjectID AND IsArchived=0) + OR (SELECT COUNT(DISTINCT nso.SceneID) FROM dbo.NarrativeSceneOrder nso JOIN dbo.SceneCharacters sc ON sc.SceneID=nso.SceneID + WHERE nso.ProjectID=@ProjectID AND sc.CharacterID=@CharacterID AND nso.SceneID IN(@FromSceneID,@ToSceneID))<>2 + THROW 51000,'Choose character appearances in this project.',1; + IF @RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@MapID AND FeatureID=@RouteFeatureID AND GeometryClass='Path') + THROW 51000,'Choose a path on this map.',1; + IF @TypicalMinutes IS NOT NULL AND @TypicalMinutes NOT BETWEEN 1 AND 525600 THROW 51000,'Check the typical journey duration.',1; + SET @TravelMethod=NULLIF(LTRIM(RTRIM(@TravelMethod)),''); + IF @RouteFeatureID IS NULL AND @TravelMethod IS NULL AND @TypicalMinutes IS NULL + DELETE dbo.MapJourneyNotes WHERE MapID=@MapID AND CharacterID=@CharacterID AND FromSceneID=@FromSceneID AND ToSceneID=@ToSceneID; + ELSE + BEGIN + UPDATE dbo.MapJourneyNotes SET RouteFeatureID=@RouteFeatureID,TravelMethod=@TravelMethod,TypicalMinutes=@TypicalMinutes + WHERE MapID=@MapID AND CharacterID=@CharacterID AND FromSceneID=@FromSceneID AND ToSceneID=@ToSceneID; + IF @@ROWCOUNT=0 INSERT dbo.MapJourneyNotes(MapID,CharacterID,FromSceneID,ToSceneID,RouteFeatureID,TravelMethod,TypicalMinutes) + VALUES(@MapID,@CharacterID,@FromSceneID,@ToSceneID,@RouteFeatureID,@TravelMethod,@TypicalMinutes); + END; + COMMIT; +END; +GO + +-- Preserve journey annotations across the Stage 1 replace-in-transaction geometry save. +CREATE OR ALTER PROCEDURE dbo.StoryMap_Save @ProjectID int,@MapID int,@UserID int,@Revision int,@Name nvarchar(200),@Kind nvarchar(40),@Features nvarchar(max),@Relationships nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + BEGIN TRAN; + EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@MapID AND ProjectID=@ProjectID AND Revision=@Revision) THROW 51000,'Map changed in another window. Reload before saving; your edits are still here.',1; + SELECT * INTO #f FROM OPENJSON(@Features) WITH ( +[FeatureID] uniqueidentifier '$.FeatureID', +[Name] nvarchar(200) '$.Name', +[Type] nvarchar(60) '$.Type', +[GeometryClass] nvarchar(12) '$.GeometryClass', +[Layer] nvarchar(30) '$.Layer', +[X] float '$.X', +[Y] float '$.Y', +[Width] float '$.Width', +[Height] float '$.Height', +[Rotation] float '$.Rotation', +[ZOrder] int '$.ZOrder', +[IsPlaced] bit '$.IsPlaced', +[IsProvisional] bit '$.IsProvisional', +[IsLocked] bit '$.IsLocked', +[ShowLabel] bit '$.ShowLabel', +[LabelX] float '$.LabelX', +[LabelY] float '$.LabelY', +[LocationID] int '$.LocationID', +[FloorPlanID] int '$.FloorPlanID', +[StartFeatureID] uniqueidentifier '$.StartFeatureID', +[EndFeatureID] uniqueidentifier '$.EndFeatureID', +[GeometryJson] nvarchar(max) '$.GeometryJson', +[Notes] nvarchar(4000) '$.Notes',CreateLocation bit '$.CreateLocation'); + IF EXISTS(SELECT 1 FROM #f f WHERE LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations l WHERE l.LocationID=f.LocationID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Locations in this project.',1; + IF EXISTS(SELECT 1 FROM #f f WHERE FloorPlanID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.FloorPlans l WHERE l.FloorPlanID=f.FloorPlanID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Floor Plans in this project.',1; + IF EXISTS(SELECT 1 FROM #f f WHERE (StartFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.StartFeatureID AND x.GeometryClass='Marker')) OR (EndFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.EndFeatureID AND x.GeometryClass='Marker'))) THROW 51000,'Route endpoints must be places on this map.',1; + -- Create only on explicit request, atomically with the map revision. Retry cannot duplicate a Location. + DECLARE @fid uniqueidentifier,@label nvarchar(200),@lid int; + DECLARE @created table(ID int); + DECLARE places CURSOR LOCAL FAST_FORWARD FOR SELECT FeatureID,Name FROM #f WHERE CreateLocation=1 AND LocationID IS NULL; + OPEN places; FETCH NEXT FROM places INTO @fid,@label; + WHILE @@FETCH_STATUS=0 + BEGIN + DELETE FROM @created; + INSERT @created EXEC dbo.Location_Save @ProjectID=@ProjectID,@LocationName=@label; + SELECT @lid=ID FROM @created; + UPDATE #f SET LocationID=@lid WHERE FeatureID=@fid; + FETCH NEXT FROM places INTO @fid,@label; + END; + CLOSE places; DEALLOCATE places; + DELETE dbo.MapRelationships WHERE MapID=@MapID; + -- Detach links to removed parent features, preserving the detailed maps themselves. + UPDATE dbo.StoryMaps SET ParentFeatureID=NULL,Revision=Revision+1 WHERE ParentMapID=@MapID AND ParentFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f WHERE FeatureID=ParentFeatureID); + DELETE dbo.MapFeatures WHERE MapID=@MapID; + INSERT dbo.MapFeatures(MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes]) SELECT @MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes] FROM #f; + INSERT dbo.MapRelationships(MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes]) SELECT @MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes] FROM OPENJSON(@Relationships) WITH ([RelationshipID] uniqueidentifier '$.RelationshipID',[SourceID] uniqueidentifier '$.SourceID',[TargetID] uniqueidentifier '$.TargetID',[Direction] nvarchar(2) '$.Direction',[RelativeDistance] nvarchar(12) '$.RelativeDistance',[MeasuredDistance] decimal(18,3) '$.MeasuredDistance',[Unit] nvarchar(30) '$.Unit',[TypicalTravelTime] nvarchar(120) '$.TypicalTravelTime',[Notes] nvarchar(1000) '$.Notes'); + UPDATE dbo.StoryMaps SET Name=@Name,Kind=@Kind,Revision=Revision+1,ModifiedDate=SYSUTCDATETIME() WHERE MapID=@MapID; + UPDATE dbo.MapJourneyNotes SET RouteFeatureID=NULL WHERE MapID=@MapID AND RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=@MapID AND f.FeatureID=RouteFeatureID); + COMMIT; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryMap_Backup @ProjectID int,@UserID int=NULL +AS +BEGIN + SET NOCOUNT ON; + -- Same internal/null-user convention as ProjectBackup_Export; public export checks ownership first. + IF @UserID IS NOT NULL EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY MapID; + SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID ORDER BY f.MapID,f.FeatureID; + SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID ORDER BY r.MapID,r.RelationshipID; + SELECT n.* FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson + @ProjectID int, + @SourceRestorePointID int = NULL, + @SafetyRestorePointID int = NULL, + @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF ISJSON(@JsonData) <> 1 + THROW 51001, 'Restore JSON is invalid.', 1; + + IF JSON_VALUE(@JsonData, '$.Format') <> N'PlotDirector.ProjectBackup' + THROW 51002, 'Restore JSON format is not recognised.', 1; + + IF JSON_VALUE(@JsonData, '$.FormatVersion') NOT IN (N'1.0', N'1.1') + THROW 51003, 'Restore JSON format version is not supported.', 1; + + IF TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')) <> @ProjectID + THROW 51004, 'Restore point does not belong to this project.', 1; + + DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY); + INSERT INTO @RestoreTables (TableName) + VALUES + (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'), + (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'), + (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'), + (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'), + (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'), + (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'), + (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'), + (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'), + (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'), + (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'), + (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'), + (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'), + (N'ScenarioWarnings'); + + BEGIN TRANSACTION; + DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0); + + + DECLARE @TableName sysname; + DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN DisableCursor; + FETCH NEXT FROM DisableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;'; + EXEC (@DisableSql); + FETCH NEXT FROM DisableCursor INTO @TableName; + END + CLOSE DisableCursor; + DEALLOCATE DisableCursor; + + DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; + DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID; + DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID; + + DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID; + + DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + + DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo + INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE b.ProjectID = @ProjectID; + + DELETE sd FROM dbo.SceneDependencies sd + LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID + LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID; + + DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID; + DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID; + DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID; + + DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID; + + DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID; + + DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID; + DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID; + + DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID; + + DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID; + + DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.Books WHERE ProjectID = @ProjectID; + DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID; + + UPDATE p + SET ProjectName = src.ProjectName, + Description = src.Description, + CreatedDate = src.CreatedDate, + UpdatedDate = SYSUTCDATETIME(), + IsArchived = src.IsArchived, + ArchivedDate = src.ArchivedDate, + ArchivedReason = src.ArchivedReason + FROM dbo.Projects p + CROSS APPLY OPENJSON(@JsonData, '$.Project') + WITH + ( + ProjectID int '$.ProjectID', + ProjectName nvarchar(200) '$.ProjectName', + Description nvarchar(max) '$.Description', + CreatedDate datetime2 '$.CreatedDate', + IsArchived bit '$.IsArchived', + ArchivedDate datetime2 '$.ArchivedDate', + ArchivedReason nvarchar(1000) '$.ArchivedReason' + ) src + WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0; + + -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography. + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + THROW 51005,'Map backup contains features outside this project.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID) + OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID) + THROW 51005,'Map hierarchy or Location links cross projects.',1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n + WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID) + OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID) + OR (SELECT COUNT(*) FROM dbo.NarrativeSceneOrder nso WHERE nso.ProjectID=@ProjectID AND nso.SceneID IN(n.FromSceneID,n.ToSceneID))<>2 + OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path'))) + THROW 51005,'Journey annotations cross project or map boundaries.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0; + UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID; + + DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN EnableCursor; + FETCH NEXT FROM EnableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;'; + EXEC (@EnableSql); + FETCH NEXT FROM EnableCursor INTO @TableName; + END + CLOSE EnableCursor; + DEALLOCATE EnableCursor; + + IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL + BEGIN + INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes) + VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.'); + END; + + COMMIT TRANSACTION; +END; +GO diff --git a/PlotLine/Sql/211_MapJourneyArchivedSceneRestore.sql b/PlotLine/Sql/211_MapJourneyArchivedSceneRestore.sql new file mode 100644 index 00000000..08099cd2 --- /dev/null +++ b/PlotLine/Sql/211_MapJourneyArchivedSceneRestore.sql @@ -0,0 +1,245 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +-- Backups preserve archived canonical scenes and their map annotations. +-- Validate project identity against retained rows, not the active-manuscript view. +CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson + @ProjectID int, + @SourceRestorePointID int = NULL, + @SafetyRestorePointID int = NULL, + @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF ISJSON(@JsonData) <> 1 + THROW 51001, 'Restore JSON is invalid.', 1; + + IF JSON_VALUE(@JsonData, '$.Format') <> N'PlotDirector.ProjectBackup' + THROW 51002, 'Restore JSON format is not recognised.', 1; + + IF JSON_VALUE(@JsonData, '$.FormatVersion') NOT IN (N'1.0', N'1.1') + THROW 51003, 'Restore JSON format version is not supported.', 1; + + IF TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')) <> @ProjectID + THROW 51004, 'Restore point does not belong to this project.', 1; + + DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY); + INSERT INTO @RestoreTables (TableName) + VALUES + (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'), + (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'), + (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'), + (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'), + (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'), + (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'), + (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'), + (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'), + (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'), + (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'), + (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'), + (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'), + (N'ScenarioWarnings'); + + BEGIN TRANSACTION; + DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0); + + + DECLARE @TableName sysname; + DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN DisableCursor; + FETCH NEXT FROM DisableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;'; + EXEC (@DisableSql); + FETCH NEXT FROM DisableCursor INTO @TableName; + END + CLOSE DisableCursor; + DEALLOCATE DisableCursor; + + DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; + DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID; + DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID; + + DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID; + + DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + + DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo + INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE b.ProjectID = @ProjectID; + + DELETE sd FROM dbo.SceneDependencies sd + LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID + LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID; + + DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID; + DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID; + DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID; + + DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID; + + DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID; + + DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID; + DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID; + + DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID; + + DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID; + + DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.Books WHERE ProjectID = @ProjectID; + DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID; + + UPDATE p + SET ProjectName = src.ProjectName, + Description = src.Description, + CreatedDate = src.CreatedDate, + UpdatedDate = SYSUTCDATETIME(), + IsArchived = src.IsArchived, + ArchivedDate = src.ArchivedDate, + ArchivedReason = src.ArchivedReason + FROM dbo.Projects p + CROSS APPLY OPENJSON(@JsonData, '$.Project') + WITH + ( + ProjectID int '$.ProjectID', + ProjectName nvarchar(200) '$.ProjectName', + Description nvarchar(max) '$.Description', + CreatedDate datetime2 '$.CreatedDate', + IsArchived bit '$.IsArchived', + ArchivedDate datetime2 '$.ArchivedDate', + ArchivedReason nvarchar(1000) '$.ArchivedReason' + ) src + WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0; + + -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography. + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + THROW 51005,'Map backup contains features outside this project.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID) + OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID) + THROW 51005,'Map hierarchy or Location links cross projects.',1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n + WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID) + OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID) + OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@ProjectID AND s.SceneID IN(n.FromSceneID,n.ToSceneID))<>2 + OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path'))) + THROW 51005,'Journey annotations cross project or map boundaries.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0; + UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID; + + DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN EnableCursor; + FETCH NEXT FROM EnableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;'; + EXEC (@EnableSql); + FETCH NEXT FROM EnableCursor INTO @TableName; + END + CLOSE EnableCursor; + DEALLOCATE EnableCursor; + + IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL + BEGIN + INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes) + VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.'); + END; + + COMMIT TRANSACTION; +END; +GO diff --git a/PlotLine/Views/FloorPlans/Edit.cshtml b/PlotLine/Views/FloorPlans/Edit.cshtml index d83fd97c..a12dd868 100644 --- a/PlotLine/Views/FloorPlans/Edit.cshtml +++ b/PlotLine/Views/FloorPlans/Edit.cshtml @@ -85,6 +85,11 @@ +@if (int.TryParse(Context.Request.Query["storyMapId"], out var storyMapId) && storyMapId > 0) +{ +

← Back to map Story Mode

+} +
@@ -2686,6 +2691,8 @@ refreshGridCoordinateLabels(); refreshReferenceOverlay(); refreshOccupancyTrays(); + const mapStoryScene = Number(new URLSearchParams(window.location.search).get("storySceneId")); + if (mapStoryScene > 0) applyStoryPosition({ sceneId: mapStoryScene }); checkOverlaps(); }; diff --git a/PlotLine/Views/Maps/Index.cshtml b/PlotLine/Views/Maps/Index.cshtml index 93c52cc2..c474fc89 100644 --- a/PlotLine/Views/Maps/Index.cshtml +++ b/PlotLine/Views/Maps/Index.cshtml @@ -20,6 +20,17 @@ +

Rough first. Detail later. Visual placement is never a physical scale.