From 7fa095409cea95994bb68850b8fb4574daff5730 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 23 Nov 2026 11:21:45 +0000 Subject: [PATCH] Refine Character ribbon, grouped relationships and canonical evolution history --- ...Character-Workspace-Refinement-20261123.md | 57 +++++++++++++++ .../Browser/character-workspace-live.cjs | 7 +- .../Browser/character-workspace.cjs | 9 +-- .../Browser/relationship-evolution.cjs | 3 + .../Browser/relationship-workspace.cjs | 4 +- .../CharacterWorkspaceBrowserFixture.cs | 6 +- .../CharacterWorkspaceDatabaseTests.cs | 18 +++++ PlotLine.Tests/Program.cs | 4 +- PlotLine.Tests/ToolbarBrowserHost.cs | 1 + .../CharacterWorkspaceController.cs | 2 +- PlotLine/Controllers/DynamicsController.cs | 10 ++- PlotLine/Data/CharacterWorkspaceReader.cs | 4 +- PlotLine/Data/Repositories.cs | 6 +- PlotLine/Models/CoreModels.cs | 4 ++ PlotLine/Services/CharacterWorkspace.cs | 4 +- PlotLine/Services/CoreServices.cs | 6 +- .../Sql/309_CharacterRelationshipGroups.sql | 28 ++++++++ .../310_CharacterRelationshipQuickEdit.sql | 62 ++++++++++++++++ .../311_RelationshipEvolutionRefinement.sql | 37 ++++++++++ .../312_CharacterRelationshipGroupBounds.sql | 29 ++++++++ .../313_CharacterRelationshipLensFilters.sql | 30 ++++++++ .../ViewModels/CharacterWorkspaceModels.cs | 3 +- PlotLine/ViewModels/CoreViewModels.cs | 1 + PlotLine/Views/Characters/Details.cshtml | 10 +-- .../Characters/_WorkspaceOperation.cshtml | 13 +++- .../Views/Characters/_WorkspaceTab.cshtml | 24 +++++-- PlotLine/Views/Dynamics/Relationship.cshtml | 71 ++++++------------- .../Views/Shared/_ApplicationShell.cshtml | 1 + .../Shared/_CharacterRibbonCommands.cshtml | 10 +++ PlotLine/wwwroot/css/character-workspace.css | 9 +++ .../wwwroot/js/character-workspace-graph.js | 2 +- PlotLine/wwwroot/js/character-workspace.js | 30 ++++---- PlotLine/wwwroot/js/relationship-history.js | 1 + PlotLine/wwwroot/js/relationship-workspace.js | 5 +- 34 files changed, 400 insertions(+), 111 deletions(-) create mode 100644 Docs/Writer/Character-Workspace-Refinement-20261123.md create mode 100644 PlotLine.Tests/Browser/relationship-evolution.cjs create mode 100644 PlotLine/Sql/309_CharacterRelationshipGroups.sql create mode 100644 PlotLine/Sql/310_CharacterRelationshipQuickEdit.sql create mode 100644 PlotLine/Sql/311_RelationshipEvolutionRefinement.sql create mode 100644 PlotLine/Sql/312_CharacterRelationshipGroupBounds.sql create mode 100644 PlotLine/Sql/313_CharacterRelationshipLensFilters.sql create mode 100644 PlotLine/Views/Shared/_CharacterRibbonCommands.cshtml create mode 100644 PlotLine/wwwroot/js/relationship-history.js diff --git a/Docs/Writer/Character-Workspace-Refinement-20261123.md b/Docs/Writer/Character-Workspace-Refinement-20261123.md new file mode 100644 index 00000000..becf83b6 --- /dev/null +++ b/Docs/Writer/Character-Workspace-Refinement-20261123.md @@ -0,0 +1,57 @@ +# Character workspace refinement — 23 November 2026 + +## Scope and preservation + +This is a focused change to the main Character Details workspace and existing dedicated Relationship Evolution route. The five tabs, profile/gallery/aliases, character-level Evolution, appearances/knowledge, canonical Family/Story engines, Context, existing main editor and Timeline remain available. No manuscript-specific production rules or automatic deduplication were introduced. + +## Phase 1 — ribbon + +The existing Characters navigation remains in the ribbon. The redundant Characters/Timeline/Edit/Actions header controls are removed; the header retains portrait, identity, classification and analysis status. Edit Character and Actions now live in a selected-character ribbon group. Merge, Reanalyse, normal HTML character export, Markdown-format character export and Archive use their original controllers and forms. Markdown remains `Exports.Character(format=markdown)`; it was not reinterpreted. Owner/Collaborator editing checks, anti-forgery and the established Archive confirmation are retained; Viewer has export actions only. Each full character navigation renders the canonical ID into the shared ribbon partial. The dropdown uses Bootstrap with a fixed body portal so the horizontally scrolling ribbon does not clip its menu. + +## Phase 2 — grouped relationships + +SQL filters before grouping and orders by the other participant display name using case-insensitive `Latin1_General_100_CI_AS`, then canonical character ID. This is independent of A/B direction. Definition order within a group is controlled type name, then canonical definition ID. Queries page 25 character groups. Each group initially reads at most three definitions (75 total); a focused group pages all of its definitions in batches of 25. No client-side full dataset is loaded for sorting. Two identical display names remain separate canonical identities. Reciprocal flags remain one record; separately authored reverse records remain distinct. + +Collapsed summaries show name, count, a few recorded types and meaningful states. Expanded groups show distinct definitions, direction/category, selected-point state, notes, initial/scene-established status and start/end links. Family filtering mirrors the existing `ContextFamily_Structure` / `ContextRelationshipLenses.Family` predicate, including canonical partnerships, and never infers family membership from participants or prose. Story filtering selects the other definitions. The graph lenses remain the existing engines. Search, paging and narrative cutoff are retained. Expanded group IDs and selected definition survive ordinary refreshes; empty groups disappear after removal. + +## Phase 3 — actions and safe quick editing + +Each definition has Edit, History and Remove. Inspect Connection previously only selected/highlighted the diagram; clicking or keyboard-selecting the record now preserves that function, and diagram selection reveals its canonical record. One contextual link replaces repeated full-editor links. History links to the exact existing Dynamics Relationship route; Advanced Evolution and the complete in-page history have been removed. + +The focused native dialog reuses the established operation partial/controller, canonical controlled types and `Relationship_Save`. It edits type within the existing category, reverses direction explicitly, changes safe non-Family-category reciprocal representation, permanent status, reader awareness, initial state/intensity/reader awareness, and optional notes. Category is a property of canonical type, not an independent field. The definition ID is retained: no delete/recreate or inverse-record rewriting occurs. Pair identities, narrative boundaries, book and initial/scene-established status remain unchanged. + +Structural changes with dependent events, cross-category changes and Family-category reciprocity changes are rejected atomically with an inline explanation and focused route to the full editor. Those operations can reinterpret historical/family semantics and lack canonical coordinated validation here. Notes and supported initial properties remain editable. The full editor deep link selects the requested definition if established at its current point; otherwise it explains why it is unavailable there. The full editor itself was not redesigned. + +Removal retains the existing versioned, authorised canonical archive/event-delete operations, explicit scope/dependency confirmation and source-provenance guards. SQL locks and the original definition/history hash protect concurrent changes. Shared toast feedback and existing lightweight Context invalidation are reused; no new SignalR connection is created. + +## Phase 4 — dedicated history + +Diagnosis: the old graphic was a fixed-height decorative bright gradient, with an unlabelled positional strip. It rendered even with zero/one event, clipped edge markers, and substituted intensity 3 when no intensity was recorded. It did not explain axes or missing data. This was principally sparse-data/rendering/theme design, not missing canonical events. + +The existing Dynamics Relationship route is retained. It shows exact names/type/direction/definition ID, canonical book/chapter/scene-ordered events, actual state and optional intensity, notes, evidence/review status, source links and retained continuity warnings. Event editing/removal uses the existing protected operation workflow on this page. Data is paged at 25. Empty/single-event cases get concise explicit presentations. Multiple verified recorded intensities get a compact labelled point plot, with no synthetic intermediate states or values for missing intensity. Narrow charts scroll internally instead of shrinking text or overflowing the page. Theme surfaces and text use existing application tokens. The source of ordering is the established canonical scene-order function; same-scene events sort by canonical event ID. The return link identifies the originating character, selected definition and narrative point, restoring selection/expansion in Relationships. Character-level Evolution remains separate. + +## Qualification and Development delivery + +Evidence, final regression results and deployed commit are appended after verification. The two pre-existing untracked investigation documents are preserved. Tests use rollback SQL fixtures or explicitly disposable Development browser characters only; no actual manuscript relationship is corrected, merged or removed. + +### Database qualification + +Forward-only migrations 309–313 were applied only to the verified `PlotDirector_Development` database. Each uses `CREATE OR ALTER` routines; existing applied numbered scripts remain unchanged. The backup `/var/opt/mssql/backup/character-refinement-20261123T105440Z.bak` completed with COPY_ONLY/CHECKSUM and passed `RESTORE VERIFYONLY`; no restore/reset occurred. The quick-edit procedure initially failed compilation because SQL treats parameter/local variable names case-insensitively; the unapplied procedure was corrected before successful application. No dependent application build was deployed during that failure. + +The opt-in disposable-scope SQL suite passed and rolled back every case: 28 globally ordered groups, matching/case-varied names with stable identity, direction-independent grouping, 28 definitions in a single group with 25+3 focused pages, combined search/category filters and no deduplication; same-ID family type/direction changes; one-row story reciprocity; rejection of incompatible category, family reciprocity and semantic rewrites with history; canonical archive/restore retaining dependent events and independent reverse facts; one-event editing/removal; stale-history and permission/confirmation checks; source-linked blocking; dedicated canonical history pagination at 25+3 and stable same-scene event order. The final test confirms no fixture character remains from any rollback case. + +Read-only real-manuscript acceptance used the actual Dapper readers: bounded explorers, SQL/.NET ordering agreement, selected-point future-knowledge exclusion, canonical management preview mapping and a sparse single-event dedicated history. The real-project relationship checksum was identical before and after; no AI work or manuscript mutation occurred. + +### Regression and visual acceptance + +`dotnet build PlotLine.slnx -m:1 --disable-build-servers` passes with zero warnings/errors. Single-process compilation avoids an initial CLR/build-server crash on this host. The full executable harness reports **786 PASS** and exits successfully. The 15 focused Character workspace service checks also pass after the final form/ribbon integration adjustments. + +The rendered main-workspace Playwright suite passes: lazy tabs and retained profile/gallery/navigation; sorted compact groups with two directional definitions together; Family/Story filters; controlled type modal, inline stale validation, unsaved/Escape handling and full-width controls; selection/expansion after saves and exact-history return; archive refresh; correct relocated ribbon IDs after character navigation, Markdown-format link and anti-forgery forms; unclipped Actions menu at desktop/laptop/tablet/mobile widths; actual touch pan/pinch; stable Native/SI connection counts and Viewer controls. Browser fixture pagination is complemented by actual SQL all-page ordering tests. The dedicated history suite passes empty/single/five-event cases, actual intensity omission rather than fabricated values, canonical order/source navigation, exact return identity, event modal protection and Viewer restrictions. The existing Relationships Editor browser suite passes after the minimal deep-link integration. + +Widths 1366, 1024, 768 and 390 pass without page-wide horizontal overflow. The compact chart has a bounded internal scroller on narrow screens. Screenshots `/tmp/character-refinement-grouped-dark.png` and `/tmp/relationship-evolution-dark-desktop.png` were visually inspected in the actual warm-dark theme. The final scoped outline-button adjustment improves contrast without changing the shared application theme. + +No additional per-tab/component SignalR connections or complete-dataset broadcasts were added. Physical device/touch and assistive-technology screen-reader acceptance remain manual recommendations; browser tests cover touch emulation, keyboard, modal focus and responsive geometry. + +The final dedicated-history browser check also performs a successful event-form save, verifies that the shared success toast remains visible and that only the bounded content is fetched (no document reload), then checks protected-source removal. Main workspace saves restore focus to the selected definition and retain its group. The exact full-editor deep link is tested after saved story-position restoration, in addition to the original editor regression scenarios. + +The database suite reports **26 passing checks in 16 fully rolled-back cases**. Build, focused service checks, main-workspace browser, dedicated-history browser and main Relationships Editor browser all pass for the delivered refinements. Deployment evidence follows. diff --git a/PlotLine.Tests/Browser/character-workspace-live.cjs b/PlotLine.Tests/Browser/character-workspace-live.cjs index 7d183f4b..ceef0771 100644 --- a/PlotLine.Tests/Browser/character-workspace-live.cjs +++ b/PlotLine.Tests/Browser/character-workspace-live.cjs @@ -5,8 +5,9 @@ step='new isolated character and Supporting default';await p.goto('https://dev.p step='five live bounded tabs and empty states';for(const tab of ['relationships','evolution','appearances','knowledge','overview']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}await p.click('[data-character-tab="relationships"]');await p.locator('[data-character-node="'+id+'"]').waitFor({state:'attached'}); step='existing Context peer notifications';const peer=await c.newPage();await peer.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await peer.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController.connection?.state==='Connected');await peer.evaluate(project=>{window.workspaceHints=0;document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInvalidated',hint=>{if(Number(hint.projectId)===project)workspaceHints++});},s.project); step='initial parent via canonical save';await p.locator('[data-workspace-add]').click();// Resolve the known fixture name from its authenticated shell, without printing it. -const targetShell=await c.request.get('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]);const html=await targetShell.text();const name=await p.evaluate(text=>new DOMParser().parseFromString(text,'text/html').querySelector('h1')?.childNodes[0]?.textContent.trim(),html);assert(name);await p.locator('[data-workspace-target-search]').fill(name.slice(0,50));await p.locator('[data-workspace-target] option[value="'+s.characters[0]+'"]').waitFor({state:'attached'});await p.locator('[data-workspace-target]').selectOption(String(s.characters[0]));const type=await p.locator('[name=RelationshipTypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Parent$/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=RelationshipTypeID]',type);await p.locator('[name=Notes]').fill('Disposable workspace qualification definition');await p.locator('[data-workspace-operation-form] button[type=submit], [data-workspace-operation-form] button:not([type])').first().click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);let row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));row=p.locator('[data-workspace-relationship="'+rid+'"]');await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'attached'}); -step='live edit, dirty main navigation guard and archive preview';await row.locator('[data-workspace-operation="definition"]').click();await p.locator('[name=Notes]').fill('Disposable definition edited');p.once('dialog',d=>d.dismiss());assert.equal(await p.evaluate(()=>window.PlotDirectorCharacterWorkspace.requestLeave(()=>{window.unexpectedLeave=true})),false);assert.equal(await p.evaluate(()=>!!window.unexpectedLeave),false);await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await row.locator('[data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/0 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/underlying relationship definition/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(r=>!document.querySelector('[data-workspace-relationship="'+r+'"]'),rid);await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'detached'});assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…'); +const targetShell=await c.request.get('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]);const html=await targetShell.text();const name=await p.evaluate(text=>new DOMParser().parseFromString(text,'text/html').querySelector('h1')?.childNodes[0]?.textContent.trim(),html);assert(name);await p.locator('[data-workspace-target-search]').fill(name.slice(0,50));await p.locator('[data-workspace-target] option[value="'+s.characters[0]+'"]').waitFor({state:'attached'});await p.locator('[data-workspace-target]').selectOption(String(s.characters[0]));const type=await p.locator('[name=RelationshipTypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Parent$/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=RelationshipTypeID]',type);await p.locator('[name=Notes]').fill('Disposable workspace qualification definition');await p.locator('[data-workspace-operation-form] button[type=submit], [data-workspace-operation-form] button:not([type])').first().click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.locator('[data-relationship-group] > summary').first().click();let row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));row=p.locator('[data-workspace-relationship="'+rid+'"]');await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'attached'}); +step='dedicated empty history and exact return';await row.getByRole('link',{name:'History',exact:true}).click();await p.waitForURL(u=>u.pathname==='/Dynamics/Relationship/'+rid);assert.match(await p.locator('main').innerText(),/No recorded events/);assert.equal(await p.locator('.relationship-evolution-chart').count(),0);await p.getByRole('link',{name:'Return to character Relationships'}).click();await p.locator('[data-workspace-relationship="'+rid+'"].is-selected').waitFor();assert.equal(await row.evaluate(n=>n.closest('[data-relationship-group]').open),true); +step='live edit, dirty main navigation guard and archive preview';await row.locator('[data-workspace-operation="definition"]').click();const childType=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Child$/.test(n.textContent))?.value);assert(childType);await p.locator('[name=TypeID]').selectOption(childType);await p.locator('[name=ReverseDirection]').check();await p.locator('[name=Notes]').fill('Disposable definition edited');p.once('dialog',d=>d.dismiss());assert.equal(await p.evaluate(()=>window.PlotDirectorCharacterWorkspace.requestLeave(()=>{window.unexpectedLeave=true})),false);assert.equal(await p.evaluate(()=>!!window.unexpectedLeave),false);await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await row.locator('[data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/0 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/underlying relationship definition/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(r=>!document.querySelector('[data-workspace-relationship="'+r+'"]'),rid);await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'detached'});assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…'); await peer.waitForFunction(()=>workspaceHints===3);await peer.waitForTimeout(400);assert.equal(await peer.evaluate(()=>workspaceHints),3);assert.equal(await peer.locator('[data-context-scene]').inputValue(),String(s.scene)); -step='archive only this newly created fixture character';await p.locator('.character-workspace-header .dropdown-toggle').click();await p.locator('.character-workspace-header form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal [data-confirm-submit]').click();await p.waitForURL(u=>!u.pathname.endsWith('/Details/'+id));assert.deepEqual(errors,[]);console.log('PASS Development live Character workspace: new isolated Supporting fixture; all five tabs; canonical initial Parent add/edit; dirty navigation rejection; explicit dependency preview; direct soft archive and Family/Story refresh; exactly one existing Context peer hint per add/edit/archive; newly created fixture character archived. Existing manuscript and baseline fixture relationships untouched.'); +step='archive only this newly created fixture character';await p.locator('[data-character-ribbon] .dropdown-toggle').click();await p.locator('[data-character-actions-for] form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal [data-confirm-submit]').click();await p.waitForURL(u=>!u.pathname.endsWith('/Details/'+id));assert.deepEqual(errors,[]);console.log('PASS Development live Character workspace: new isolated Supporting fixture; all five tabs and exact dedicated History/return; canonical initial Parent add and same-ID Child/direction edit; dirty navigation rejection; explicit dependency preview; direct soft archive and Family/Story refresh; exactly one existing Context peer hint per add/edit/archive; newly created fixture character archived. Existing manuscript and baseline fixture relationships untouched.'); }catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})(); diff --git a/PlotLine.Tests/Browser/character-workspace.cjs b/PlotLine.Tests/Browser/character-workspace.cjs index b5baf004..708551aa 100644 --- a/PlotLine.Tests/Browser/character-workspace.cjs +++ b/PlotLine.Tests/Browser/character-workspace.cjs @@ -1,15 +1,16 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; -(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let removed=false,notes=null,fail=false,viewer=false,tabReads=[],familyReads=0;for(const [endpoint,fixture]of [['Tab','tab'],['Family','family'],['Operation','operation']])await c.route('**/Characters/Workspace/'+endpoint+'/*',async r=>{const u=new URL(r.request().url());if(endpoint==='Operation'&&r.request().method()==='POST'){if(fail){fail=false;await r.fulfill({response:await r.fetch({method:'GET',url:base+'/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true¬es='+encodeURIComponent('Draft retained')})});return;}if(r.request().postData()?.includes('archive'))removed=true;else notes='Saved fixture definition';await r.fulfill({json:{saved:true,message:removed?'Relationship archived; history retained.':'Relationship saved.'}});return;}if(endpoint==='Tab')tabReads.push(u.searchParams.get('Tab'));if(endpoint==='Family')familyReads++;u.searchParams.set('viewer',String(viewer));u.searchParams.set('removed',String(removed));if(notes)u.searchParams.set('notes',notes);await r.fulfill({response:await r.fetch({url:base+'/character-workspace-'+fixture+'-fixture'+u.search})});});await c.route('**/Characters/Workspace/Lookup/*',r=>r.fulfill({json:[{id:6,name:'Another established character'}]}));await c.route('**/Characters/Workspace/Story/*',r=>r.fulfill({json:{lens:'story',focusID:5,povID:null,sceneID:22,canEdit:!viewer,truncated:false,nodes:[{id:5,name:'Current character'},{id:7,name:'Recorded colleague'}],links:[{id:12,a:5,b:7,type:'Friend',category:'Friendship',state:'Earlier recorded state',reciprocal:false,initial:true,recent:[]}]}}));await c.route('**/Characters/Details/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('id',u.pathname.split('/').at(-1));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-fixture'+u.search})});});const p=await c.newPage(),errors=[];await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async locator=>locator.click());let native=0,si=0;p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))native++;if(r.url().includes('/hubs/story-intelligence/negotiate'))si++;});await p.goto(base+'/character-workspace-fixture');await p.waitForSelector('[data-character-tab-content="overview"]'); +(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let removed=false,notes=null,fail=false,viewer=false,tabReads=[],familyReads=0;for(const [endpoint,fixture]of [['Tab','tab'],['Family','family'],['Operation','operation']])await c.route('**/Characters/Workspace/'+endpoint+'/*',async r=>{const u=new URL(r.request().url());if(endpoint==='Operation'&&r.request().method()==='POST'){if(fail){fail=false;await r.fulfill({response:await r.fetch({method:'GET',url:base+'/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true¬es='+encodeURIComponent('Draft retained')})});return;}if(r.request().postData()?.includes('archive'))removed=true;else notes='Saved fixture definition';await r.fulfill({json:{saved:true,message:removed?'Relationship archived; history retained.':'Relationship saved.'}});return;}if(endpoint==='Tab'){tabReads.push(u.searchParams.get('Tab'));u.searchParams.set('id',u.pathname.split('/').at(-1));}if(endpoint==='Family')familyReads++;u.searchParams.set('viewer',String(viewer));u.searchParams.set('removed',String(removed));if(notes)u.searchParams.set('notes',notes);await r.fulfill({response:await r.fetch({url:base+'/character-workspace-'+fixture+'-fixture'+u.search})});});await c.route('**/Characters/Workspace/Lookup/*',r=>r.fulfill({json:[{id:6,name:'Another established character'}]}));await c.route('**/Characters/Workspace/Story/*',r=>r.fulfill({json:{lens:'story',focusID:5,povID:null,sceneID:22,canEdit:!viewer,truncated:false,nodes:[{id:5,name:'Current character'},{id:7,name:'Recorded colleague'}],links:[{id:12,a:5,b:7,type:'Friend',category:'Friendship',state:'Earlier recorded state',reciprocal:false,initial:true,recent:[]}]}}));await c.route('**/Characters/Details/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('id',u.pathname.split('/').at(-1));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-fixture'+u.search})});});const p=await c.newPage(),errors=[];await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async locator=>locator.click());let native=0,si=0;p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))native++;if(r.url().includes('/hubs/story-intelligence/negotiate'))si++;});await p.goto(base+'/character-workspace-fixture');await p.waitForSelector('[data-character-tab-content="overview"]'); step='compact shell and lazy Overview';assert.deepEqual(tabReads,['overview']);assert.equal(await p.locator('[data-character-tab-content]').count(),1);assert.equal(await p.locator('[data-character-tab]').count(),5);assert.match(await p.locator('.character-workspace-header').innerText(),/Supporting/);assert.match(await p.locator('.character-dossier').innerText(),/Recorded variant/);assert(await p.locator('.character-workspace-header').evaluate(n=>n.getBoundingClientRect().height<260));assert.equal(await p.locator('[data-workspace-relationship]').count(),0);await p.screenshot({path:'/tmp/character-workspace-overview-desktop.png',fullPage:true}); - step='relationships layout, branch and record selection';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node="5"]');assert.equal(await p.locator('[data-workspace-relationship]').count(),3);await p.locator('[data-character-branch="3"]').click();await p.locator('[data-character-node="1"]').waitFor();await p.screenshot({path:'/tmp/character-workspace-family-desktop.png',fullPage:true});await p.click('[data-workspace-select-relationship="9"]');assert(await p.locator('[data-workspace-relationship="9"]').evaluate(n=>n.classList.contains('is-selected')));await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.waitForSelector('[data-workspace-operation-form]');assert(await p.locator('[data-workspace-operation-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));await p.locator('[name=Notes]').fill('Saved fixture definition');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>document.querySelector('[data-workspace-relationship="9"]')?.textContent.includes('Saved fixture definition')); + step='relationships layout, branch and record selection';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node="5"]');assert.equal(await p.locator('[data-workspace-relationship]').count(),4);assert.equal(await p.locator('[data-relationship-group]').count(),3);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),false);await p.locator('[data-relationship-group="6"] > summary').click();assert.deepEqual(await p.locator('[data-relationship-group] > summary > strong').allTextContents(),['Recorded child','Recorded colleague','Recorded partner']);for(const [category,count]of [['family',2],['story',1],['',3]]){await p.locator('[data-workspace-filter] [name=Category]').selectOption(category);await p.locator('[data-workspace-filter]').getByRole('button',{name:'Apply filters'}).click();await p.waitForFunction(n=>document.querySelectorAll('[data-relationship-group]').length===n,count);}assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);await p.locator('[data-character-branch="3"]').click();await p.locator('[data-character-node="1"]').waitFor();await p.screenshot({path:'/tmp/character-workspace-family-desktop.png',fullPage:true});await p.locator('[data-workspace-relationship="9"] > p').first().click();assert(await p.locator('[data-workspace-relationship="9"]').evaluate(n=>n.classList.contains('is-selected')));await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.waitForSelector('[data-workspace-operation-form]');assert(await p.locator('[data-workspace-operation-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[name=TypeID]').inputValue(),'1');await p.locator('[name=TypeID]').selectOption('2');await p.locator('[name=Notes]').fill('Saved fixture definition');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>document.querySelector('[data-workspace-relationship="9"]')?.textContent.includes('Saved fixture definition')); step='inline stale error, Escape and draft protection';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.locator('[name=Notes]').fill('Draft retained');fail=true;await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.locator('.validation-summary-errors').waitFor();assert.equal(await p.locator('[name=Notes]').inputValue(),'Draft retained');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-workspace-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click(); - step='explicit underlying removal with retained dependent history';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/2 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/1 separately recorded/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>!document.querySelector('[data-workspace-relationship="9"]'));assert(familyReads>1);assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false); + step='explicit underlying removal with retained dependent history';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/2 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/1 separately recorded/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>!document.querySelector('[data-workspace-relationship="9"]'));assert(familyReads>1);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false); step='bounded Evolution, Appearances and Knowledge and cached tabs';for(const tab of ['evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert.equal(await p.locator('[data-workspace-entry]').count(),25);await p.locator('[data-workspace-entry] summary').first().click();assert(await p.locator('[data-workspace-entry] .character-record-detail').first().isVisible());}await p.locator('[data-workspace-page="2"]').click();await p.waitForSelector('[data-character-tab-content][data-page="2"]');assert.equal(await p.locator('[data-workspace-entry]').count(),25);const reads=tabReads.length;await p.click('[data-character-tab="overview"]');await p.waitForSelector('[data-character-tab-content="overview"]');await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');assert.equal(tabReads.length,reads+1); // Overview invalidated by the save; Knowledge restores its second page. step='selected story point and back forward';await p.click('[data-workspace-position]');await p.locator('[data-workspace-dialog] [data-workspace-entry="22"] summary').click();await p.locator('[data-workspace-set-position="22"]').click();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]');assert.match(p.url(),/SceneID=22/);await p.goBack();await p.waitForSelector('[data-character-tab-content="knowledge"][data-page="2"]');await p.goForward();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]'); step='Story network uses selected point and filters';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node]');await p.click('[data-character-lens="story"]');await p.locator('[data-character-connection="12"]').waitFor({state:'attached'});assert.match(await p.locator('[data-character-graph-selection]').innerText(),/Recorded identity|Current character/); step='responsive and touch-size geometry';for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});for(const tab of ['overview','relationships','evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+tab);}}await p.screenshot({path:'/tmp/character-workspace-mobile.png',fullPage:true});assert.equal(native,1);assert(si<=2,'existing global/detail SI connections do not grow per tab'); step='direct legacy fragment, remembered character tab and keyboard';await p.goto(base+'/Characters/Details/5#character-gallery');await p.locator('[data-workspace-gallery][open]').waitFor();await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');await p.locator('[data-character-switch]').fill('another');await p.locator('[data-character-matches] a').click();await p.waitForURL(/\/Characters\/Details\/6\?tab=knowledge/);await p.locator('[data-character-tab-content="knowledge"]').waitFor();await p.locator('[data-character-tab="knowledge"]').focus();await p.keyboard.press('Home');await p.waitForSelector('[data-character-tab-content="overview"]'); - step='event history and protected-source controls';await p.setViewportSize({width:1024,height:1000});await p.click('[data-character-tab="relationships"]');await p.locator('[data-workspace-history="12"]').click();await p.locator('[data-character-history] [data-workspace-entry] summary').first().click();await p.locator('[data-workspace-operation="event-edit"]').first().click();await p.locator('[name=Notes]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/one recorded development/);await p.locator('[data-workspace-cancel]').click();await p.locator('[data-workspace-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/only event #1/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/definition and other events remain/);await p.locator('[data-workspace-cancel]').click();await c.route('**/Characters/Workspace/Operation/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('protected','true');await r.fulfill({response:await r.fetch({url:base+'/character-workspace-operation-fixture'+u.search})});});await p.locator('[data-workspace-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/Direct modification\/removal is blocked/);assert.equal(await p.locator('[data-workspace-operation-form] [type=submit]').count(),0);await p.locator('[data-workspace-cancel]').click(); + step='one exact history destination and ribbon targets';await p.setViewportSize({width:1024,height:1000});await p.click('[data-character-tab="relationships"]');assert.equal(await p.locator('[data-workspace-history]').count(),0);assert.equal(await p.locator('[data-character-history]').count(),0);assert.match(await p.locator('[data-workspace-relationship="12"] a').filter({hasText:'History'}).getAttribute('href'),/Dynamics\/Relationship\/12.*returnCharacterId=6/);assert.equal(await p.locator('.character-workspace-header .button-row,.character-workspace-header .dropdown,.character-workspace-header a.btn').count(),0);assert.match(await p.locator('[data-character-ribbon-edit]').getAttribute('href'),/Characters\/Edit\/6/);assert.equal(await p.locator('[data-character-ribbon] form[action*="Archive"] [name=id]').inputValue(),'6');await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="6"]');await menu.waitFor({state:'visible'});assert.match(await menu.getByRole('link',{name:'Markdown',exact:true}).getAttribute('href'),/Exports\/Character\/6.*format=markdown/);assert(await menu.locator('form[action*="Archive"] button').evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));await p.keyboard.press('Escape'); step='tablet touch pan and pinch';await p.setViewportSize({width:768,height:1000});await p.locator('[data-character-lens="family"]').click();await p.locator('[data-character-node]').first().waitFor({state:'attached'});await p.locator('[data-character-graph-reset]').click();const host=p.locator('[data-character-graph]');await host.scrollIntoViewIfNeeded();const box=await host.boundingBox(),x=box.x+box.width*.5,y=box.y+box.height*.5,cdp=await c.newCDPSession(p);await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:true,maxTouchPoints:2});const world=p.locator('[data-character-graph] svg > g'),beforePan=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x+70,y:y+30,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePan);const beforePinch=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:x-35,y,id:1},{x:x+35,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x-70,y,id:1},{x:x+70,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePinch);await p.screenshot({path:'/tmp/character-workspace-tablet-family.png',fullPage:false});await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:false}); + step='return to exact definition and retained group';removed=false;await p.goto(base+'/Characters/Details/5?tab=relationships&relationshipId=9');await p.waitForSelector('[data-workspace-relationship="9"].is-selected');assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="5"]');await menu.waitFor({state:'visible'});const archive=menu.locator('form[action*="Archive"] button');assert(await archive.evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.keyboard.press('Escape');}await p.setViewportSize({width:1366,height:1000});await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});await p.screenshot({path:'/tmp/character-refinement-grouped-dark.png',fullPage:true}); step='read-only workspace';viewer=true;await p.goto(base+'/character-workspace-fixture?viewer=true&tab=relationships');await p.waitForSelector('[data-character-tab-content="relationships"]');assert.equal(await p.locator('[data-workspace-operation]').count(),0);assert.equal(await p.locator('[data-workspace-add]').count(),0);assert.deepEqual(errors,[]);console.log('PASS main Character browser: compact header, five lazy tabs, dossier/aliases/gallery, bounded explorers and pages, Family branches, Story and selected point, diagram/record selection, modal widths/inline error/Escape/unsaved protection, explicit archive consequences, refresh, cache, back/forward, character links, legacy hash, keyboard, desktop/laptop/tablet/mobile, touch pan/pinch, event history/source protection and read-only; connection counts stable across tabs.'); }catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})(); diff --git a/PlotLine.Tests/Browser/relationship-evolution.cjs b/PlotLine.Tests/Browser/relationship-evolution.cjs new file mode 100644 index 00000000..e66b4f40 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-evolution.cjs @@ -0,0 +1,3 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let protectedSource=false;await c.route('**/Characters/Workspace/Operation/*',async r=>{if(r.request().method()==='POST'){await r.fulfill({json:{saved:true,message:'One canonical event saved.'}});return;}const u=new URL(r.request().url());u.searchParams.set('protected',String(protectedSource));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-operation-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async l=>l.click());for(const count of [0,1,5]){await p.setViewportSize({width:1366,height:1000});await p.goto(base+'/relationship-evolution-fixture?count='+count);await p.locator('[data-relationship-evolution="9"]').waitFor();await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});assert.equal(await p.locator('[data-evolution-event]').count(),count);assert.equal(await p.locator('.relationship-evolution-chart').count(),count>1?1:0);assert.equal(await p.locator('.dynamics-timeline').count(),0);if(count===0)assert.match(await p.locator('main').innerText(),/No recorded events/);if(count===1)assert.match(await p.locator('main').innerText(),/One recorded event/);if(count===5){assert.deepEqual(await p.locator('[data-evolution-event]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.evolutionEvent))),[1,2,3,4,5]);assert.equal(await p.locator('.relationship-evolution-chart circle').count(),4);await p.locator('.relationship-evolution-chart a').first().click();assert.match(p.url(),/#event-1/);await p.screenshot({path:'/tmp/relationship-evolution-dark-desktop.png',fullPage:true});}for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}assert.match(await p.getByRole('link',{name:'Return to character Relationships'}).getAttribute('href'),/Characters\/Details\/5.*relationshipId=9/);} +await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/one recorded development/);await p.locator('[name=Notes]').fill('Unsaved event draft');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-history-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click();let refreshes=0,navigations=0;p.on('request',r=>{if(r.url().includes('/relationship-evolution-fixture'))refreshes++;});p.on('load',()=>navigations++);await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[name=Notes]').fill('Saved event draft');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-history-dialog]').open);await p.locator('.pd-toast').filter({hasText:'One canonical event saved.'}).waitFor();await p.waitForTimeout(150);assert(refreshes>0);assert.equal(navigations,0);protectedSource=true;await p.locator('[data-history-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/Direct modification\/removal is blocked/);assert.equal(await p.locator('[data-workspace-operation-form] [type=submit]').count(),0);await p.locator('[data-workspace-cancel]').click();await p.goto(base+'/relationship-evolution-fixture?count=1&viewer=true');assert.equal(await p.locator('[data-history-operation]').count(),0);assert.deepEqual(errors,[]);console.log('PASS relationship Evolution: empty/single/multiple canonical histories, dark theme bounded intensity chart without invented missing values, chronological source links, exact return identity, desktop/laptop/tablet/mobile, event modal draft/Escape/source protection and Viewer permissions.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/relationship-workspace.cjs b/PlotLine.Tests/Browser/relationship-workspace.cjs index ca2d8846..6f36411c 100644 --- a/PlotLine.Tests/Browser/relationship-workspace.cjs +++ b/PlotLine.Tests/Browser/relationship-workspace.cjs @@ -174,7 +174,9 @@ const base = 'http://127.0.0.1:5238'; await app.locator('.pd-context-popup').waitFor(); assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available after focusing'); await app.keyboard.press('Escape'); + await page.goto(base + '/fixture?page=relationships&relationshipId=1'); + await page.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace?.selectedRelationship?.characterRelationshipID===1); assert.deepEqual(errors, []); - console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout and PWA menu'); + console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout, exact definition deep link and PWA menu'); } finally { await browser.close(); } })().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs b/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs index fccf50e5..161481bc 100644 --- a/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs +++ b/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs @@ -5,14 +5,14 @@ using PlotLine.ViewModels; internal static class CharacterWorkspaceBrowserFixture { public static CharacterDetailViewModel Header(int id=5,bool viewer=false)=>new(){Project=new(){ProjectID=7,ProjectName="Character workspace qualification"},Character=new(){CharacterID=id,ProjectID=7,CharacterName=id==5?"A character with a long established canonical name":"Another established character",CharacterImportance=6,Sex="Recorded sex",BirthDate=new(1980,1,1),DefaultDescription=string.Join("\n",Enumerable.Repeat("A long canonical biography with details that must wrap naturally in the dossier.",12)),Height="Recorded height",EyeColour="Recorded eyes"},WorkspaceCanEdit=!viewer,WorkspaceCounts=new(){Relationships=3,Appearances=71,Attributes=44,Knowledge=66,Images=0,FirstSceneID=22},DisplayAge="40 years",AgeContext="At age reference scene",AgeReferenceScene=new(){SceneID=22,SceneTitle="Reference scene"},CharacterAnalysis=new(){CharacterID=id,Status="Completed",Summary="Existing persisted analysis, distinct from the author's profile."},Aliases=[new(){CharacterID=id,Alias="Recorded variant"}]}; - public static CharacterRelationship Relationship(int id=9)=>new(){CharacterRelationshipID=id,ProjectID=7,CharacterAID=5,CharacterBID=id==12?7:id==10?8:6,CharacterAName="A character with a long established canonical name",CharacterBName=id==12?"Recorded colleague":id==10?"Recorded partner":"Recorded child",RelationshipTypeName=id==12?"Friend":id==10?"Spouse":"Parent",RelationshipCategoryName=id==12?"Friendship":id==10?"Romantic / Sexual":"Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",Notes="Canonical definition notes",IsReciprocal=id==10}; + public static CharacterRelationship Relationship(int id=9)=>new(){RelationshipTypeID=id==12?3:1,WorkspaceDefinitionCount=id==9?2:1,CharacterRelationshipID=id,ProjectID=7,CharacterAID=5,CharacterBID=id==12?7:id==10?8:6,CharacterAName="A character with a long established canonical name",CharacterBName=id==12?"Recorded colleague":id==10?"Recorded partner":"Recorded child",RelationshipTypeName=id==12?"Friend":id==10?"Spouse":"Parent",RelationshipCategoryName=id==12?"Friendship":id==10?"Romantic / Sexual":"Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",Notes="Canonical definition notes",IsReciprocal=id==10}; public static CharacterWorkspacePage Page(int id,CharacterWorkspaceQuery q,bool viewer=false,bool removed=false,string? notes=null) { var p=Header(id,viewer);var page=new CharacterWorkspacePage{Profile=p,Query=q,Total=q.Tab=="overview"?0:71,Books=[new("First book","12"),new("Second book","13")],PointLabel=q.SceneID.HasValue?"First book · Ch 1 · Scene 2: Earlier point":null}; - if(q.Tab=="relationships"){page.Total=removed?2:3;page.Relationships=new[]{9,10,12}.Where(n=>!removed||n!=9).Where(n=>!q.RelationshipID.HasValue||n==q.RelationshipID).Select(n=>{var r=Relationship(n);if(notes!=null&&n==9)r.Notes=notes;return new CurrentRelationshipViewModel{Relationship=r,LatestEvent=q.SceneID.HasValue?new(){RelationshipStateName="Earlier recorded state",Description="Earlier canonical development"}:null};}).ToArray();return page;} + if(q.Tab=="relationships"){page.Total=3;page.Relationships=new[]{9,10,12,13}.Where(n=>!removed||n!=9).Where(n=>!q.RelationshipID.HasValue||n==q.RelationshipID).Select(n=>{var r=Relationship(n);if(n==13){r.CharacterAID=6;r.CharacterBID=5;r.CharacterAName="Recorded child";r.CharacterBName=p.Character.CharacterName;r.WorkspaceDefinitionCount=2;}if(notes!=null&&n==9)r.Notes=notes;return new CurrentRelationshipViewModel{Relationship=r,LatestEvent=q.SceneID.HasValue?new(){RelationshipStateName="Earlier recorded state",Description="Earlier canonical development"}:null};}).Where(x=>string.IsNullOrEmpty(q.Category)||(q.Category=="family")==ContextRelationshipLenses.Family(x.Relationship.RelationshipCategoryName,x.Relationship.RelationshipTypeName)).OrderBy(x=>x.Relationship.CharacterAID==id?x.Relationship.CharacterBName:x.Relationship.CharacterAName,StringComparer.OrdinalIgnoreCase).ThenBy(x=>x.Relationship.CharacterRelationshipID).ToArray();return page;} page.Entries=q.Tab is "overview" or "gallery"?[]:Enumerable.Range((q.Page-1)*25+1,Math.Min(25,Math.Max(0,71-(q.Page-1)*25))).Select(i=>new CharacterWorkspaceEntry{ID=i,Kind=q.Tab=="appearances"?"appearances":q.Tab=="knowledge"?"knowledge":q.Tab=="history"?"relationships":q.Tab=="scenes"?"scenes":"attributes",RelationshipID=q.Tab=="history"?q.RelationshipID:null,SceneID=i,BookID=i>35?13:12,BookTitle=i>35?"Second book":"First book",ChapterNumber=(i-1)/10+1,SceneNumber=i,SceneTitle="Recorded source scene "+i,Ordinal=i,Heading=q.Tab=="scenes"?"Source scene "+i:q.Tab=="knowledge"?"Recorded asset or thread":"Recorded change "+i,State=q.Tab=="knowledge"?(i%2==0?"Knows":"Partially Knows"):"New recorded state",Previous=q.Tab=="evolution"?"Previous recorded state":null,Notes="Existing canonical detail and source. "+new string('x',220),EvidenceState=i%7==0?"Needs review":"Verified",IsPov=i%3==0}).Where(e=>string.IsNullOrEmpty(q.Search)||e.Heading!.Contains(q.Search,StringComparison.OrdinalIgnoreCase)).ToArray();return page; } - public static CharacterWorkspaceOperation Operation(int id,string action,int relationship,int? eventId,bool protectedSource=false,string version="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")=>new(){CharacterID=id,RelationshipID=relationship,EventID=eventId,Action=action,Version=version,Record=new(){Relationship=Relationship(relationship),Version=version,EventCount=2,OtherPairRecords=1},Event=eventId.HasValue?new(){Record=new(){RelationshipEventID=eventId.Value,CharacterRelationshipID=relationship,SceneID=22,RelationshipStateID=1,Description="One event description"},ProtectedSource=protectedSource}:null,Notes=eventId.HasValue?"One event description":"Canonical definition notes",StateID=1,Intensity=5,States=[new("Established","1"),new("Changed","2")]}; + public static CharacterWorkspaceOperation Operation(int id,string action,int relationship,int? eventId,bool protectedSource=false,string version="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")=>new(){CharacterID=id,RelationshipID=relationship,EventID=eventId,Action=action,Version=version,TypeID=1,Types=[new("Family · Parent","1"),new("Family · Child","2")],Reciprocal=false,Permanent=true,ReaderKnows=false,Record=new(){Relationship=Relationship(relationship),Version=version,EventCount=action=="definition"?0:2,OtherPairRecords=1},Event=eventId.HasValue?new(){Record=new(){RelationshipEventID=eventId.Value,CharacterRelationshipID=relationship,SceneID=22,RelationshipStateID=1,Description="One event description"},ProtectedSource=protectedSource}:null,Notes=eventId.HasValue?"One event description":"Canonical definition notes",StateID=1,Intensity=5,States=[new("Established","1"),new("Changed","2")]}; public static ContextFamilyTree Family(int focus,int[] expanded,bool removed=false) { var links=new List{Relationship(9),Relationship(10),new(){CharacterRelationshipID=1,CharacterAID=1,CharacterBID=3,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=2,CharacterAID=3,CharacterBID=5,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=3,CharacterAID=4,CharacterBID=5,RelationshipTypeName="Biological Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=4,CharacterAID=6,CharacterBID=11,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=5,CharacterAID=12,CharacterBID=6,RelationshipTypeName="Adoptive Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=6,CharacterAID=13,CharacterBID=6,RelationshipTypeName="Step Parent",RelationshipCategoryName="Family"}}.Where(r=>!removed||r.CharacterRelationshipID!=9).ToArray(); diff --git a/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs b/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs index 6672bb95..566a2152 100644 --- a/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs +++ b/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs @@ -1,3 +1,4 @@ +using PlotLine.Models; using System.Data;using System.Text.Json;using Dapper;using Microsoft.Data.SqlClient; internal static class CharacterWorkspaceDatabaseTests @@ -17,7 +18,24 @@ async Task Case(string name,Func action){using var tx=db.Be await Case("parent archive retains history and restores",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);await Event(tx,r);var frame=await Frame(tx,r);Check(frame.Events==2,"preview reports dependent scene events");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=@r",new{r},tx)==2,"erroneous parent definition archives reversibly without cascading its two events");await db.ExecuteAsync("dbo.Archive_Restore",new{EntityType="Relationship",EntityID=r},tx,commandType:CommandType.StoredProcedure);Check(await db.ExecuteScalarAsync("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"existing canonical restore reactivates the same definition and retained history");}); await Case("reciprocal single record and independent reverse",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,true);Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterAID=@actor AND CharacterBID=@c OR CharacterAID=@c AND CharacterBID=@actor",new{actor,c},tx)==1,"canonical reciprocal flag does not create an extra reverse row");int reverse=await Rel(tx,c,false,childType,true);var frame=await Frame(tx,r);Check(frame.Other==1,"confirmation distinguishes a separately authored reverse fact");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@reverse",new{reverse},tx)==0,"independent reverse fact is retained, not silently cascaded");}); foreach(var type in new[]{parent,friend})await Case("definition edit "+type,async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,type);var frame=await Frame(tx,r);await Change(tx,r,frame.Version,"definition");var row=await db.QuerySingleAsync<(int Type,int A,int B,bool Initial,string Notes)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID,IsInitialRelationship,Notes FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==type&&row.A==actor&&row.B==c&&row.Initial&&row.Notes=="Updated isolated definition","focused definition edit preserves pair/type and family/story meaning");}); +await Case("global grouped alphabetical pagination",async tx=>{ + string token="Isolated workspace regression Group "+Guid.NewGuid().ToString("N");var expected=new List<(int ID,string Name)>(); + for(int i=0;i<28;i++){string name=token+" "+(i==0?"alpha":i==1?"ALPHA":((char)('b'+i%22)).ToString()+i.ToString("00"));int c=await db.QuerySingleAsync("dbo.Character_Save",new{ProjectID=project,CharacterName=name},tx,commandType:CommandType.StoredProcedure);expected.Add((c,name));await Rel(tx,c);} + int focus=expected[0].ID;await Rel(tx,focus,false,friend);await Rel(tx,focus,false,childType,true);for(int i=0;i<25;i++)await Rel(tx,focus); + async Task<(int Total,List Rows)> Read(int page=1,string? category=null,int? other=null,int definitionPage=1){using var grid=await db.QueryMultipleAsync("dbo.CharacterWorkspace_Relationships",new{CharacterID=actor,UserID=owner,Page=page,Search=token,Category=category,OtherCharacterID=other,DefinitionPage=definitionPage},tx,commandType:CommandType.StoredProcedure);int total=await grid.ReadSingleAsync();await grid.ReadAsync();await grid.ReadAsync();await grid.ReadAsync();return(total,(await grid.ReadAsync()).ToList());} + var first=await Read();var second=await Read(2);var actual=first.Rows.Concat(second.Rows).Select(r=>(int)((int)r.CharacterAID==actor?r.CharacterBID:r.CharacterAID)).Distinct().ToArray();var sorted=expected.OrderBy(e=>e.Name,StringComparer.OrdinalIgnoreCase).ThenBy(e=>e.ID).Select(e=>e.ID).ToArray();Check(first.Total==28&&actual.SequenceEqual(sorted),"case-insensitive alphabetical groups span all pages, direction independent and duplicate names stable by identity"); + var group=await Read(other:focus);var more=await Read(other:focus,definitionPage:2);Check(group.Total==1&&group.Rows.Count==25&&more.Rows.Count==3,"one character group retains 28 distinct definitions with bounded inner pagination"); + var family=await Read(category:"family",other:focus);var story=await Read(category:"story",other:focus);Check(family.Total==1&&story.Total==1&&story.Rows.Count==1&&(string)story.Rows[0].RelationshipTypeName=="Friend","family/story filters classify individual definitions, including one pair in both categories"); + Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND (CharacterAID=@focus AND CharacterBID=@actor OR CharacterBID=@focus AND CharacterAID=@actor)",new{project,focus,actor},tx)==28,"grouping and pagination never merge or deduplicate canonical definitions"); +}); +async Task Structural(SqlTransaction tx,int r,string v,int type,bool reverse=false,bool? reciprocal=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=owner,RelationshipID=r,Version=v,Action="definition",Notes="Structural isolated edit",TypeID=type,ReverseDirection=reverse,Reciprocal=reciprocal},tx,commandType:CommandType.StoredProcedure); +await Case("canonical type and direction edits retain record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,childType,true);var row=await db.QuerySingleAsync<(int Type,int A,int B)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==childType&&row.A==c&&row.B==actor,"canonical family type/direction edit retains exact definition ID without recreating records");}); +await Case("story reciprocity edit retains one record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,friend);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,friend,reciprocal:true);Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsReciprocal=1",new{r},tx)==1,"story reciprocity is one flag on the same canonical definition");}); +await Case("incompatible category rejected",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,friend);throw new Exception("Cross-category change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"cross-category type change requires full-editor review");}}); +await Case("history prevents semantic rewrite",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,childType);throw new Exception("History reinterpretation accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"dependent history prevents unsafe structural reinterpretation");}}); +await Case("family reciprocity cannot manufacture reverse parentage",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,parent,reciprocal:true);throw new Exception("Family reciprocity change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"family reciprocity changes require explicit full-editor review");}}); await Case("single event edit then remove",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);int e=await Event(tx,r),other=await Event(tx,r);var frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-edit",e:e,notes:"Updated one event");Check(await db.ExecuteScalarAsync("SELECT Description FROM dbo.RelationshipEvents WHERE RelationshipEventID=@e",new{e},tx)=="Updated one event","one event changes without rewriting the definition");frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-remove",e:e);Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");}); +await Case("dedicated history canonical order and bounded pages",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);for(int i=0;i<28;i++)await Event(tx,r,"Recorded history "+i);async Task> Read(int page){using var grid=await db.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution",new{CharacterRelationshipID=r,Page=page},tx,commandType:CommandType.StoredProcedure);await grid.ReadAsync();var rows=(await grid.ReadAsync()).ToList();await grid.ReadAsync();return rows;}var first=await Read(1);var second=await Read(2);Check(first.Count==25&&second.Count==3&&first.All(e=>e.TotalRecords==28),"dedicated history pages 28 actual events as 25 + 3 with no synthetic transitions");Check(first.Concat(second).Select(e=>e.RelationshipEventID).SequenceEqual(first.Concat(second).Select(e=>e.RelationshipEventID).OrderBy(id=>id)),"same-scene developments retain stable canonical event order");}); await Case("stale dependent history",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Event(tx,r);try{await Change(tx,r,frame.Version,"archive");throw new Exception("Stale archive accepted");}catch(SqlException ex)when(ex.Number==51021){Check(true,"new dependent event invalidates the confirmation atomically");}}); await Case("permission enforcement",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",user:-991);throw new Exception("Foreign user accepted");}catch(SqlException ex)when(ex.Number==51020){Check(true,"ungranted user cannot mutate a definition");}}); await Case("missing explicit confirmation",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",false);throw new Exception("Unconfirmed accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"SQL enforces explicit destructive confirmation");}}); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 6189d0da..22d29a93 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -1569,7 +1569,7 @@ static void CharacterDetailCanQueueSingleCharacterEnrichment() var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs")); var characterService = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs")); var enrichmentService = File.ReadAllText(Path.Combine(root, "Services/CharacterEnrichmentService.cs")); - var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")); + var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml")); Assert(view.Contains("Reanalyse character", StringComparison.Ordinal), "Character detail should expose a discreet reanalyse action."); Assert(view.Contains("data-character-reanalyse-form", StringComparison.Ordinal), "Character reanalyse action should be script-addressable."); @@ -6236,7 +6236,7 @@ static void CharacterMergeIsReusableStoredProcedureWorkflow() var repository = File.ReadAllText(Path.Combine(root, "Data/Repositories.cs")); var services = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs")); var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs")); - var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")); + var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml")); var merge = File.ReadAllText(Path.Combine(root, "Views/Characters/Merge.cshtml")); var siCharacters = File.ReadAllText(Path.Combine(root, "Services/StoryIntelligenceCharacterImportService.cs")); var migration = File.ReadAllText(Path.Combine(root, "Sql/165_Phase26A_PovAndCharacterIdentityFoundation.sql")); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index f05210b3..bfdc2c12 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -414,6 +414,7 @@ internal static class ToolbarBrowserHost var graph=PlotLine.Services.Context.ContextRelationshipLenses.Compose(new(new(){Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=fixture.Scene.SceneID,ChapterID=10}],Characters=fixture.Structure.Seeds.Where(c=>visible.People.Contains(c.CharacterID)).ToList(),Relationships=fixture.Structure.Links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).ToList()},focus,visible.Truncated),"family",fixture.Scene,context.Request.Query["readonly"]!="true"); return context.Response.WriteAsJsonAsync(new PlotLine.Services.Context.ContextFamilyTree(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People))); }); + app.MapGet("/relationship-evolution-fixture",async context=>{int count=int.TryParse(context.Request.Query["count"],out var n)?n:1;var model=new RelationshipEvolutionViewModel{Project=new(){ProjectID=7,ProjectName="Evolution fixture"},Relationship=CharacterWorkspaceBrowserFixture.Relationship(),ReturnCharacterID=5,CanEdit=context.Request.Query["viewer"]!="true",Events=Enumerable.Range(1,count).Select(i=>new PlotLine.Models.RelationshipProgressionPoint{RelationshipEventID=i,CharacterRelationshipID=9,SceneID=i,SceneNumber=i,BookTitle="Recorded book",ChapterNumber=1,SceneTitle="Canonical scene "+i,GlobalSceneIndex=i*3,Intensity=i==2?null:Math.Min(10,i+2),RelationshipStateName="Recorded state "+i,Description="Canonical event description",TotalRecords=count}).ToArray()};await RenderFullAsync(context,"Dynamics","Relationship",model);}); app.MapGet("/character-workspace-fixture",async context=>{ var id=int.TryParse(context.Request.Query["id"],out var cid)?cid:5;var profile=CharacterWorkspaceBrowserFixture.Header(id,context.Request.Query["viewer"]=="true");profile.WorkspaceTab=context.Request.Query["tab"].FirstOrDefault();if(profile.WorkspaceTab!=null)profile.WorkspacePage=CharacterWorkspaceBrowserFixture.Page(id,new(){Tab=profile.WorkspaceTab},context.Request.Query["viewer"]=="true");await RenderFullAsync(context,"Characters","Details",profile); }); diff --git a/PlotLine/Controllers/CharacterWorkspaceController.cs b/PlotLine/Controllers/CharacterWorkspaceController.cs index 08c356ff..515e60a2 100644 --- a/PlotLine/Controllers/CharacterWorkspaceController.cs +++ b/PlotLine/Controllers/CharacterWorkspaceController.cs @@ -26,7 +26,7 @@ public sealed class CharacterWorkspaceController(CharacterWorkspace workspace):C public async Task Operation(int id,CharacterWorkspaceOperation input,CancellationToken ct) { if(input.CharacterID!=id)return Forbid();try{if(!ModelState.IsValid)throw new ArgumentException("Check the fields below.");await workspace.Change(input,ct);return Ok(new{saved=true,message=input.Action=="archive"?"Relationship removed from active views. History retained; restore is available in Archived Items.":input.Action=="event-remove"?"One relationship event removed.":"Relationship changes saved."});} - catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){var frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);} + catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){CharacterWorkspaceOperation frame;try{frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);}catch(UnauthorizedAccessException){return Forbid();}frame.TypeID=input.TypeID??frame.TypeID;frame.ReverseDirection=input.ReverseDirection;frame.Reciprocal=input.Reciprocal??frame.Reciprocal;frame.Permanent=input.Permanent;frame.ReaderKnows=input.ReaderKnows;frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);} } [HttpGet("Add/{id:int}")] public async Task Add(int id,CancellationToken ct) diff --git a/PlotLine/Controllers/DynamicsController.cs b/PlotLine/Controllers/DynamicsController.cs index fea7aa51..dc6b3be7 100644 --- a/PlotLine/Controllers/DynamicsController.cs +++ b/PlotLine/Controllers/DynamicsController.cs @@ -19,10 +19,14 @@ public sealed class DynamicsController(IDynamicsService dynamics) : Controller return model is null ? NotFound() : View(model); } - public async Task Relationship(int id) + public async Task Relationship(int id,[FromServices]CharacterWorkspace workspace,int? returnCharacterId=null,int? returnSceneId=null,int page=1,CancellationToken ct=default) { - var model = await dynamics.GetRelationshipEvolutionAsync(id); - return model is null ? NotFound() : View(model); + if(page is <1 or >100000)return BadRequest(); + var model=await dynamics.GetRelationshipEvolutionAsync(id,page);if(model is null)return NotFound(); + var r=model.Relationship;var anchor=returnCharacterId==r.CharacterBID?r.CharacterBID:r.CharacterAID; + try{var scope=await workspace.Scope(anchor);if(scope.Project.ProjectID!=r.ProjectID)return NotFound();model.CanEdit=scope.CanEdit;}catch(UnauthorizedAccessException){return NotFound();} + if(page>1&&model.Events.Count==0){model=await dynamics.GetRelationshipEvolutionAsync(id,1);if(model is null)return NotFound();model.CanEdit=(await workspace.Scope(anchor)).CanEdit;page=1;} + model.ReturnCharacterID=anchor;model.ReturnSceneID=returnSceneId;model.Page=page;return View(model); } public async Task Knowledge(int id) diff --git a/PlotLine/Data/CharacterWorkspaceReader.cs b/PlotLine/Data/CharacterWorkspaceReader.cs index 620f3cb3..33f3c015 100644 --- a/PlotLine/Data/CharacterWorkspaceReader.cs +++ b/PlotLine/Data/CharacterWorkspaceReader.cs @@ -29,7 +29,7 @@ public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,I public async Task<(int,RelationshipMapData)> Relationships(int character,int project,int user,CharacterWorkspaceQuery q,CancellationToken ct) { using var db=connections.CreateConnection();int total;RelationshipMapData data; - using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Relationships",new{CharacterID=character,UserID=user,q.Page,Search=q.Search??"",q.RelationshipID},commandType:CommandType.StoredProcedure,cancellationToken:ct))){total=(await grid.ReadSingleAsync()).Total;data=new(){Books=(await grid.ReadAsync()).ToList(),Chapters=(await grid.ReadAsync()).ToList(),Scenes=(await grid.ReadAsync()).ToList(),Relationships=(await grid.ReadAsync()).ToList()};} + using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Relationships",new{CharacterID=character,UserID=user,q.Page,Search=q.Search??"",q.RelationshipID,q.Category,q.OtherCharacterID,q.DefinitionPage},commandType:CommandType.StoredProcedure,cancellationToken:ct))){total=(await grid.ReadSingleAsync()).Total;data=new(){Books=(await grid.ReadAsync()).ToList(),Chapters=(await grid.ReadAsync()).ToList(),Scenes=(await grid.ReadAsync()).ToList(),Relationships=(await grid.ReadAsync()).ToList()};} if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Use the full Relationships Editor for a project beyond the workspace ordering limit."); var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var maximum=q.SceneID.HasValue?order.SingleOrDefault(s=>s.SceneID==q.SceneID)?.Ordinal??throw new UnauthorizedAccessException():order.Count-1; var events=(await db.QueryAsync(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=maximum},commandType:CommandType.StoredProcedure,cancellationToken:ct))).ToList();await ParagraphEvidenceProjection.Apply(db,configuration,events); @@ -44,5 +44,5 @@ public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,I var item=(await grid.ReadAsync()).SingleOrDefault();if(item==null)return(frame,null);json=JsonSerializer.Serialize((object)item);var eventFrame=JsonSerializer.Deserialize(json,options)!;eventFrame.Record=JsonSerializer.Deserialize(json,options)!;return(frame,eventFrame); } public async Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct) - {using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness},commandType:CommandType.StoredProcedure,cancellationToken:ct));} + {using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness,input.TypeID,input.ReverseDirection,input.Reciprocal,input.Permanent,input.ReaderKnows},commandType:CommandType.StoredProcedure,cancellationToken:ct));} } diff --git a/PlotLine/Data/Repositories.cs b/PlotLine/Data/Repositories.cs index 028c8459..01d77bd4 100644 --- a/PlotLine/Data/Repositories.cs +++ b/PlotLine/Data/Repositories.cs @@ -431,7 +431,7 @@ public interface IExportRepository public interface IDynamicsRepository { Task<(Character? Character, IReadOnlyList ArcPoints, IReadOnlyList RelationshipEvents, IReadOnlyList KnowledgeEvents, IReadOnlyList Issues)> GetCharacterArcAsync(int characterId); - Task<(CharacterRelationship? Relationship, IReadOnlyList Events, IReadOnlyList Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId); + Task<(CharacterRelationship? Relationship, IReadOnlyList Events, IReadOnlyList Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1); Task<(Character? Character, IReadOnlyList KnowledgeEvents, IReadOnlyList Issues)> GetKnowledgeTimelineAsync(int characterId); Task<(IReadOnlyList Pairings, IReadOnlyList Issues)> GetStoryDynamicsAsync(int projectId); Task RunContinuityChecksAsync(int projectId, int? bookId, int? sceneId); @@ -1774,10 +1774,10 @@ public sealed class DynamicsRepository(ISqlConnectionFactory connectionFactory,I return (character,arc,await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,relationships),await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,knowledge),issues); } - public async Task<(CharacterRelationship? Relationship, IReadOnlyList Events, IReadOnlyList Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId) + public async Task<(CharacterRelationship? Relationship, IReadOnlyList Events, IReadOnlyList Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1) { using var connection = connectionFactory.CreateConnection(); - using var result = await connection.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution", new { CharacterRelationshipID = characterRelationshipId }, commandType: CommandType.StoredProcedure); + using var result = await connection.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution", new { CharacterRelationshipID = characterRelationshipId,Page=page }, commandType: CommandType.StoredProcedure); return ( await result.ReadSingleOrDefaultAsync(), (await result.ReadAsync()).ToList(), diff --git a/PlotLine/Models/CoreModels.cs b/PlotLine/Models/CoreModels.cs index 16a32280..5b237f60 100644 --- a/PlotLine/Models/CoreModels.cs +++ b/PlotLine/Models/CoreModels.cs @@ -1329,6 +1329,7 @@ public sealed class RelationshipState public sealed class CharacterRelationship { + public int WorkspaceDefinitionCount {get;set;} = 1; public int? CreatedByUserID { get; set; } public int? ModifiedByUserID { get; set; } public DateTime? CreatedDateUTC { get; set; } @@ -2587,6 +2588,9 @@ public sealed class CharacterArcPoint public sealed class RelationshipProgressionPoint { + public int TotalRecords {get;set;} + public string EvidenceState {get;set;}="Verified"; + public string? SourceReviewKey {get;set;} public int RelationshipEventID { get; set; } public int CharacterRelationshipID { get; set; } public int SceneID { get; set; } diff --git a/PlotLine/Services/CharacterWorkspace.cs b/PlotLine/Services/CharacterWorkspace.cs index 59e83936..55b4ea1d 100644 --- a/PlotLine/Services/CharacterWorkspace.cs +++ b/PlotLine/Services/CharacterWorkspace.cs @@ -14,7 +14,7 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR var author=user.UserId??throw new UnauthorizedAccessException();var character=await characters.GetCharacterAsync(id)??throw new UnauthorizedAccessException();var project=await projects.GetForUserAsync(character.ProjectID,author)??throw new UnauthorizedAccessException();return(character,project,ContextEditPolicy.CanEdit(project)); } public static void Validate(CharacterWorkspaceQuery q) - {if(!Tabs.Contains(q.Tab)&&q.Tab is not ("history" or "scenes" or "gallery"))throw new ArgumentException("Choose a character workspace tab.");if(q.Page is <1 or >100000||q.Search?.Length>120||q.Category?.Length>100)throw new ArgumentException("Invalid workspace filter.");} + {if(q.Tab=="relationships"&&!string.IsNullOrEmpty(q.Category)&&q.Category is not ("family" or "story"))throw new ArgumentException("Choose Family, Story or all definitions.");if(!Tabs.Contains(q.Tab)&&q.Tab is not ("history" or "scenes" or "gallery"))throw new ArgumentException("Choose a character workspace tab.");if(q.Page is <1 or >100000||q.Search?.Length>120||q.Category?.Length>100||q.DefinitionPage is <1 or >100000)throw new ArgumentException("Invalid workspace filter.");} public async Task Header(int id,string? tab,CancellationToken ct) { if(tab!=null&&!Tabs.Contains(tab))throw new ArgumentException("Choose a character workspace tab.");var scope=await Scope(id);var summary=await reader.Summary(id,user.UserId!.Value,ct);var age=CharacterAgeDisplayService.GetProfileAge(scope.Character,summary.Ages.Select(r=>r.Scene).ToArray(),summary.Ages.Where(r=>r.IsAppearance).Select(r=>new SceneCharacter{CharacterID=id,SceneID=r.SceneID}).ToArray()); @@ -51,7 +51,7 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR { var scope=await Scope(id);if(!scope.CanEdit)throw new UnauthorizedAccessException();if(action is not ("definition" or "archive" or "event-edit" or "event-remove"))throw new ArgumentException("Unsupported relationship operation."); (CharacterRelationshipFrame Relationship,CharacterWorkspaceEvent? Event) frame;try{frame=await reader.Frame(id,user.UserId!.Value,relationship,eventID,ct);}catch(SqlException error)when(error.Number==51020){throw new UnauthorizedAccessException();}if(action.StartsWith("event-")&&frame.Event==null)throw new UnauthorizedAccessException();var r=frame.Relationship.Relationship;var e=frame.Event?.Record;var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID); - return new(){CharacterID=id,RelationshipID=relationship,EventID=eventID,Action=action,Version=frame.Relationship.Version,Record=frame.Relationship,Event=frame.Event,Notes=e?.Description??r.Notes,StateID=e?.RelationshipStateID??r.InitialRelationshipStateID,Intensity=e?.Intensity??r.InitialIntensity,Awareness=e?.IsKnownToOtherCharacter??r.ReaderInitiallyKnows,States=lookups.RelationshipStates.Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToArray()}; + return new(){TypeID=r.RelationshipTypeID,Reciprocal=r.IsReciprocal,Permanent=r.IsPermanent,ReaderKnows=r.IsKnownToReader,Types=lookups.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray(),CharacterID=id,RelationshipID=relationship,EventID=eventID,Action=action,Version=frame.Relationship.Version,Record=frame.Relationship,Event=frame.Event,Notes=e?.Description??r.Notes,StateID=e?.RelationshipStateID??r.InitialRelationshipStateID,Intensity=e?.Intensity??r.InitialIntensity,Awareness=e?.IsKnownToOtherCharacter??r.ReaderInitiallyKnows,States=lookups.RelationshipStates.Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToArray()}; } public async Task Change(CharacterWorkspaceOperation input,CancellationToken ct) { diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index ba7293e3..36ca7834 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -648,7 +648,7 @@ public interface IExportService public interface IDynamicsService { Task GetCharacterArcAsync(int characterId); - Task GetRelationshipEvolutionAsync(int characterRelationshipId); + Task GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1); Task GetKnowledgeTimelineAsync(int characterId); Task GetStoryDynamicsAsync(int projectId); Task RunContinuityChecksAsync(int projectId, int? bookId, int? sceneId); @@ -7560,9 +7560,9 @@ public sealed class DynamicsService(IProjectRepository projects, IDynamicsReposi }; } - public async Task GetRelationshipEvolutionAsync(int characterRelationshipId) + public async Task GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1) { - var data = await dynamics.GetRelationshipEvolutionAsync(characterRelationshipId); + var data = await dynamics.GetRelationshipEvolutionAsync(characterRelationshipId,page); if (data.Relationship is null) { return null; diff --git a/PlotLine/Sql/309_CharacterRelationshipGroups.sql b/PlotLine/Sql/309_CharacterRelationshipGroups.sql new file mode 100644 index 00000000..4fd78317 --- /dev/null +++ b/PlotLine/Sql/309_CharacterRelationshipGroups.sql @@ -0,0 +1,28 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1 +AS +BEGIN + SET NOCOUNT ON; + DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1)); + IF @project IS NULL THROW 51020,'Character unavailable',1; + IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1; + DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%'; + SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs + FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID + WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID) + AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' AND cat.CategoryName=N'Family') OR (@Category=N'story' AND COALESCE(cat.CategoryName,N'')<>N'Family')) + AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~'); + SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName; + SELECT COUNT(*) Total FROM #Groups; + SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0; + SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0; + SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder 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=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0; + ;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i) + SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName + FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID JOIN dbo.Characters a ON a.CharacterID=r.CharacterAID JOIN dbo.Characters b ON b.CharacterID=r.CharacterBID JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID LEFT JOIN dbo.RelationshipStates st ON st.RelationshipStateID=r.InitialRelationshipStateID + WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN ((@DefinitionPage-1)*25)+1 AND @DefinitionPage*25 + ORDER BY g.GroupNumber,x.DefinitionNumber; +END; +GO diff --git a/PlotLine/Sql/310_CharacterRelationshipQuickEdit.sql b/PlotLine/Sql/310_CharacterRelationshipQuickEdit.sql new file mode 100644 index 00000000..8110fe08 --- /dev/null +++ b/PlotLine/Sql/310_CharacterRelationshipQuickEdit.sql @@ -0,0 +1,62 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_ChangeRelationship @CharacterID int,@UserID int,@RelationshipID int,@Version varchar(64),@Action nvarchar(24),@Confirmed bit=0,@EventID int=NULL,@Notes nvarchar(4000)=NULL,@StateID int=NULL,@Intensity int=NULL,@Awareness bit=0,@TypeID int=NULL,@ReverseDirection bit=0,@Reciprocal bit=NULL,@Permanent bit=NULL,@ReaderKnows bit=NULL +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @project int,@allowed bit=0; + SELECT @project=c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p WITH(HOLDLOCK) ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a WITH(HOLDLOCK) ON a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0; + IF @project IS NULL THROW 51020,'Editing unavailable',1; + DECLARE @current varchar(64); + SELECT @current=CONVERT(varchar(64),HASHBYTES('SHA2_256',CONCAT((SELECT r.* FOR JSON PATH,WITHOUT_ARRAY_WRAPPER),(SELECT e.RelationshipEventID,e.UpdatedDate,e.SceneID,e.RelationshipStateID,e.Description FROM dbo.RelationshipEvents e WITH(UPDLOCK,HOLDLOCK) WHERE e.CharacterRelationshipID=r.CharacterRelationshipID ORDER BY e.RelationshipEventID FOR JSON PATH))),2) + FROM dbo.CharacterRelationships r WITH(UPDLOCK,HOLDLOCK) WHERE r.CharacterRelationshipID=@RelationshipID AND r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID); + IF @current IS NULL THROW 51020,'Relationship unavailable',1; + IF @Version IS NULL OR @current<>@Version THROW 51021,'This relationship or its history changed. Cancel and reopen to review current values.',1; + IF @Action=N'archive' + BEGIN + IF @Confirmed<>1 THROW 51022,'Confirm removal of this underlying relationship.',1; + EXEC dbo.Relationship_Archive @CharacterRelationshipID=@RelationshipID; + END + ELSE IF @Action=N'definition' + BEGIN + IF @Intensity IS NOT NULL AND @Intensity NOT BETWEEN 1 AND 10 THROW 51022,'Intensity must be 1 to 10.',1; + IF @StateID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipStates WHERE RelationshipStateID=@StateID) THROW 51022,'Choose a recorded state',1; + DECLARE @a int,@b int,@type int,@savedPermanent bit,@start int,@end int,@known bit,@initial bit,@book int,@reader bit,@state int,@strength int,@savedReciprocal bit; + SELECT @a=CharacterAID,@b=CharacterBID,@type=RelationshipTypeID,@savedPermanent=IsPermanent,@start=StartSceneID,@end=EndSceneID,@known=IsKnownToReader,@initial=IsInitialRelationship,@book=InitialBookID,@reader=ReaderInitiallyKnows,@state=InitialRelationshipStateID,@strength=InitialIntensity,@savedReciprocal=IsReciprocal FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@RelationshipID; + DECLARE @oldCategory int=(SELECT RelationshipCategoryID FROM dbo.RelationshipTypes WHERE RelationshipTypeID=@type),@newCategory int,@categoryName nvarchar(100); + SET @TypeID=COALESCE(@TypeID,@type);SET @Reciprocal=COALESCE(@Reciprocal,@savedReciprocal); + SELECT @newCategory=t.RelationshipCategoryID,@categoryName=c.CategoryName FROM dbo.RelationshipTypes t JOIN dbo.RelationshipCategories c ON c.RelationshipCategoryID=t.RelationshipCategoryID WHERE t.RelationshipTypeID=@TypeID AND (t.IsActive=1 OR t.RelationshipTypeID=@type); + IF @newCategory IS NULL THROW 51022,'Choose a supported canonical relationship type.',1; + IF @newCategory<>@oldCategory THROW 51022,'Changing category requires the full Relationships Editor; no history or family semantics were changed.',1; + IF (@TypeID<>@type OR @ReverseDirection=1 OR @Reciprocal<>@savedReciprocal) AND EXISTS(SELECT 1 FROM dbo.RelationshipEvents WITH(UPDLOCK,HOLDLOCK) WHERE CharacterRelationshipID=@RelationshipID) THROW 51022,'This definition has recorded history. Use the full Relationships Editor for structural changes; notes and initial properties remain editable here.',1; + IF @categoryName=N'Family' AND @Reciprocal<>@savedReciprocal THROW 51022,'Family reciprocity is structural. Use the full Relationships Editor to review the exact family semantics.',1; + SET @type=@TypeID;SET @savedReciprocal=@Reciprocal;SET @savedPermanent=COALESCE(@Permanent,@savedPermanent);SET @known=COALESCE(@ReaderKnows,@known); + IF @ReverseDirection=1 BEGIN DECLARE @swap int=@a;SET @a=@b;SET @b=@swap;END; + IF @initial=1 BEGIN SET @state=@StateID;SET @strength=@Intensity;SET @reader=@Awareness;END; + EXEC dbo.Relationship_Save @CharacterRelationshipID=@RelationshipID,@ProjectID=@project,@CharacterAID=@a,@CharacterBID=@b,@RelationshipTypeID=@type,@IsPermanent=@savedPermanent,@StartSceneID=@start,@EndSceneID=@end,@IsKnownToReader=@known,@Notes=@Notes,@IsInitialRelationship=@initial,@InitialBookID=@book,@ReaderInitiallyKnows=@reader,@InitialRelationshipStateID=@state,@InitialIntensity=@strength,@IsReciprocal=@savedReciprocal; + END + ELSE IF @Action IN(N'event-edit',N'event-remove') + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents WITH(UPDLOCK,HOLDLOCK) WHERE RelationshipEventID=@EventID AND CharacterRelationshipID=@RelationshipID) THROW 51020,'Event unavailable',1; + IF EXISTS(SELECT 1 FROM dbo.RelationshipEvents WHERE RelationshipEventID=@EventID AND SourceReviewKey IS NOT NULL) OR EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex WITH(UPDLOCK,HOLDLOCK) WHERE EventKind=N'Relationship' AND EventID=@EventID) OR EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WITH(UPDLOCK,HOLDLOCK) WHERE SourceEventID=@EventID) THROW 51022,'This event has source/review dependencies. Use its source or review workflow; no history was deleted.',1; + IF @Action=N'event-remove' + BEGIN + IF @Confirmed<>1 THROW 51022,'Confirm removal of this one event.',1; + EXEC dbo.RelationshipEvent_Delete @RelationshipEventID=@EventID; + END + ELSE + BEGIN + IF @StateID IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.RelationshipStates WHERE RelationshipStateID=@StateID) THROW 51022,'Choose a recorded state.',1; + IF @Intensity IS NOT NULL AND @Intensity NOT BETWEEN 1 AND 10 THROW 51022,'Intensity must be 1 to 10.',1; + DECLARE @scene int=(SELECT SceneID FROM dbo.RelationshipEvents WHERE RelationshipEventID=@EventID); + EXEC dbo.RelationshipEvent_Save @RelationshipEventID=@EventID,@CharacterRelationshipID=@RelationshipID,@SceneID=@scene,@RelationshipStateID=@StateID,@Intensity=@Intensity,@IsKnownToOtherCharacter=@Awareness,@Description=@Notes; + END; + END + ELSE THROW 51022,'Unsupported operation.',1; + COMMIT; + END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH; +END; +GO diff --git a/PlotLine/Sql/311_RelationshipEvolutionRefinement.sql b/PlotLine/Sql/311_RelationshipEvolutionRefinement.sql new file mode 100644 index 00000000..be65a58b --- /dev/null +++ b/PlotLine/Sql/311_RelationshipEvolutionRefinement.sql @@ -0,0 +1,37 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.Dynamics_RelationshipEvolution + @CharacterRelationshipID int,@Page int=1 +AS +BEGIN + SET NOCOUNT ON; + IF @Page<1 OR @Page>100000 THROW 51022,'Invalid history page',1; + DECLARE @project int=(SELECT ProjectID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@CharacterRelationshipID); + + SELECT cr.CharacterRelationshipID, cr.ProjectID, cr.CharacterAID, ca.CharacterName AS CharacterAName, + cr.CharacterBID, cb.CharacterName AS CharacterBName, cr.RelationshipTypeID, rt.TypeName AS RelationshipTypeName, + cr.IsReciprocal,cr.IsInitialRelationship,cr.InitialRelationshipStateID,cr.InitialIntensity,cr.ReaderInitiallyKnows,cr.InitialBookID,cr.IsPermanent, cr.StartSceneID, cr.EndSceneID, cr.IsKnownToReader, cr.Notes, cr.CreatedDate, cr.UpdatedDate, cr.IsArchived + FROM dbo.CharacterRelationships cr + INNER JOIN dbo.Characters ca ON ca.CharacterID = cr.CharacterAID + INNER JOIN dbo.Characters cb ON cb.CharacterID = cr.CharacterBID + INNER JOIN dbo.RelationshipTypes rt ON rt.RelationshipTypeID = cr.RelationshipTypeID + WHERE cr.CharacterRelationshipID = @CharacterRelationshipID; + + SELECT re.RelationshipEventID, re.CharacterRelationshipID, re.SceneID, nso.BookTitle, nso.BookSubtitle, nso.ChapterNumber, nso.SceneNumber, + nso.SceneTitle, CAST(nso.Ordinal+1 AS int) GlobalSceneIndex,COUNT(*) OVER() TotalRecords, rs.StateName AS RelationshipStateName, re.Intensity, re.IsKnownToOtherCharacter,re.Description,COALESCE(ev.EvidenceState,N'Verified') EvidenceState,re.SourceReviewKey + FROM dbo.RelationshipEvents re + INNER JOIN dbo.RelationshipStates rs ON rs.RelationshipStateID = re.RelationshipStateID + INNER JOIN dbo.CharacterWorkspace_SceneOrder(@project) nso ON nso.SceneID = re.SceneID + OUTER APPLY(SELECT TOP(1) m.EvidenceState FROM dbo.ManuscriptEvidenceIndex m WHERE m.EventKind=N'Relationship' AND m.EventID=re.RelationshipEventID AND m.IsPrimary=1 ORDER BY CASE WHEN m.EvidenceState=N'Verified' THEN 1 ELSE 0 END,m.EvidenceID) ev + WHERE re.CharacterRelationshipID = @CharacterRelationshipID + ORDER BY nso.Ordinal,re.RelationshipEventID OFFSET ((@Page-1)*25) ROWS FETCH NEXT 25 ROWS ONLY; + + SELECT N'Relationship Continuity' AS Category, ws.SeverityName, cw.Message AS Title, cw.Details AS Detail, cw.SceneID, cw.EntityID, cw.EntityType + FROM dbo.ContinuityWarnings cw + INNER JOIN dbo.WarningSeverities ws ON ws.WarningSeverityID = cw.WarningSeverityID + INNER JOIN dbo.WarningTypes wt ON wt.WarningTypeID = cw.WarningTypeID + WHERE cw.IsDismissed = 0 AND cw.EntityType = N'Relationship' AND cw.EntityID = @CharacterRelationshipID + AND wt.TypeName = N'Abrupt Relationship Change'; +END; +GO diff --git a/PlotLine/Sql/312_CharacterRelationshipGroupBounds.sql b/PlotLine/Sql/312_CharacterRelationshipGroupBounds.sql new file mode 100644 index 00000000..042122d7 --- /dev/null +++ b/PlotLine/Sql/312_CharacterRelationshipGroupBounds.sql @@ -0,0 +1,29 @@ +-- At most 25 groups × 3 definitions; focused groups page all definitions in batches of 25. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1 +AS +BEGIN + SET NOCOUNT ON; + DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1)); + IF @project IS NULL THROW 51020,'Character unavailable',1; + IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1; + DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%'; + SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs + FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID + WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID) + AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' AND cat.CategoryName=N'Family') OR (@Category=N'story' AND COALESCE(cat.CategoryName,N'')<>N'Family')) + AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~'); + SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName; + SELECT COUNT(*) Total FROM #Groups; + SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0; + SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0; + SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder 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=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0; + ;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i) + SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName + FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID JOIN dbo.Characters a ON a.CharacterID=r.CharacterAID JOIN dbo.Characters b ON b.CharacterID=r.CharacterBID JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID LEFT JOIN dbo.RelationshipStates st ON st.RelationshipStateID=r.InitialRelationshipStateID + WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN CASE WHEN @OtherCharacterID IS NULL THEN 1 ELSE ((@DefinitionPage-1)*25)+1 END AND CASE WHEN @OtherCharacterID IS NULL THEN 3 ELSE @DefinitionPage*25 END + ORDER BY g.GroupNumber,x.DefinitionNumber; +END; +GO diff --git a/PlotLine/Sql/313_CharacterRelationshipLensFilters.sql b/PlotLine/Sql/313_CharacterRelationshipLensFilters.sql new file mode 100644 index 00000000..7cdc2057 --- /dev/null +++ b/PlotLine/Sql/313_CharacterRelationshipLensFilters.sql @@ -0,0 +1,30 @@ +-- Mirrors the existing canonical family predicate in ContextFamily_Structure / ContextRelationshipLenses.Family. +-- At most 25 groups × 3 definitions; focused groups page all definitions in batches of 25. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1 +AS +BEGIN + SET NOCOUNT ON; + DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1)); + IF @project IS NULL THROW 51020,'Character unavailable',1; + IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1; + DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%'; + SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs + FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID + WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID) + AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' AND (cat.CategoryName=N'Family' OR (cat.CategoryName=N'Romantic / Sexual' AND t.TypeName IN(N'Spouse',N'Partner',N'Ex-spouse',N'Former spouse',N'Romantic Partner')))) OR (@Category=N'story' AND NOT(cat.CategoryName=N'Family' OR (cat.CategoryName=N'Romantic / Sexual' AND t.TypeName IN(N'Spouse',N'Partner',N'Ex-spouse',N'Former spouse',N'Romantic Partner'))))) + AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~'); + SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName; + SELECT COUNT(*) Total FROM #Groups; + SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0; + SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0; + SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder 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=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0; + ;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i) + SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName + FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID JOIN dbo.Characters a ON a.CharacterID=r.CharacterAID JOIN dbo.Characters b ON b.CharacterID=r.CharacterBID JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID LEFT JOIN dbo.RelationshipStates st ON st.RelationshipStateID=r.InitialRelationshipStateID + WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN CASE WHEN @OtherCharacterID IS NULL THEN 1 ELSE ((@DefinitionPage-1)*25)+1 END AND CASE WHEN @OtherCharacterID IS NULL THEN 3 ELSE @DefinitionPage*25 END + ORDER BY g.GroupNumber,x.DefinitionNumber; +END; +GO diff --git a/PlotLine/ViewModels/CharacterWorkspaceModels.cs b/PlotLine/ViewModels/CharacterWorkspaceModels.cs index f3a8a1c8..a3197033 100644 --- a/PlotLine/ViewModels/CharacterWorkspaceModels.cs +++ b/PlotLine/ViewModels/CharacterWorkspaceModels.cs @@ -8,7 +8,7 @@ public sealed class CharacterWorkspaceCounts } public sealed class CharacterWorkspaceQuery { - public string Tab{get;set;}="overview";public int Page{get;set;}=1;[StringLength(120)]public string? Search{get;set;}public int? BookID{get;set;}public string? Category{get;set;}public int? SceneID{get;set;}public int? RelationshipID{get;set;} + public string Tab{get;set;}="overview";public int Page{get;set;}=1;[StringLength(120)]public string? Search{get;set;}public int? BookID{get;set;}public string? Category{get;set;}public int? SceneID{get;set;}public int? RelationshipID{get;set;}public int? OtherCharacterID{get;set;}public int DefinitionPage{get;set;}=1; } public sealed class CharacterWorkspaceEntry { @@ -26,6 +26,7 @@ public sealed class CharacterRelationshipFrame public sealed class CharacterWorkspaceEvent {public RelationshipEvent Record{get;set;}=new();public bool ProtectedSource{get;set;}} public sealed class CharacterWorkspaceOperation { + public int? TypeID{get;set;}public bool ReverseDirection{get;set;}public bool? Reciprocal{get;set;}public bool? Permanent{get;set;}public bool? ReaderKnows{get;set;}public IReadOnlyList Types{get;set;}=[]; public int CharacterID{get;set;}public int RelationshipID{get;set;}public int? EventID{get;set;}public string Action{get;set;}="definition";[Required,StringLength(64)]public string Version{get;set;}="";[StringLength(4000)]public string? Notes{get;set;}public int? StateID{get;set;}[Range(1,10)]public int? Intensity{get;set;}public bool Awareness{get;set;}public bool Confirmed{get;set;} public CharacterRelationshipFrame Record{get;set;}=new();public CharacterWorkspaceEvent? Event{get;set;}public IReadOnlyList States{get;set;}=[]; } diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 5621d375..16099838 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -1170,6 +1170,7 @@ public sealed class CharacterArcViewModel public sealed class RelationshipEvolutionViewModel { + public int Page{get;set;}=1;public int Total=>Events.FirstOrDefault()?.TotalRecords??0;public int ReturnCharacterID{get;set;}public int? ReturnSceneID{get;set;}public bool CanEdit{get;set;} public Project Project { get; set; } = new(); public CharacterRelationship Relationship { get; set; } = new(); public IReadOnlyList Events { get; set; } = []; diff --git a/PlotLine/Views/Characters/Details.cshtml b/PlotLine/Views/Characters/Details.cshtml index 7b1007e6..6765d673 100644 --- a/PlotLine/Views/Characters/Details.cshtml +++ b/PlotLine/Views/Characters/Details.cshtml @@ -1,18 +1,12 @@ @model CharacterDetailViewModel -@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;} +@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;ViewData["CharacterRibbonModel"]=Model;}

@Model.Project.ProjectName · Character

@c.CharacterName

@CharacterWorkspace.Classification(c.CharacterImportance)@(analysis.Status??"Not analysed")@analysis.CurrentMessage
-
CharactersTimeline -@if(Model.WorkspaceCanEdit){Edit character} -
+
diff --git a/PlotLine/Views/Characters/_WorkspaceOperation.cshtml b/PlotLine/Views/Characters/_WorkspaceOperation.cshtml index 8b6faae0..4c3493b0 100644 --- a/PlotLine/Views/Characters/_WorkspaceOperation.cshtml +++ b/PlotLine/Views/Characters/_WorkspaceOperation.cshtml @@ -1,7 +1,7 @@ @model CharacterWorkspaceOperation @{var r=Model.Record.Relationship;var destructive=Model.Action is "archive" or "event-remove";var linked=Model.Action.StartsWith("event-")&&Model.Event?.ProtectedSource==true;}
-

@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship definition":"Edit one relationship event")

+

@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship":"Edit one relationship event")

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName · @r.RelationshipCategoryName

@@ -12,7 +12,16 @@ } @if(linked){

This event has manuscript evidence, review provenance or source dependencies. Direct modification/removal is blocked so that evidence is not orphaned. Use its source/review workflow.

Open source scene} else if(!destructive){ -

@(Model.Action=="definition"?"The pair, type, direction, book and narrative start/end remain unchanged. Use the full Relationships Editor for structural changes.":"This changes one recorded development at its original scene, not the definition or other events.")

+

@(Model.Action=="definition"?"Category is derived from the selected canonical type. Book, narrative start/end and initial/scene-established status remain unchanged. Structural changes with recorded history or across categories require the full Relationships Editor.":"This changes one recorded development at its original scene, not the definition or other events.")

+@if(Model.Action=="definition"){ + +

@Model.Record.EventCount recorded event(s) will be retained. Type/direction changes are available here only without events and within the existing category. Independent definitions are unchanged.

+ +

Family-category reciprocity changes require the full editor to review family semantics.

+ + +Full Relationships Editor for this pair +} @if(Model.Action!="definition"||r.IsInitialRelationship){} } diff --git a/PlotLine/Views/Characters/_WorkspaceTab.cshtml b/PlotLine/Views/Characters/_WorkspaceTab.cshtml index 337a7b9f..0538bae3 100644 --- a/PlotLine/Views/Characters/_WorkspaceTab.cshtml +++ b/PlotLine/Views/Characters/_WorkspaceTab.cshtml @@ -20,6 +20,7 @@ Model.Profile.Images=Model.Images; +@if(q.Tab=="relationships"){@if(q.OtherCharacterID.HasValue){}} @if(q.Tab!="relationships"){} @if(q.Tab=="evolution"){} @if(q.Tab=="knowledge"){} @@ -30,13 +31,22 @@ Model.Profile.Images=Model.Images;
Family: parent · biological · adoptive (dashed) · step (dotted) · partnership. Story: friendship (green), hostility (red), romance (purple), professional/social (blue).

Only recorded connections are shown. A relationship does not establish a first meeting, mutual trust or viewpoint knowledge.

-@foreach(var current in Model.Relationships){var r=current.Relationship;var other=r.CharacterAID==c.CharacterID?r.CharacterBID:r.CharacterAID;var name=r.CharacterAID==c.CharacterID?r.CharacterBName:r.CharacterAName; -

@name

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName @r.RelationshipCategoryName

@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&¤t.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){· Intensity @current.CurrentIntensity}

@current.CurrentNotes

@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Directional record")

-
-@if(Model.Profile.WorkspaceCanEdit){} -Advanced evolutionFull Relationships Editor
} +@foreach(var group in Model.Relationships.GroupBy(x=>x.Relationship.CharacterAID==c.CharacterID?x.Relationship.CharacterBID:x.Relationship.CharacterAID)){ +var first=group.First();var other=group.Key;var name=first.Relationship.CharacterAID==c.CharacterID?first.Relationship.CharacterBName:first.Relationship.CharacterAName;var count=first.Relationship.WorkspaceDefinitionCount; +
@name @if(count>1){@count definitions}@string.Join(" · ",group.Select(x=>x.Relationship.RelationshipTypeName).Distinct().Take(3))@string.Join(" · ",group.Select(x=>x.CurrentStateName).Distinct().Take(2)) +
Open @name +@foreach(var current in group){var r=current.Relationship; +

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName @r.RelationshipCategoryName

@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&¤t.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){· Intensity @current.CurrentIntensity}

@current.CurrentNotes

Definition #@r.CharacterRelationshipID · @(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Independent directional record")

+@if(r.StartSceneID.HasValue){Start scene #@r.StartSceneID}@if(r.EndSceneID.HasValue){End scene #@r.EndSceneID} +
@if(Model.Profile.WorkspaceCanEdit){} +History +@if(Model.Profile.WorkspaceCanEdit){}
} +@if(!q.OtherCharacterID.HasValue&&count>3){} +@if(q.OtherCharacterID.HasValue&&count>25){

Showing definitions @((q.DefinitionPage-1)*25+1)–@Math.Min(q.DefinitionPage*25,count) of @count.

@if(q.DefinitionPage>1){}@if(q.DefinitionPage*25More definitions for @name}
} +
} + @if(!Model.Relationships.Any()){

No matching relationship definitions recorded. Add an initial relationship or use the scene editor for a scene-based development.

} -
+

Select a definition to highlight its diagram connection. Full Relationships Editor

}else{ @if(!Model.Entries.Any()){

No matching records at this point. Change the filters or record information in its scene/source editor.

} @foreach(var group in Model.Entries.GroupBy(e=>new{e.BookID,e.BookDisplayTitle,e.ChapterNumber,e.SceneID,e.SceneTitle,e.SceneNumber})){ @@ -51,6 +61,6 @@ Model.Profile.Images=Model.Images;@Model.Total recorded results · page @q.Page of @totalPages@if(q.Page>1){}@if(q.PageNext} +
@Model.Total @(q.Tab=="relationships"?"character groups":"recorded results") · page @q.Page of @totalPages@if(q.Page>1){}@if(q.PageNext}
} diff --git a/PlotLine/Views/Dynamics/Relationship.cshtml b/PlotLine/Views/Dynamics/Relationship.cshtml index 65c3cdea..28a006b1 100644 --- a/PlotLine/Views/Dynamics/Relationship.cshtml +++ b/PlotLine/Views/Dynamics/Relationship.cshtml @@ -1,53 +1,22 @@ @model RelationshipEvolutionViewModel -@{ - ViewData["DesktopLayout"] = "details"; - ViewData["Title"] = "Relationship Evolution"; - var maxIndex = Math.Max(Model.Events.Any() ? Model.Events.Max(x => x.GlobalSceneIndex) : 1, 1); -} - -
-
-

Relationship Evolution

-

@Model.Relationship.CharacterAName -> @Model.Relationship.CharacterBName

-

@Model.Relationship.RelationshipTypeName

-
- Show on timeline +@{ViewData["DesktopLayout"]="details";ViewData["Title"]="Relationship Evolution";var r=Model.Relationship;var pages=Math.Max(1,(Model.Total+24)/25);var points=Model.Events.Where(e=>e.Intensity.HasValue&&e.EvidenceState=="Verified").ToArray();var min=Model.Events.Select(e=>e.GlobalSceneIndex).DefaultIfEmpty(0).Min();var max=Model.Events.Select(e=>e.GlobalSceneIndex).DefaultIfEmpty(1).Max();} +
+

Relationship Evolution · Definition #@r.CharacterRelationshipID

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName

@r.RelationshipTypeName · @(r.IsReciprocal?"One reciprocal definition":"Directional definition")

Return to character Relationships
+

@r.Notes

@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition"). Events below remain distinct from the underlying definition. @Model.Total recorded event(s).

+@if(Model.Events.Count>1&&points.Length>1){ +

Recorded intensity

Horizontal: canonical manuscript scene order (this page). Vertical: recorded intensity, 1–10. Each purple point is one verified event; missing values and intermediate states are not inferred. Select a point to inspect its event.

+ +@foreach(var level in new[]{1,5,10}){var y=170-(level-1)*16; @level} +@foreach(var e in points){var x=50+(e.GlobalSceneIndex-min)*710m/Math.Max(1,max-min);var y=170-(e.Intensity!.Value-1)*16;@e.BookDisplayTitle · Ch @e.ChapterNumber · Scene @e.SceneNumber · @e.RelationshipStateName · Intensity @e.Intensity} +First recorded scene on this pageLast recorded scene on this page +
+}else if(Model.Total==0){

No recorded events

This author definition has no scene-based developments. No timeline or intensity has been inferred. Use the scene editor to record a development.

} +else{

@(Model.Total==1?"One recorded event: its state and any recorded intensity are shown below.":"Recorded changes are shown chronologically below. This page has insufficient verified intensity values for a useful chart.")

} +@if(Model.Issues.Any()){}else{

No recorded continuity warnings for this definition.

} +

Recorded history

+@foreach(var e in Model.Events){

@e.BookDisplayTitle · Ch @e.ChapterNumber · Scene @e.SceneNumber: @e.SceneTitle

@e.RelationshipStateName · Intensity @(e.Intensity?.ToString()??"not recorded") · @(e.IsKnownToOtherCharacter?"Known to the other character":"Not recorded as known to the other character")

@e.Description

@e.EvidenceState @(e.SourceReviewKey!=null?"· Accepted review source":"") · Event #@e.RelationshipEventID

@if(e.EvidenceState!="Verified"){

Source evidence needs review; this is not an established relationship development.

} +
Open scene / source@if(Model.CanEdit){}
} +
@if(Model.Page>1){Previous events}Page @Model.Page of @pages · up to 25 events per page@if(Model.PageNext events}Show on timeline
- -
-
- @foreach (var item in Model.Events) - { - var left = (item.GlobalSceneIndex - 1) * 100m / maxIndex; - - - - } -
-
- - - -
-

Relationship History

-
- @foreach (var item in Model.Events) - { -
-
-

@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle

- @item.RelationshipStateName -
-
- Intensity @DisplayValue(item.Intensity) - @(item.IsKnownToOtherCharacter ? "Known to other character" : "Private/uncertain") -
-

@item.Description

-
- } -
-
- -@functions { - private static string DisplayValue(int? value) => value?.ToString() ?? "-"; -} +

+@section Scripts{} diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index b6a04a4a..d8e4ef62 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -128,6 +128,7 @@ @foreach (var category in ApplicationRibbon.Categories) {