diff --git a/PlotLine.Tests/Browser/writer-phase2.cjs b/PlotLine.Tests/Browser/writer-phase2.cjs new file mode 100644 index 00000000..5cb431e9 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-phase2.cjs @@ -0,0 +1,15 @@ +// Real Development acceptance. Requires a private disposable identity; never run against Production. +const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); +const w=JSON.parse(fs.readFileSync(process.env.PD_WRITER2_IDENTITY)),base='https://dev.plotdirector.com',before=process.env.PD_WRITER2_STAGE==='before',out=process.env.PD_WRITER2_SCREENSHOTS; +(async()=>{const browser=await chromium.launch();try{const context=await browser.newContext({viewport:{width:1440,height:1000}});await context.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID);const p=await context.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message)); +await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]); +const route=(d,b=w.book,project=w.project)=>`${base}/Writer/${d}?projectId=${project}${b?'&bookId='+b:''}`; +const shot=async n=>{if(!out)return;fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.waitForTimeout(200);await p.screenshot({path:out+'/'+n+'.png',animations:'disabled'});}; +for(const [label,book,project] of [['Populated',w.book,w.project],['Minimal',w.otherBook,w.project],['Structured',w.structuredBook,w.project],['No-book',null,w.emptyProject]])for(const d of ['Write','Explore','Plan','Review','Reflect']){const r=await p.goto(route(d,book,project));assert.equal(r.status(),200,label+d);if(!before&&book&&d==='Reflect')await p.locator('.writer-month-grid').waitFor();if(!before&&book&&d==='Explore')await p.locator('[data-investigation-opening] input[name=concern]').first().waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),label+d+' overflow');await shot(label+'-'+d);} +if(before){console.log('PASS baseline authenticated four-fixture captures');return;} +await p.goto(route('Write'));const exportSessions=async()=>await(await p.request.get(base+`/Writer/Work/Export?bookId=${w.book}`)).json();const sessionsBefore=await exportSessions();const form=p.locator('[data-focus-wizard]');if(!await form.isVisible())await p.locator('[data-change-focus]').click();await form.locator('[name=Activity]').selectOption('Revising');await form.locator('[data-focus-next]').click();await form.locator('[name=ChapterID]').selectOption(String(w.chapter));await form.locator('[name=SceneID]').selectOption(String(w.scene));await form.locator('[data-focus-next]').click();await form.locator('[name=Intention]').fill('Clarify the turning point');await form.locator('[data-focus-back]').click();assert.equal(await form.locator('[name=ChapterID]').inputValue(),String(w.chapter));await form.locator('[data-focus-next]').click();assert.equal(await form.locator('[name=Intention]').inputValue(),'Clarify the turning point');let saves=0;p.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/Writer/SaveObjective')saves++;});await form.evaluate(n=>{n.requestSubmit();n.requestSubmit();});await p.locator('[data-focus-summary]').filter({hasText:'Clarify the turning point'}).waitFor();assert.equal(saves,1);assert.deepEqual(await exportSessions(),sessionsBefore,'focus must not create sessions');await shot('Write-established');await p.goto(route('Plan'));assert((await p.locator('.writer3-main').textContent()).includes('Clarify the turning point'));await p.goto(route('Write'));assert((await p.locator('[data-focus-summary]').textContent()).includes('Clarify the turning point'));await p.locator('[data-change-focus]').click();await form.locator('[data-focus-next]').click();await form.locator('[name=ChapterID]').selectOption('');await form.locator('[data-focus-next]').click();await form.locator('[data-save-focus]').click();await p.locator('[data-focus-summary]').filter({hasText:'Across the book'}).waitFor();assert.deepEqual(await exportSessions(),sessionsBefore); +await p.goto(route('Explore'));await p.locator('[data-discovery-tiles] [data-tile]:visible').first().waitFor();const tile=p.locator('[data-discovery-tiles] [data-tile]:visible').first(),id=await tile.getAttribute('data-tile');await tile.locator('[data-dismiss]').click();assert(await p.locator(`[data-tile="${id}"]`).isHidden());await p.reload();assert(await p.locator(`[data-tile="${id}"]`).isHidden());await p.locator('[data-reconsider]').click();assert(await p.locator(`[data-tile="${id}"]`).isVisible());await p.locator(`[data-tile="${id}"] [data-defer]`).click();assert(await p.locator(`[data-tile="${id}"]`).isHidden());await p.locator('[data-reconsider]').click();await p.locator('[data-investigation-opening] input[name=concern]').first().check();await p.locator('[data-investigation-opening] button[type=submit]').click();await p.waitForURL(/Investigate\?bookId=.*id=/);assert(await p.locator('[data-investigation-answer]').isVisible());await p.goto(route('Explore'));await p.locator('[data-my-investigations] article').first().waitFor();const completed=p.locator('[data-my-investigations] article').filter({hasText:'Original results'}).first();await completed.getByRole('button',{name:'Continue',exact:true}).click();await p.locator('.investigation form[data-guidance-navigation]').first().locator('button').click();await p.locator('[data-investigation-companion] #guidance-finding').waitFor();assert.equal(context.pages().length,1);await p.locator('[data-guidance-pin]').click();await p.goto(route('Explore'));await p.locator('[data-discovery-active] form').first().waitFor();await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.explore'));await p.locator('.help-drawer-article').waitFor();await shot('Explore-both-panels'); +await p.goto(route('Review')+'&chapterId='+w.chapter);await p.locator('[data-review-intentions-slot] [data-review-intentions]').waitFor();assert(await p.locator('.reader-page').isVisible());const paragraph=p.locator('[data-paragraph-id][data-scene-id]').filter({hasText:'recorded first paragraph'}).first();await paragraph.click();await p.locator('[data-review-record]').click();await p.locator('[data-review-cancel]').click();await p.locator('[data-review-intentions-slot]').getByText('Disposable review scene',{exact:true}).waitFor();await shot('Review-context');await p.locator('#reader-focus').click();await p.locator('#reader-next').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('#reader-focus').click();await p.goto(route('Review')+'&reading=true&chapterId='+w.chapter);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-reading'),'true');await shot('Reading-mode'); +await p.goto(route('Reflect'));await p.locator('.writer-month-grid').waitFor();const month=await p.locator('.writer-section-heading h2').first().textContent();await p.getByRole('link',{name:'Previous month',exact:true}).click();assert(p.url().includes('/Writer/Reflect'));assert.notEqual(await p.locator('.writer-section-heading h2').first().textContent(),month);await p.locator('.writer-month-grid a').first().click();assert(p.url().includes('day='));await shot('Reflect-day'); +for(const width of [1920,1366,800])for(const d of ['Write','Explore','Plan','Review','Reflect']){await p.setViewportSize({width,height:1000});await p.goto(route(d));await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.layout'));await p.locator('.help-drawer-article').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),d+' '+width);await shot(d+'-'+width+'-panels');const collapse=p.locator('[data-ribbon-collapse]');await collapse.click();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(await p.locator('[data-guidance-collapse]').isVisible())await p.locator('[data-guidance-collapse]').click();await p.locator('[data-help-collapse]').count().then(async n=>{if(n)await p.locator('[data-help-collapse]').click();});await shot(d+'-'+width+'-collapsed');} +assert.deepEqual(errors,[]);console.log('PASS Phase 2 authenticated four fixtures, AJAX focus and no sessions, discovery preferences, canonical questionnaire, saved guidance, Review/Reading/Focus scene context, Reflect month/day, three widths and panel/ribbon states');await context.close();}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Sql/WriterPhase2Focus.sql b/PlotLine.Tests/Sql/WriterPhase2Focus.sql new file mode 100644 index 00000000..8764e386 --- /dev/null +++ b/PlotLine.Tests/Sql/WriterPhase2Focus.sql @@ -0,0 +1,45 @@ +-- Development only; isolated transactional fixtures roll back. +IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1; +GO +SET NOCOUNT ON; +SET XACT_ABORT OFF; +BEGIN TRANSACTION; +DECLARE @l int,@u int,@other int,@p int,@b int,@foreign int,@c int,@scene int; +INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@objective.invalid','Synthetic Objective','not-a-credential'); SET @u=SCOPE_IDENTITY(); +INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@objective.invalid','Other Objective','not-a-credential'); SET @other=SCOPE_IDENTITY(); +INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),'Objective fixture',10,100,100,100,100,0,0,0); SET @l=SCOPE_IDENTITY(); +INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@u,@l,1,1,'2030-01-01'); +INSERT dbo.Projects(ProjectName) VALUES('Synthetic objective'); SET @p=SCOPE_IDENTITY(); +INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@u,'Owner',1); +INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Objective book',1,1); SET @b=SCOPE_IDENTITY(); +INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Other book',2,2); SET @foreign=SCOPE_IDENTITY(); +INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Objective chapter',1,1,(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder)); SET @c=SCOPE_IDENTITY(); +INSERT dbo.Scenes(ChapterID,SceneTitle,SceneNumber,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@c,'Objective scene',1,1,(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder),(SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY SortOrder),(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY SortOrder)); SET @scene=SCOPE_IDENTITY(); +DECLARE @sessions bigint=(SELECT COUNT_BIG(*) FROM dbo.WriterWorkSessions); +EXEC dbo.WriterObjective @u,@b,'save',@c,@scene,'Revising',N'Clarify the turning point'; +IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE BookID=@b AND UserID=@u AND Intention=N'Clarify the turning point') THROW 51001,'Intention not retained',1; +IF (SELECT COUNT_BIG(*) FROM dbo.WriterWorkSessions)<>@sessions THROW 51001,'Focus created a session',1; +IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE BookID=@b AND UserID=@u AND ChapterID=@c AND SceneID=@scene AND Activity='Revising') THROW 51001,'Objective not persisted',1; +PRINT 'PASS objective book/chapter/scene and revision intention persist'; +EXEC dbo.WriterObjective @u,@b,'save',NULL,NULL,'Drafting'; +IF (SELECT COUNT(*) FROM dbo.WriterWorkingObjectives WHERE BookID=@b AND UserID=@u)<>1 THROW 51001,'Duplicate objective',1; +PRINT 'PASS revisiting updates one objective without requiring a chapter or plan'; +BEGIN TRY EXEC dbo.WriterObjective @other,@b,'save',NULL,NULL,'Drafting'; THROW 51001,'Foreign access accepted',1; END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW; END CATCH; +PRINT 'PASS unauthorised author refused'; +BEGIN TRY EXEC dbo.WriterObjective @u,@foreign,'save',@c,@scene,'Revising'; THROW 51001,'Foreign chapter accepted',1; END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW; END CATCH; +PRINT 'PASS cross-book chapter refused'; +BEGIN TRY EXEC dbo.WriterObjective @u,@b,'save',NULL,@scene,'Revising'; THROW 51001,'Unparented scene accepted',1; END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW; END CATCH; +PRINT 'PASS scene requires matching chapter'; +BEGIN TRY EXEC dbo.WriterObjective @u,@b,'save',NULL,NULL,'Invented'; THROW 51001,'Invalid activity accepted',1; END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW; END CATCH; +PRINT 'PASS unsupported activity refused'; +-- Read ignores a removed chapter so the author can select a replacement. +EXEC dbo.WriterObjective @u,@b,'save',@c,@scene,'Editing'; +UPDATE dbo.Chapters SET IsArchived=1 WHERE ChapterID=@c; +EXEC dbo.WriterObjective @u,@b,'read'; +PRINT 'PASS read tolerates archived working target'; +DELETE dbo.Scenes WHERE SceneID=@scene; +DELETE dbo.Chapters WHERE ChapterID=@c; +DELETE dbo.Books WHERE BookID=@b; +IF EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE BookID=@b) THROW 51001,'Book deletion blocked or orphaned',1; +PRINT 'PASS objective follows existing permanent book cleanup'; +ROLLBACK; diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index 5aebdc4b..a1d66597 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -36,7 +36,7 @@ public sealed class WriterController( } return result; } - public Task Reflect(int? projectId, int? bookId = null) => LoadDestination("Reflect", projectId, bookId); + public Task Reflect(int? projectId, int? bookId = null, int? year=null, int? month=null, DateTime? day=null) => LoadDestination("Reflect", projectId, bookId, journey:true, year:year, month:month, day:day); public Task Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId); public Task Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId); @@ -127,9 +127,21 @@ public sealed class WriterController( try { await objectives.Save(author, model); } catch (SqlException e) when (e.Number == 51000) { TempData["WriterWorkspaceError"] = "That chapter or scene is no longer available. Choose a place in this book."; return RedirectToAction(nameof(Write), new { bookId = model.BookID, setup = true }); } + if(Request.Headers["X-Requested-With"]=="XMLHttpRequest") { + var confirmed=(await objectives.Read(author,model.BookID)).Objective!; + return Json(new { saved=true, activity=confirmed.Activity, chapterID=confirmed.ChapterID, sceneID=confirmed.SceneID, title=confirmed.SceneTitle??confirmed.ChapterTitle??"Across the book", intention=confirmed.Intention, sessionKind=PlotLine.Services.Writer.WriterFocusActivities.SessionKind(confirmed.Activity), continueUrl=confirmed.SceneID.HasValue?Url.Action("Edit","Scenes",new{id=confirmed.SceneID}):confirmed.ChapterID.HasValue?Url.Action("Chapter",new{id=confirmed.ChapterID}):Url.Action("Details","Books",new{id=model.BookID}), inspectUrl=confirmed.ChapterID.HasValue?Url.Action("Inspect","WriterAuthoring",new{bookId=model.BookID,chapterId=confirmed.ChapterID,sceneId=confirmed.SceneID}):null }); + } return scheduleNow ? RedirectToAction(nameof(ScheduleSetup), new { bookId = model.BookID }) : RedirectToAction(nameof(Write), new { bookId = model.BookID }); } + [HttpGet, ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] + public async Task Focus(int bookId) + { + if(access==null||!await access.CanAccessEntityAsync("Book",bookId)||objectives==null)return NotFound(); + var saved=await objectives.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),bookId); + return PartialView("_WriterFocusForm",new WriterDashboardViewModel {BookID=bookId,Objective=saved.Objective,ObjectiveChoices=saved.Choices}); + } + public async Task Chapter(int id) { var model = await writerWorkspace.GetChapterWorkflowAsync(id); diff --git a/PlotLine/Controllers/WriterInvestigationsController.cs b/PlotLine/Controllers/WriterInvestigationsController.cs index 5792cc72..294e3c94 100644 --- a/PlotLine/Controllers/WriterInvestigationsController.cs +++ b/PlotLine/Controllers/WriterInvestigationsController.cs @@ -28,6 +28,11 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv ViewData["SavedConcernLabels"]=labels; return View(new InvestigationPage(row,c,state,saved,project,bookId)); }); + [HttpGet] + public Task Opening(int bookId)=>Guard(async()=>{ + var project=await service.Project(bookId);var c=await service.AuthorCatalogue()??throw new ArgumentException("The investigation catalogue is unavailable.");await EnsureCatalogue(c); + return PartialView("_Opening",new InvestigationPage(null,c,null,[],project,bookId)); + }); [HttpPost("/Writer/Explore/Investigate/Start"),ValidateAntiForgeryToken] public Task Start(int bookId,string concern,string? catalogueVersion=null)=>Guard(async()=>{if(catalogueVersion!=null&&!await IsAdmin())return NotFound();var c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is unavailable.");await EnsureCatalogue(c);var row=await service.Start(Author,bookId,concern,c.Version);return RedirectToAction(nameof(Index),new{bookId,id=row.ID});}); [HttpPost("/Writer/Explore/Investigate/Answer"),ValidateAntiForgeryToken] diff --git a/PlotLine/Data/WriterObjectiveRepository.cs b/PlotLine/Data/WriterObjectiveRepository.cs index 6c679a7d..6d07372f 100644 --- a/PlotLine/Data/WriterObjectiveRepository.cs +++ b/PlotLine/Data/WriterObjectiveRepository.cs @@ -13,6 +13,6 @@ public sealed class WriterObjectiveRepository(ISqlConnectionFactory factory) public async Task Save(int user, WriterObjective value) { using var db = factory.CreateConnection(); - await db.ExecuteAsync("dbo.WriterObjective", new { UserID = user, value.BookID, value.ChapterID, value.SceneID, value.Activity, Action = "save" }, commandType: CommandType.StoredProcedure); + await db.ExecuteAsync("dbo.WriterObjective", new { UserID = user, value.BookID, value.ChapterID, value.SceneID, value.Activity, value.Intention, Action = "save" }, commandType: CommandType.StoredProcedure); } } diff --git a/PlotLine/Models/WriterObjective.cs b/PlotLine/Models/WriterObjective.cs index 851458ff..ceb9f503 100644 --- a/PlotLine/Models/WriterObjective.cs +++ b/PlotLine/Models/WriterObjective.cs @@ -8,6 +8,8 @@ public sealed class WriterObjective public int? SceneID { get; set; } [Required, RegularExpression("^(Drafting|Revising|Editing|Researching|Proofreading)$")] public string Activity { get; set; } = "Drafting"; + [StringLength(2000)] + public string? Intention { get; set; } public string? ChapterTitle { get; set; } public string? SceneTitle { get; set; } } diff --git a/PlotLine/Sql/280_WriterFocusIntention.sql b/PlotLine/Sql/280_WriterFocusIntention.sql new file mode 100644 index 00000000..b4260751 --- /dev/null +++ b/PlotLine/Sql/280_WriterFocusIntention.sql @@ -0,0 +1,37 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF COL_LENGTH('dbo.WriterWorkingObjectives','Intention') IS NULL ALTER TABLE dbo.WriterWorkingObjectives ADD Intention nvarchar(2000) NULL; +GO +CREATE OR ALTER PROCEDURE dbo.WriterObjective + @UserID int, @BookID int, @Action varchar(10)='read', @ChapterID int=NULL, @SceneID int=NULL, @Activity nvarchar(20)=NULL, @Intention nvarchar(2000)=NULL +AS +BEGIN + SET NOCOUNT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID + WHERE b.BookID=@BookID AND b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) + THROW 51000,'Book access denied',1; + IF @Action='read' + BEGIN + SELECT o.BookID,o.Activity,o.Intention,o.ChapterID,o.SceneID,c.ChapterTitle,s.SceneTitle + FROM dbo.WriterWorkingObjectives o + LEFT JOIN dbo.Chapters c ON c.ChapterID=o.ChapterID AND c.BookID=@BookID AND c.IsArchived=0 + LEFT JOIN dbo.Scenes s ON s.SceneID=o.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0 + WHERE o.BookID=@BookID AND o.UserID=@UserID AND (o.ChapterID IS NULL OR c.ChapterID IS NOT NULL) AND (o.SceneID IS NULL OR s.SceneID IS NOT NULL); + SELECT c.ChapterID,c.ChapterTitle,s.SceneID,s.SceneTitle FROM dbo.Chapters c + LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 + WHERE c.BookID=@BookID AND c.IsArchived=0 ORDER BY c.SortOrder,c.ChapterID,s.SortOrder,s.SceneID; + RETURN; + END; + IF @Action<>'save' THROW 51000,'Unknown objective action',1; + IF @Activity IS NULL OR @Activity NOT IN(N'Drafting',N'Revising',N'Editing',N'Researching',N'Proofreading') THROW 51000,'Choose a working activity',1; + IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Chapter is unavailable in this book',1; + IF @SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene is unavailable in this chapter',1; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + IF EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID AND UserID=@UserID) + UPDATE dbo.WriterWorkingObjectives SET ChapterID=@ChapterID,SceneID=@SceneID,Activity=@Activity,Intention=@Intention,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID AND UserID=@UserID; + ELSE INSERT dbo.WriterWorkingObjectives(BookID,UserID,ChapterID,SceneID,Activity,Intention) VALUES(@BookID,@UserID,@ChapterID,@SceneID,@Activity,@Intention); + COMMIT; +END; +GO diff --git a/PlotLine/Views/Writer/Destination.cshtml b/PlotLine/Views/Writer/Destination.cshtml index 5c3a137a..fe5c7ef5 100644 --- a/PlotLine/Views/Writer/Destination.cshtml +++ b/PlotLine/Views/Writer/Destination.cshtml @@ -22,11 +22,12 @@ } @section Scripts { + @if(Model.Destination=="Review"){} - @if(Model.Destination == "Write"){ + @if(Model.Destination is "Write" or "Plan"){ diff --git a/PlotLine/Views/Writer/_JourneyCalendar.cshtml b/PlotLine/Views/Writer/_JourneyCalendar.cshtml index f1eb2ad0..b8356fb3 100644 --- a/PlotLine/Views/Writer/_JourneyCalendar.cshtml +++ b/PlotLine/Views/Writer/_JourneyCalendar.cshtml @@ -1,10 +1,10 @@ @model WriterDashboardViewModel @{var work=Model.Work??new PlotLine.Models.WriterWorkPage{BookID=Model.BookID??0};var first=new DateTime(work.Year,work.Month,1);var offset=((int)first.DayOfWeek+6)%7;var days=work.Days.ToDictionary(x=>x.Day.Date);var maximum=Math.Max(1,days.Values.Select(x=>x.Intensity).DefaultIfEmpty(1).Max());int Level(PlotLine.Models.WriterWorkDay? day)=>day==null||day.Intensity==0?0:Math.Clamp((int)Math.Ceiling(day.Intensity*4d/maximum),1,4);string Description(PlotLine.Models.WriterWorkDay? value)=>value==null?"No retained activity":$"{value.Changes} accepted changes; {value.Writing+value.Editing} writing/editing sessions; {value.Planning} planning sessions; {value.Reading} reading sessions; {value.EngagedSeconds} browser-engaged seconds; {value.PlaybackSeconds:0} observed audio seconds";var previous=first.AddMonths(-1);var next=first.AddMonths(1);}
-

@first.ToString("MMMM yyyy")

-

Green shows relative observed activity, including revision with zero net growth. Unavailable audio without playback evidence does not add listening activity. Neutral days mean no retained observation. Receipt dates use UTC; historical coverage is incomplete.

- -
@work.Year year overview
@for(var date=new DateTime(work.Year,1,1);date.Year==work.Year;date=date.AddDays(1)){days.TryGetValue(date,out var day);}
+

@first.ToString("MMMM yyyy")

+

Colour shows relative recorded activity, including revision. Select a date to explore it. A quiet day here does not establish that no writing took place.

What this calendar records

Accepted manuscript changes are observed automatically. Sessions are started explicitly by you; their elapsed time is separate from observed browser or audio activity. Earlier or imported writing may not have tracking history. Dates use UTC.

+ +
@work.Year year overview
@for(var date=new DateTime(work.Year,1,1);date.Year==work.Year;date=date.AddDays(1)){days.TryGetValue(date,out var day);}
@if(work.Day is {} selected){days.TryGetValue(selected.Date,out var observed);

@selected.ToString("d MMMM yyyy")

@if(observed==null){

No retained observation for this day. This does not establish that no work took place.

}else{

@observed.Changes accepted changes · +@observed.Added / −@observed.Removed words · @(observed.Added-observed.Removed) net.

@Math.Floor(observed.EngagedSeconds/60d) browser-engaged minutes · @Math.Floor(observed.PlaybackSeconds/60) observed playback minutes. These may overlap and are not added.

}Accepted-change evidence}

@(work.Day.HasValue?"Sessions on this day":"Recent sessions")

@foreach(var session in work.Sessions.Take(20)){
@session.Kind · @(session.ChapterTitle??(session.ChapterID.HasValue?"Chapter no longer available":"Whole book"))

@session.StartedUtc.ToString("d MMM HH:mm") UTC · @session.EngagedSeconds browser-engaged seconds · @Math.Round(session.PlaybackSeconds) observed playback seconds · @Math.Round(session.UniqueSeconds) unique audio seconds.

@if(session.EndedUtc.HasValue){@Math.Round((session.EndedUtc.Value-session.StartedUtc).TotalMinutes) minutes elapsed (not active time).}@if(session.ChangesDuringSession>0){

@session.ChangesDuringSession accepted changes during this interval · +@session.AdditionsDuringSession / −@session.RemovalsDuringSession words across the book · @session.ChangedParagraphs changed paragraph identities associated with this chapter. Overlap in time does not prove that playback caused edits.

}@if(session.StartRevision.HasValue){

Accepted checkpoint @session.StartRevision → @(session.EndRevision?.ToString()??"session open") · @session.StartParagraphCount → @(session.EndParagraphCount?.ToString()??"—") paragraphs (whole book).

}@if(session.Note!=null){

@session.Note

}
} diff --git a/PlotLine/Views/Writer/_ReviewContext.cshtml b/PlotLine/Views/Writer/_ReviewContext.cshtml index 97cc8a13..fd9857ce 100644 --- a/PlotLine/Views/Writer/_ReviewContext.cshtml +++ b/PlotLine/Views/Writer/_ReviewContext.cshtml @@ -1,7 +1,7 @@ @model PlotLine.Services.Writer.ReviewPanel @{var data=Model.Intentions;var goal=data.Sections.First(x=>x.Kind=="Goals");var scene=data.Sections.FirstOrDefault(x=>x.Kind=="Scene");string Compact(string value)=>value.Length>360?value[..360]+"…":value;} -
-

What did I want this to achieve?

@Model.ReferenceMessage

+

@Model.ReferenceMessage

+

Chapter and scene intentions

@if(scene!=null){

@data.Scene?.SceneTitle

@(string.IsNullOrWhiteSpace(scene.Value("ScenePurposeNotes"))?"No scene intention recorded.":Compact(scene.Value("ScenePurposeNotes")))

@Compact(scene.Value("SceneOutcomeNotes"))

Recorded scene state: @data.Scene?.RevisionStatusName

}

@(string.IsNullOrWhiteSpace(goal.Value("GoalSummary"))?"No chapter intention recorded. You can review without one.":Compact(goal.Value("GoalSummary")))

Chapter details, reminders & editing diff --git a/PlotLine/Views/Writer/_WriterExplore.cshtml b/PlotLine/Views/Writer/_WriterExplore.cshtml index f904210d..bb57bdb1 100644 --- a/PlotLine/Views/Writer/_WriterExplore.cshtml +++ b/PlotLine/Views/Writer/_WriterExplore.cshtml @@ -1,27 +1,23 @@ @inject PlotLine.Services.Investigations.InvestigationAccess InvestigationAccess @model WriterDashboardViewModel -
-
- @if(InvestigationAccess.Enabled && Model.BookID.HasValue){

What's troubling you about your story?

You don't need to know the answer yet. Work through a concern one question at a time.

Explore a concern

Explore your concern through questions and practical writing actions. Suggestions use your answers, not manuscript analysis.

} - @if(InvestigationAccess.Enabled&&Model.BookID.HasValue){

My Investigations

Continue a saved concern or revisit its original results.

Loading your saved investigations…

} -

Start with your question

What would you like to explore?

You do not need a finished outline or a linked manuscript. Choose a starting point.

- -

These open your authenticated writing and story tools. No manuscript analysis runs here.

-
- +
+
+

Discover what could help your story

Find a practical next step, or try a different way of looking at your work.

+ @if(Model.ProjectID.HasValue){ +
+ @foreach(var suggestion in Model.Suggestions.Where(x=>x.Key!="explore").Take(2)){ + } + +

Understand the people in your story

Record what matters about your characters, whether you are starting out or deepening a draft.

Develop your characters
+ +

Picture the space around a scene

A floor plan can help you think about rooms, positions and movement.

Explore floor plans
+

+ }else{

Choose a project to discover tools for its characters, settings and story.

Choose or create a project} +
+

Explore a concern

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

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

Loading starting concerns…

Open Guided Investigation
+

My Investigations

Continue a saved concern or revisit its original results.

Loading your saved investigations…

+ }else{

@(Model.BookID.HasValue?"Guided Investigation is not available in this environment. The story tools remain available.":"Select a book to keep your concerns and investigations with that book.")

} +
diff --git a/PlotLine/Views/Writer/_WriterFocusForm.cshtml b/PlotLine/Views/Writer/_WriterFocusForm.cshtml index bdf457fe..2fdc5e03 100644 --- a/PlotLine/Views/Writer/_WriterFocusForm.cshtml +++ b/PlotLine/Views/Writer/_WriterFocusForm.cshtml @@ -1,12 +1,15 @@ @model WriterDashboardViewModel -@{ var objective = Model.Objective; } -
- - - - -
@if(!Model.ActivityIsPrivate){}
+@{var objective=Model.Objective;} + + +

Step 1 of 3

+
What are you doing? + +

Choose your intended work. This does not start a recording.

+ + +

-

Saving does not start recording. Planning opens this book’s existing schedule setup; chapter and scene allocations are chosen there. Planning does not save this selection.

diff --git a/PlotLine/Views/Writer/_WriterPlan.cshtml b/PlotLine/Views/Writer/_WriterPlan.cshtml index 4dc7445d..7cf6cfb4 100644 --- a/PlotLine/Views/Writer/_WriterPlan.cshtml +++ b/PlotLine/Views/Writer/_WriterPlan.cshtml @@ -1,15 +1,15 @@ @model WriterDashboardViewModel -
-
-

Make room for your writing

Plan your next writing time

Use your existing chapters and scenes to choose activities and working budgets. Detailed scene estimates are optional.

- Create a writing plan -

Work ahead

-
- +
+
+

Next activities

Choose what deserves your attention next. Dates and schedules are optional.

+

Your next intended work

+ @if(Model.Objective is {} focus){

@focus.Activity · @(focus.SceneTitle??focus.ChapterTitle??"Across the book")

@if(!string.IsNullOrWhiteSpace(focus.Intention)){

@focus.Intention

}Continue this work} + else{

Start with one piece of work you would like to continue. It does not need a deadline.

} + @(Model.Objective==null?"Choose next work":"Change next work") +

This is your saved writing focus, not a completed task or a recorded session.

+ @if(Model.PlannedActivities.Count>0){

Scheduled writing activities

    @foreach(var item in Model.PlannedActivities.Take(12)){
  1. @item.Kind · @item.Title@item.Status · @item.Minutes planned minutes@if(item.SceneID.HasValue){Work on this scene}else{Work on this chapter}
  2. }
} + else{

Writing time ahead

} +
Schedule and completed work

@Model.WritingSchedule.CompletedTasks completed · @Model.WritingSchedule.SkippedTasks skipped · @Model.WritingSchedule.RemainingTasks outstanding scheduled tasks. These are recorded task states, not measured manuscript progress.

+
+
diff --git a/PlotLine/Views/Writer/_WriterReflect.cshtml b/PlotLine/Views/Writer/_WriterReflect.cshtml index 86147075..5048a5e1 100644 --- a/PlotLine/Views/Writer/_WriterReflect.cshtml +++ b/PlotLine/Views/Writer/_WriterReflect.cshtml @@ -1,9 +1,10 @@ @model WriterDashboardViewModel -
-

Your recorded progress

See what has changed

Open Writing Journey
- -
+
+ @if(Model.ActivityIsPrivate){

Recorded activity is private to the book owner. Your chapter and scene tools remain available.

} + else{ +

Your writing journey

Look back at recorded work, explore a day, or notice how your writing has changed over time.

+ @if(Model.Work?.Days.Any(x=>x.Intensity>0)!=true&&Model.Work?.Sessions.Count==0){

Your journey will grow as writing sessions and manuscript changes are recorded. Quiet days here do not mean you did no writing.

} + +
Recorded manuscript progress
+ } +
diff --git a/PlotLine/Views/Writer/_WriterReview.cshtml b/PlotLine/Views/Writer/_WriterReview.cshtml index 3f73cc78..b70fa6ce 100644 --- a/PlotLine/Views/Writer/_WriterReview.cshtml +++ b/PlotLine/Views/Writer/_WriterReview.cshtml @@ -2,6 +2,7 @@ @{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",Objective=reader?.Chapter==null?null:new(){ChapterID=reader.Chapter.ChapterID,ChapterTitle=reader.Chapter.ChapterTitle,Activity="Revising"}};}
+
Chapter intentions and verified scene context

Loading recorded intentions…

@if(reader!=null){} else{

Read the accepted manuscript

Select a book with chapters to review your accepted writing.

Open your book}
diff --git a/PlotLine/Views/Writer/_WriterWrite.cshtml b/PlotLine/Views/Writer/_WriterWrite.cshtml index 97bb3f33..b837398c 100644 --- a/PlotLine/Views/Writer/_WriterWrite.cshtml +++ b/PlotLine/Views/Writer/_WriterWrite.cshtml @@ -1,28 +1,31 @@ @model WriterDashboardViewModel @{var focus = Model.Objective; var editing = Context.Request.Query["setup"] == "true"; var kind = focus?.Activity is "Revising" or "Editing" or "Proofreading" ? "Editing" : focus?.Activity == "Researching" ? "Planning" : "Writing";}
-
+

Your current work

+
@if(focus != null && !editing){ -

@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")

@focus.Activity

@if(focus.ChapterID.HasValue){

Chapter: @focus.ChapterTitle

}

Write manuscript prose in Word; use the intentions and reminders below to guide your work.

+

@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")

@focus.Activity

@if(focus.ChapterID.HasValue){

Chapter: @focus.ChapterTitle

}@if(!string.IsNullOrWhiteSpace(focus.Intention)){

@focus.Intention

}

Keep your intention here; write manuscript prose in Word.

@if(focus.SceneID.HasValue){Open current scene } else if(focus.ChapterID.HasValue){Open current chapter } else{Open your chapters } - Change working focus
}else{

@(editing ? "Choose your working focus" : "Where would you like to begin?")

Choose an activity and, if you like, a chapter or scene. You can start without a writing plan.

-
+ } +
+ + @if(!Model.ActivityIsPrivate){ @if(focus != null && !editing){
}

Work sessions & Audio Review

Recording keeps your saved working focus. Audio Review is recorded for a chapter.

} else{

Work-session evidence is private to the book owner. Your chapter and scene tools remain available.

} - @if(focus?.ChapterID.HasValue==true && !editing){

Loading your recorded intentions…

} +

Loading your recorded intentions…