diff --git a/PlotLine.Tests/Browser/investigation-deletion.cjs b/PlotLine.Tests/Browser/investigation-deletion.cjs new file mode 100644 index 00000000..d37710f0 --- /dev/null +++ b/PlotLine.Tests/Browser/investigation-deletion.cjs @@ -0,0 +1,48 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +(async()=>{const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-icon-pwa-');const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}});const b=c.browser(),base='http://127.0.0.1:5238';try{ +await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}))); +await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); +let p;if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage(); +await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))})); +const url=base+'/Writer/Explore?projectId=7&bookId=12',root=p.locator('[data-explore-investigation]'),journey=p.locator('[data-explore-journey]'),layout=p.locator('[data-explore-layout]'); +p.setDefaultTimeout(20000);let navigations=0;p.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===p.mainFrame())navigations++;}); +const idle=()=>p.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy')); +const start=async()=>{await root.getByRole('tab',{name:'New investigation',exact:true}).click();await journey.locator('[name=concern]').first().check();await journey.getByRole('button',{name:'Begin',exact:true}).click();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));return new URL(p.url()).searchParams.get('investigation');}; +const token=()=>root.locator('[name=__RequestVerificationToken]').first().inputValue(); +const payload=async id=>({id,projectId:'7',bookId:'12',__RequestVerificationToken:await token()}); +const post=(data)=>p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:data}); +const landing=async()=>{await journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click());await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));}; +const selectSaved=async()=>{await root.getByRole('tab',{name:'Saved investigations',exact:true}).click();}; +let menuCaptured=false; +const openDelete=async id=>{const button=p.locator(`[data-explore-saved] [data-investigation-delete="${id}"]`);if(await button.locator('..').getAttribute('open')===null)await button.locator('..').locator('summary').click();if(!menuCaptured){for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-actions.png`});}menuCaptured=true;}await button.click();await p.getByRole('dialog',{name:'Delete this investigation?',exact:true}).waitFor();}; +const dialog=()=>p.getByRole('dialog',{name:'Delete this investigation?',exact:true}); +await p.goto(url);await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();const initialNav=navigations; +const active=await start(),stale=await journey.locator('[data-investigation-answer]').evaluate(f=>Object.fromEntries(new FormData(f))); +await journey.getByRole('button',{name:'Keep this investigation alongside my work',exact:true}).click();await p.waitForFunction(id=>window.PlotDirectorGuidanceSummary?.summary?.id===id,active); +const sibling=await c.newPage();await sibling.goto(url+'&investigation='+active);await sibling.locator('[data-inline-investigation]').waitFor();await p.bringToFront(); +stale.option=await journey.locator('[name=option]').first().inputValue();stale.operation='answer'; +const bounds=await layout.boundingBox(),handle=p.locator('[data-explore-divider]'),rect=await handle.boundingBox();await p.mouse.move(rect.x+rect.width/2,rect.y+80);await p.mouse.down();await p.mouse.move(bounds.x+(bounds.width-rect.width)*.4+rect.width/2,rect.y+80,{steps:10});await p.mouse.up(); +const pref=()=>p.evaluate(()=>JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.startsWith('plotdirector.writerExploreLayout.')))).leftRatio); +assert(Math.abs(await pref()-.4)<.005); +await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-confirmation.png`});for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-confirmation.png`});}await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200); +assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,bookId:'12',projectId:'7'}})).status(),400);assert.equal((await post({...await payload(active),projectId:'8'})).status(),404);assert.equal((await post({...await payload(active),bookId:'13'})).status(),404); +const other=await b.newContext();await other.addCookies([{name:'fixture-user',value:'5',url:base}]);const html=await(await other.request.get(base+'/fixture')).text(),otherToken=html.match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/)[1];assert.equal((await other.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,projectId:'7',bookId:'12',__RequestVerificationToken:otherToken}})).status(),404);await other.close(); +let fail=true;await c.route('**/Writer/Explore/Investigate/Delete',r=>fail?r.fulfill({status:503,json:{message:'Fixture failure'}}):r.continue()); +await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();await dialog().locator('[data-dialog-action=delete]').click();await dialog().locator('[data-dialog-error]:not([hidden])').waitFor();assert(await dialog().isVisible());assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200);fail=false; +await p.evaluate(()=>{window.deletionFrames=[];window.deletionSampling=true;function frame(){window.deletionFrames.push(Number(document.querySelector('[data-explore-layout]').style.getPropertyValue('--explore-ratio')));if(window.deletionSampling)requestAnimationFrame(frame);}requestAnimationFrame(frame);}); +await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));await p.evaluate(()=>window.deletionSampling=false); +assert((await p.evaluate(()=>window.deletionFrames)).filter(v=>v>.405&&v<.495).length>=4,'Discard visibly animates back to landing');assert.equal(await layout.getAttribute('data-explore-state'),'landing');assert(Math.abs(await pref()-.4)<.005);assert.equal(await p.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(new URL(p.url()).searchParams.has('investigation'),false);await p.waitForFunction(()=>window.PlotDirectorGuidanceSummary?.active===false);assert.equal(await p.locator('[data-discovery-active] [data-tile]').count(),0); +assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),404);assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Answer',{form:stale})).status(),404);assert.equal((await post(await payload(active))).status(),200); +await sibling.getByRole('button',{name:'Begin',exact:true}).waitFor();assert.equal(await sibling.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(await sibling.locator('[data-explore-layout]').getAttribute('data-explore-state'),'landing');await sibling.close(); +await c.unroute('**/Writer/Explore/Investigate/Delete'); +const unrelated=await start();await landing(); +for(const completed of [false,true]){ + const id=await start(); + if(completed){for(let n=0;n<20&&await journey.locator('[data-investigation-answer]').count();n++){await journey.locator('[name=option]').first().check();await journey.locator('button[value=answer]').click();await idle();}assert.equal(await journey.locator('[data-investigation-answer]').count(),0,'Completed investigation fixture');} + else{const area=journey.locator('textarea');if(await area.count())await area.fill('Disposable saved draft');await journey.locator('button[value=save]').click();await idle();} + await landing();await selectSaved();await openDelete(id);await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+id)).status(),200);await openDelete(id);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.waitForFunction(id=>!document.querySelector(`[data-explore-saved] [data-investigation-delete="${id}"]`),id);assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+unrelated)).status(),200); +} +await selectSaved();await openDelete(unrelated);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.locator('[data-explore-saved]').filter({hasText:'No saved investigations yet.'}).waitFor();assert.equal(navigations,initialNav,'No full document reload during delete/discard'); +for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}.png`});} +console.log('PASS '+(installed?'installed PWA':'browser')+' deletion/discard, cancel, error retention/retry, ownership/project/book, stale answer/resume, repeats, saved/completed/partial, empty/unrelated lists, session cleanup and animated landing with retained preference'); +}finally{await c.close();await b.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1}); diff --git a/PlotLine.Tests/InvestigationGuidanceTests.cs b/PlotLine.Tests/InvestigationGuidanceTests.cs index 215fa6ec..f845741b 100644 --- a/PlotLine.Tests/InvestigationGuidanceTests.cs +++ b/PlotLine.Tests/InvestigationGuidanceTests.cs @@ -29,6 +29,16 @@ internal static class InvestigationGuidanceTests r=(await store.Read(4,7,12,i.ID))!;await service.Save(4,r,s,"activate");Check((await store.Read(4,7,12))!.IsActive,"finished investigation can be reactivated"); var afterEvents=await repo.Replay(4,12,i.ID);var after=await repo.Read(4,12,i.ID); Check(before==JsonSerializer.Serialize(after,CatalogueValidator.Json)&&events.SequenceEqual(afterEvents),"canonical answers, diagnostic scores and event history unchanged"); + foreach(var state in new[]{"saved","partial","completed"}){ + var owned=new Investigation{ID=Guid.NewGuid(),UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id,CurrentQuestion=state=="completed"?null:c.Questions[0].Id,Accepted=state=="completed"}; + owned.Answers.Add(new(c.Questions[0].Id,c.Questions[0].Options[0].Id,"original"));await repo.Save(owned,0,state,evaluation);owned.Answers[0]=new(c.Questions[0].Id,c.Questions[0].Options.Last().Id,"revised");await repo.Save(owned,owned.Version,"revision",evaluation); + foreach(var scope in new[]{(5,7,12),(4,8,12),(4,7,13)}){try{await repo.Delete(scope.Item1,scope.Item2,scope.Item3,owned.ID);throw new Exception("foreign deletion accepted");}catch(UnauthorizedAccessException){}} + await repo.Delete(4,7,12,owned.ID);await repo.Delete(4,7,12,owned.ID); + Check(await repo.Read(4,12,owned.ID)==null&&(await repo.List(4,12)).All(x=>x.ID!=owned.ID)&&await store.Read(4,7,12,owned.ID)==null,"delete "+state+" removes saved, resume and guidance projections; repeats are safe"); + try{await repo.Save(owned,owned.Version,"stale answer",evaluation);throw new Exception("deleted update recreated record");}catch(KeyNotFoundException){} + try{await repo.Save(owned,0,"replayed Begin",evaluation);throw new Exception("deleted Begin recreated record");}catch(KeyNotFoundException){} + } + Check(await repo.Read(4,12,i.ID)!=null,"deletion preserves unrelated investigations and their accepted tool progress"); r.InvestigationJson=JsonSerializer.Serialize(new Investigation{ID=i.ID,UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id},CatalogueValidator.Json);r.EvaluationJson=null;Check(service.Summary(r,c).Findings.Count==0,"old records without snapshots remain readable without invented advice"); } } diff --git a/PlotLine.Tests/InvestigationMemoryRepository.cs b/PlotLine.Tests/InvestigationMemoryRepository.cs index 2d3a9922..a38b6546 100644 --- a/PlotLine.Tests/InvestigationMemoryRepository.cs +++ b/PlotLine.Tests/InvestigationMemoryRepository.cs @@ -7,11 +7,13 @@ internal sealed class InvestigationMemoryRepository:IInvestigationRepository { readonly Dictionary catalogues=[];readonly Dictionary rows=[];readonly Dictionary> events=[];readonly object sync=new();string current=""; public InvestigationMemoryRepository(){var json=File.ReadAllText(Environment.GetEnvironmentVariable("PD_INV_CATALOGUE")??"Docs/Writer/Investigations/synthetic-catalogue.json");var c=CatalogueValidator.Parse(json);catalogues[c.Version]=json;current=c.Version;} + readonly Dictionary deleted=[]; + public Task Delete(int user,int project,int book,Guid id){lock(sync){if(rows.TryGetValue(id,out var json)){var i=Parse(json);if(i.UserID!=user||i.BookID!=book||i.ProjectID!=project)throw new UnauthorizedAccessException();rows.Remove(id);events.Remove(id);deleted[id]=(user,project,book);}else if(!deleted.TryGetValue(id,out var scope)||scope!=(user,project,book))throw new KeyNotFoundException();}return Task.CompletedTask;} public Task Catalogue(string? version=null){lock(sync)return Task.FromResult(catalogues.TryGetValue(version??current,out var json)?CatalogueValidator.Parse(json):null);} public Task Publish(string json,string actor){lock(sync){var c=CatalogueValidator.Parse(json);if(catalogues.ContainsKey(c.Version))throw new ArgumentException("Version already exists.");catalogues[c.Version]=json;current=c.Version;}return Task.CompletedTask;} public Task> List(int user,int book){lock(sync)return Task.FromResult>(rows.Values.Select(Parse).Where(i=>i.UserID==user&&i.BookID==book).OrderByDescending(i=>i.UpdatedUtc).ToArray());} public Task Read(int user,int book,Guid id){lock(sync){var i=rows.TryGetValue(id,out var json)?Parse(json):null;return Task.FromResult(i?.UserID==user&&i.BookID==book?i:null);}} - public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;} + public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(deleted.ContainsKey(i.ID))throw new KeyNotFoundException();if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;} public Task Replay(int user,int book,Guid id){lock(sync){if(!rows.TryGetValue(id,out var json)||Parse(json).UserID!=user||Parse(json).BookID!=book)throw new UnauthorizedAccessException();return Task.FromResult(events[id].ToArray());}} static Investigation Parse(string json)=>JsonSerializer.Deserialize(json,CatalogueValidator.Json)!; } diff --git a/PlotLine.Tests/Sql/InvestigationDeletion.sql b/PlotLine.Tests/Sql/InvestigationDeletion.sql new file mode 100644 index 00000000..1d87c960 --- /dev/null +++ b/PlotLine.Tests/Sql/InvestigationDeletion.sql @@ -0,0 +1,51 @@ +-- Development only. All fixtures are fresh UUIDs and all data changes roll back. +SET NOCOUNT ON; +IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Wrong database',1; +DECLARE @user int,@book int,@project int,@catalogue varchar(80); +SELECT TOP(1) @user=a.UserID,@book=b.BookID,@project=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE a.IsActive=1 AND b.IsArchived=0 AND p.IsArchived=0 ORDER BY b.BookID; +SELECT TOP(1) @catalogue=Version FROM dbo.WriterInvestigationCatalogues; +IF @user IS NULL OR @catalogue IS NULL THROW 51000,'No authorised fixture scope',1; +DECLARE @phase int=0; +WHILE @phase<7 +BEGIN + DECLARE @id uniqueidentifier=NEWID(),@other uniqueidentifier=NEWID(),@json nvarchar(max),@otherJson nvarchar(max),@expected int,@story int; + SET @json=(SELECT @id ID,@user UserID,@project ProjectID,@book BookID,@catalogue CatalogueVersion,1 Version,'Disposable SQL deletion fixture' Concern,JSON_QUERY('[{"Question":"fixture","Option":"one"}]') Answers,JSON_QUERY('["fixture-recommendation"]') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); + SET @otherJson=JSON_MODIFY(@json,'$.ID',CONVERT(nvarchar(36),@other)); + BEGIN TRY + BEGIN TRANSACTION; + SELECT @story=CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM dbo.Chapters WITH(HOLDLOCK) WHERE BookID=@book; + EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@json,@Event=N'{"evaluation":{"Recommendations":["fixture"]}}'; + SET @json=JSON_MODIFY(JSON_MODIFY(@json,'$.Version',2),'$.Answers[0].Option','revised'); + EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=1,@Json=@json,@Event=N'{"operation":"revision","evaluation":{"Recommendations":["fixture"]}}'; + EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@other,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@otherJson,@Event=N'{}'; + INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json,IsActive) VALUES(@id,@user,@book,1,N'{"Progress":{"fixture":"Done"}}',0); + IF @phase IN(1,2,3) + BEGIN + DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongBook int=CASE WHEN @phase=2 THEN -1 ELSE @book END,@wrongProject int=CASE WHEN @phase=3 THEN -1 ELSE @project END; + EXEC dbo.WriterInvestigationDelete @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@ID=@id; + THROW 51999,'Scope violation accepted',1; + END; + EXEC dbo.WriterInvestigationDelete @UserID=@user,@ProjectID=@project,@BookID=@book,@ID=@id; + EXEC dbo.WriterInvestigationDelete @UserID=@user,@ProjectID=@project,@BookID=@book,@ID=@id; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@id) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id) THROW 51999,'Investigation orphan remains',1; + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@other AND Json=@otherJson) THROW 51999,'Unrelated investigation changed',1; + IF ISNULL(@story,0)<>ISNULL((SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM dbo.Chapters WHERE BookID=@book),0) THROW 51999,'Independent story changed',1; + IF @phase=4 BEGIN EXEC dbo.WriterInvestigation @Action='read',@UserID=@user,@BookID=@book,@ID=@id;THROW 51999,'Deleted resume accepted',1;END; + IF @phase IN(5,6) + BEGIN + SET @expected=CASE WHEN @phase=5 THEN 2 ELSE 0 END; + SET @json=JSON_MODIFY(@json,'$.Version',@expected+1); + EXEC dbo.WriterInvestigation @Action='save',@UserID=@user,@BookID=@book,@ProjectID=@project,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=@expected,@Json=@json,@Event=N'{}'; + THROW 51999,'Deleted answer or Begin recreated investigation',1; + END; + ROLLBACK; + END TRY + BEGIN CATCH + DECLARE @error int=ERROR_NUMBER(); + IF XACT_STATE()<>0 ROLLBACK; + IF @phase=0 OR @error<>51000 THROW; + END CATCH; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID IN(@id,@other)) OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@id) THROW 51999,'SQL fixture leaked',1; + PRINT CONCAT('PASS deletion SQL scope/rollback case ',@phase); + SET @phase+=1; +END; diff --git a/PlotLine/Controllers/WriterInvestigationsController.cs b/PlotLine/Controllers/WriterInvestigationsController.cs index 988b12b1..a588f874 100644 --- a/PlotLine/Controllers/WriterInvestigationsController.cs +++ b/PlotLine/Controllers/WriterInvestigationsController.cs @@ -13,7 +13,13 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv async Task IsAdmin()=> (await HttpContext.RequestServices.GetRequiredService().AuthorizeAsync(User,null,"AdminOnly")).Succeeded; async Task EnsureCatalogue(Catalogue c){if(c.Synthetic&&!await IsAdmin())throw new UnauthorizedAccessException();} int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); - async Task Guard(Func> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}} + async Task Guard(Func> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound("This investigation was deleted or is no longer available. Return to Explore to choose another investigation.");}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound("This investigation was deleted or is no longer available. Return to Explore to choose another investigation.");}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}} + [HttpPost("/Writer/Explore/Investigate/Delete"),ValidateAntiForgeryToken] + public Task Delete(int projectId,int bookId,Guid id)=>Guard(async()=>{ + if(id==Guid.Empty||await service.Project(bookId)!=projectId)return NotFound(); + await repository.Delete(Author,projectId,bookId,id); + return Json(new{deleted=true,id}); + }); [HttpGet("/Writer/Explore/Investigate")] public Task Index(int bookId,Guid? id,string? question=null,string? catalogueVersion=null)=>Guard(async()=>{ if(id.HasValue)ViewData["GuidanceVersion"]=(await guidance.Read(Author,null,bookId,id.Value))?.GuidanceVersion??0; diff --git a/PlotLine/Data/InvestigationRepository.cs b/PlotLine/Data/InvestigationRepository.cs index 548e11be..c509a41c 100644 --- a/PlotLine/Data/InvestigationRepository.cs +++ b/PlotLine/Data/InvestigationRepository.cs @@ -5,9 +5,10 @@ using PlotLine.Models.Investigations; using PlotLine.Services.Investigations; namespace PlotLine.Data; public interface IInvestigationRepository -{Task Catalogue(string? version=null);Task Publish(string json,string actor);Task> List(int user,int book);Task Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task Replay(int user,int book,Guid id);} +{Task Delete(int user,int project,int book,Guid id);Task Catalogue(string? version=null);Task Publish(string json,string actor);Task> List(int user,int book);Task Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task Replay(int user,int book,Guid id);} public sealed class InvestigationRepository(ISqlConnectionFactory factory):IInvestigationRepository { + public async Task Delete(int user,int project,int book,Guid id){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationDelete",new{UserID=user,ProjectID=project,BookID=book,ID=id},commandType:CommandType.StoredProcedure);} public async Task Catalogue(string? version=null){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync("dbo.WriterInvestigationCatalogue",new{Action="read",Version=version},commandType:CommandType.StoredProcedure);return json==null?null:CatalogueValidator.Parse(json);} public async Task Publish(string json,string actor){var c=CatalogueValidator.Parse(json);using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationCatalogue",new{Action="publish",c.Version,Json=json,Actor=actor},commandType:CommandType.StoredProcedure);} public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.WriterInvestigation",new{Action="list",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).Select(Parse).ToArray();} diff --git a/PlotLine/Sql/290_InvestigationDeletion.sql b/PlotLine/Sql/290_InvestigationDeletion.sql new file mode 100644 index 00000000..b11836e5 --- /dev/null +++ b/PlotLine/Sql/290_InvestigationDeletion.sql @@ -0,0 +1,106 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +-- Identity-only replay protection: no concern, answers, recommendations or story content. +IF OBJECT_ID('dbo.WriterInvestigationDeletions') IS NULL + CREATE TABLE dbo.WriterInvestigationDeletions(ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,ProjectID int NOT NULL); +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationDelete @UserID int,@ProjectID int,@BookID int,@ID uniqueidentifier AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0) THROW 51000,'Investigation unavailable',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry deletion.',1; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) BEGIN COMMIT;RETURN;END; + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) THROW 51000,'Investigation unavailable',1; + INSERT dbo.WriterInvestigationDeletions(ID,UserID,BookID,ProjectID) VALUES(@ID,@UserID,@BookID,@ProjectID); + DELETE FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@ID; + DELETE FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@ID; + DELETE FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID; + COMMIT; + END TRY + BEGIN CATCH + IF XACT_STATE()<>0 ROLLBACK; + THROW; + END CATCH; +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigation @Action varchar(12),@UserID int,@BookID int,@ProjectID int=NULL,@ID uniqueidentifier=NULL,@CatalogueVersion varchar(80)=NULL,@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL,@Event nvarchar(max)=NULL AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + DECLARE @ActualProject int; + SELECT @ActualProject=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0; + IF @ActualProject IS NULL OR (@ProjectID IS NOT NULL AND @ProjectID<>@ActualProject) THROW 51000,'Investigation scope unavailable',1; + IF @Action='list' BEGIN SELECT TOP(100) Json FROM dbo.WriterInvestigations WHERE UserID=@UserID AND BookID=@BookID ORDER BY UpdatedUtc DESC,ID;RETURN;END; + IF @Action IN('read','events') BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID) THROW 51000,'Investigation unavailable',1; + IF @Action='read' SELECT Json FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID; + ELSE SELECT e.Event FROM dbo.WriterInvestigationEvents e JOIN dbo.WriterInvestigations i ON i.ID=e.InvestigationID WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID ORDER BY e.Version; + RETURN; + END; + IF @Action<>'save' OR @ID IS NULL OR @ExpectedVersion<0 OR @ExpectedVersion>1000 OR ISJSON(@Json)<>1 OR ISJSON(@Event)<>1 OR DATALENGTH(@Json)>1000000 OR DATALENGTH(@Event)>2000000 THROW 51000,'Invalid investigation save',1; + IF ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.UserID')),-1)<>@UserID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.BookID')),-1)<>@BookID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.ProjectID')),-1)<>@ActualProject OR ISNULL(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Json,'$.ID')),'00000000-0000-0000-0000-000000000000')<>@ID OR ISNULL(JSON_VALUE(@Json,'$.CatalogueVersion'),'')<>@CatalogueVersion OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.Version')),-1)<>@ExpectedVersion+1 THROW 51000,'Investigation identity mismatch',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID) THROW 51000,'This investigation was deleted. Return to Explore.',1; + IF @ExpectedVersion=0 BEGIN + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) THROW 51002,'Investigation already exists; resume it',1; + INSERT dbo.WriterInvestigations(ID,UserID,ProjectID,BookID,CatalogueVersion,Version,Json) VALUES(@ID,@UserID,@ActualProject,@BookID,@CatalogueVersion,1,@Json); + END ELSE BEGIN + UPDATE dbo.WriterInvestigations SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND CatalogueVersion=@CatalogueVersion AND Version=@ExpectedVersion; + IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this investigation. Your submitted answer has not replaced it.',1; + END; + INSERT dbo.WriterInvestigationEvents(InvestigationID,Version,Event) VALUES(@ID,@ExpectedVersion+1,@Event); + COMMIT; + END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH; +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationGuidanceState + @Action varchar(12),@UserID int,@ProjectID int=NULL,@BookID int=NULL,@ID uniqueidentifier=NULL, + @ExpectedVersion int=NULL,@Json nvarchar(max)=NULL AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + IF @Action='read' BEGIN + SELECT TOP(1) i.ID,i.ProjectID,i.BookID,b.BookTitle, + JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(i.Json,'$.Answers',JSON_QUERY((SELECT a.Question,a.[Option] FROM OPENJSON(i.Json,'$.Answers') WITH(Question varchar(100),[Option] varchar(100)) a FOR JSON PATH))),'$.Presented',NULL),'$.Recommendations',NULL) InvestigationJson, + CASE WHEN e.Event IS NULL THEN NULL ELSE (SELECT JSON_VALUE(e.Event,'$.evaluation.Outcome') Outcome,JSON_QUERY(e.Event,'$.evaluation.Recommendations') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) END EvaluationJson,g.Json GuidanceJson,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished + FROM dbo.WriterInvestigations i + JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 + JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 + LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID AND g.BookID=i.BookID + OUTER APPLY(SELECT TOP(1) Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=i.ID AND Version=i.Version) e + WHERE i.UserID=@UserID AND (@BookID IS NULL OR i.BookID=@BookID) AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID) + AND ((@ID IS NOT NULL AND i.ID=@ID) OR (@ID IS NULL AND g.IsActive=1)) + AND (@ID IS NOT NULL OR @ProjectID IS NOT NULL OR @BookID IS NOT NULL) + ORDER BY g.UpdatedUtc DESC,i.ID; + RETURN; + END; + IF @Action NOT IN('activate','save','dismiss','finish') OR @ID IS NULL OR @BookID IS NULL OR @ExpectedVersion IS NULL OR ISJSON(@Json)<>1 OR DATALENGTH(@Json)>65536 THROW 51000,'Invalid guidance request',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1; + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations i JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)) THROW 51000,'Guidance unavailable',1; + DECLARE @actual int; + SELECT @actual=Version FROM dbo.WriterInvestigationGuidance WITH(UPDLOCK,HOLDLOCK) WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID; + IF ISNULL(@actual,0)<>@ExpectedVersion THROW 51002,'Guidance changed in another window. Refresh before trying again.',1; + IF @Action='activate' UPDATE dbo.WriterInvestigationGuidance SET IsActive=0 WHERE UserID=@UserID AND BookID=@BookID AND IsActive=1 AND InvestigationID<>@ID; + IF @actual IS NULL BEGIN + IF @Action<>'activate' THROW 51000,'Activate this investigation first',1; + INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json) VALUES(@ID,@UserID,@BookID,1,@Json); + END ELSE UPDATE dbo.WriterInvestigationGuidance SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME(), + IsActive=CASE WHEN @Action='activate' THEN 1 WHEN @Action IN('dismiss','finish') THEN 0 ELSE IsActive END, + Finished=CASE WHEN @Action='activate' THEN 0 WHEN @Action='finish' THEN 1 ELSE Finished END + WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID; + COMMIT; + END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH; +END; +GO diff --git a/PlotLine/Sql/291_InvestigationDeletionIdentityLock.sql b/PlotLine/Sql/291_InvestigationDeletionIdentityLock.sql new file mode 100644 index 00000000..16648763 --- /dev/null +++ b/PlotLine/Sql/291_InvestigationDeletionIdentityLock.sql @@ -0,0 +1,112 @@ +-- Serialize UUID reuse across authorised books as well as writes within a book. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationDelete @UserID int,@ProjectID int,@BookID int,@ID uniqueidentifier AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0) THROW 51000,'Investigation unavailable',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry deletion.',1; + DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID); + EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) BEGIN COMMIT;RETURN;END; + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID) THROW 51000,'Investigation unavailable',1; + INSERT dbo.WriterInvestigationDeletions(ID,UserID,BookID,ProjectID) VALUES(@ID,@UserID,@BookID,@ProjectID); + DELETE FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@ID; + DELETE FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@ID; + DELETE FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ProjectID=@ProjectID; + COMMIT; + END TRY + BEGIN CATCH + IF XACT_STATE()<>0 ROLLBACK; + THROW; + END CATCH; +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigation @Action varchar(12),@UserID int,@BookID int,@ProjectID int=NULL,@ID uniqueidentifier=NULL,@CatalogueVersion varchar(80)=NULL,@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL,@Event nvarchar(max)=NULL AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + DECLARE @ActualProject int; + SELECT @ActualProject=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0; + IF @ActualProject IS NULL OR (@ProjectID IS NOT NULL AND @ProjectID<>@ActualProject) THROW 51000,'Investigation scope unavailable',1; + IF @Action='list' BEGIN SELECT TOP(100) Json FROM dbo.WriterInvestigations WHERE UserID=@UserID AND BookID=@BookID ORDER BY UpdatedUtc DESC,ID;RETURN;END; + IF @Action IN('read','events') BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID) THROW 51000,'Investigation unavailable',1; + IF @Action='read' SELECT Json FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID; + ELSE SELECT e.Event FROM dbo.WriterInvestigationEvents e JOIN dbo.WriterInvestigations i ON i.ID=e.InvestigationID WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID ORDER BY e.Version; + RETURN; + END; + IF @Action<>'save' OR @ID IS NULL OR @ExpectedVersion<0 OR @ExpectedVersion>1000 OR ISJSON(@Json)<>1 OR ISJSON(@Event)<>1 OR DATALENGTH(@Json)>1000000 OR DATALENGTH(@Event)>2000000 THROW 51000,'Invalid investigation save',1; + IF ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.UserID')),-1)<>@UserID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.BookID')),-1)<>@BookID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.ProjectID')),-1)<>@ActualProject OR ISNULL(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Json,'$.ID')),'00000000-0000-0000-0000-000000000000')<>@ID OR ISNULL(JSON_VALUE(@Json,'$.CatalogueVersion'),'')<>@CatalogueVersion OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.Version')),-1)<>@ExpectedVersion+1 THROW 51000,'Investigation identity mismatch',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1; + DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID); + EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1; + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationDeletions WHERE ID=@ID) THROW 51000,'This investigation was deleted. Return to Explore.',1; + IF @ExpectedVersion=0 BEGIN + IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) THROW 51002,'Investigation already exists; resume it',1; + INSERT dbo.WriterInvestigations(ID,UserID,ProjectID,BookID,CatalogueVersion,Version,Json) VALUES(@ID,@UserID,@ActualProject,@BookID,@CatalogueVersion,1,@Json); + END ELSE BEGIN + UPDATE dbo.WriterInvestigations SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND CatalogueVersion=@CatalogueVersion AND Version=@ExpectedVersion; + IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this investigation. Your submitted answer has not replaced it.',1; + END; + INSERT dbo.WriterInvestigationEvents(InvestigationID,Version,Event) VALUES(@ID,@ExpectedVersion+1,@Event); + COMMIT; + END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH; +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationGuidanceState + @Action varchar(12),@UserID int,@ProjectID int=NULL,@BookID int=NULL,@ID uniqueidentifier=NULL, + @ExpectedVersion int=NULL,@Json nvarchar(max)=NULL AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + IF @Action='read' BEGIN + SELECT TOP(1) i.ID,i.ProjectID,i.BookID,b.BookTitle, + JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(i.Json,'$.Answers',JSON_QUERY((SELECT a.Question,a.[Option] FROM OPENJSON(i.Json,'$.Answers') WITH(Question varchar(100),[Option] varchar(100)) a FOR JSON PATH))),'$.Presented',NULL),'$.Recommendations',NULL) InvestigationJson, + CASE WHEN e.Event IS NULL THEN NULL ELSE (SELECT JSON_VALUE(e.Event,'$.evaluation.Outcome') Outcome,JSON_QUERY(e.Event,'$.evaluation.Recommendations') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) END EvaluationJson,g.Json GuidanceJson,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished + FROM dbo.WriterInvestigations i + JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 + JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 + LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID AND g.BookID=i.BookID + OUTER APPLY(SELECT TOP(1) Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=i.ID AND Version=i.Version) e + WHERE i.UserID=@UserID AND (@BookID IS NULL OR i.BookID=@BookID) AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID) + AND ((@ID IS NOT NULL AND i.ID=@ID) OR (@ID IS NULL AND g.IsActive=1)) + AND (@ID IS NOT NULL OR @ProjectID IS NOT NULL OR @BookID IS NOT NULL) + ORDER BY g.UpdatedUtc DESC,i.ID; + RETURN; + END; + IF @Action NOT IN('activate','save','dismiss','finish') OR @ID IS NULL OR @BookID IS NULL OR @ExpectedVersion IS NULL OR ISJSON(@Json)<>1 OR DATALENGTH(@Json)>65536 THROW 51000,'Invalid guidance request',1; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @lock int,@resource nvarchar(255)=N'WriterInvestigationBook:'+CONVERT(nvarchar(20),@BookID); + EXEC @lock=sys.sp_getapplock @Resource=@resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation is busy. Retry.',1; + DECLARE @identityResource nvarchar(255)=N'WriterInvestigation:'+CONVERT(nvarchar(36),@ID); + EXEC @lock=sys.sp_getapplock @Resource=@identityResource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @lock<0 THROW 51002,'Investigation identity is busy. Retry.',1; + IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations i JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)) THROW 51000,'Guidance unavailable',1; + DECLARE @actual int; + SELECT @actual=Version FROM dbo.WriterInvestigationGuidance WITH(UPDLOCK,HOLDLOCK) WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID; + IF ISNULL(@actual,0)<>@ExpectedVersion THROW 51002,'Guidance changed in another window. Refresh before trying again.',1; + IF @Action='activate' UPDATE dbo.WriterInvestigationGuidance SET IsActive=0 WHERE UserID=@UserID AND BookID=@BookID AND IsActive=1 AND InvestigationID<>@ID; + IF @actual IS NULL BEGIN + IF @Action<>'activate' THROW 51000,'Activate this investigation first',1; + INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json) VALUES(@ID,@UserID,@BookID,1,@Json); + END ELSE UPDATE dbo.WriterInvestigationGuidance SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME(), + IsActive=CASE WHEN @Action='activate' THEN 1 WHEN @Action IN('dismiss','finish') THEN 0 ELSE IsActive END, + Finished=CASE WHEN @Action='activate' THEN 0 WHEN @Action='finish' THEN 1 ELSE Finished END + WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID; + COMMIT; + END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH; +END; +GO diff --git a/PlotLine/Views/Writer/_WriterExplore.cshtml b/PlotLine/Views/Writer/_WriterExplore.cshtml index 4fe87b09..f494f2ca 100644 --- a/PlotLine/Views/Writer/_WriterExplore.cshtml +++ b/PlotLine/Views/Writer/_WriterExplore.cshtml @@ -17,7 +17,8 @@

Explore a concern

You do not need to know the answer yet. Start with what is troubling you.

@if(InvestigationAccess.Enabled&&Model.BookID.HasValue){ -
+
+ @Html.AntiForgeryToken()

Loading starting concerns…

diff --git a/PlotLine/Views/WriterInvestigations/_Journey.cshtml b/PlotLine/Views/WriterInvestigations/_Journey.cshtml index be4d7936..9d538244 100644 --- a/PlotLine/Views/WriterInvestigations/_Journey.cshtml +++ b/PlotLine/Views/WriterInvestigations/_Journey.cshtml @@ -63,7 +63,7 @@
} @if(row!=null){
} -

Return to Explore · Start another investigation

+

Return to Explore · Start another investigation @if(row!=null){}