diff --git a/PlotLine.Tests/Browser/writer-onboarding-live.cjs b/PlotLine.Tests/Browser/writer-onboarding-live.cjs new file mode 100644 index 00000000..7ae662c0 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-onboarding-live.cjs @@ -0,0 +1,69 @@ +// Explicit Development acceptance only. Requires a disposable author and owned fixture. +// Credentials remain in a private file and are never logged. +const {chromium}=require('playwright'); +const fs=require('node:fs'); +const assert=require('node:assert/strict'); +(async()=>{ + const identityPath=process.env.PD_WRITER_IDENTITY,scopePath=process.env.PD_WRITER_SCOPE,output=process.env.PD_WRITER_SCREENSHOTS; + assert(identityPath?.startsWith('/tmp/pd-dev-browser-writer2-')&&scopePath&&output,'Dedicated fixture files required'); + const who=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)); + assert(who.Database==='PlotDirector_Development'&&/^pwa-browser-.*@example\.invalid$/.test(who.Email)); + for(const key of ['project','book','chapter','scene','other'])assert(Number.isSafeInteger(scope[key])&&scope[key]>0); + const base='https://dev.plotdirector.com',writer=`${base}/Writer?projectId=${scope.project}&bookId=${scope.book}`; + const browser=await chromium.launch(); + try{for(const pwa of [false,true]){ + const context=await browser.newContext({viewport:{width:1440,height:1000}}); + if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); + const page=await context.newPage(); + await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password); + await Promise.all([page.waitForURL('**/Projects'),page.locator('button[type=submit]').click()]); + await page.goto(writer); + if(!pwa){ + assert.equal(await page.getByRole('heading',{name:'Start Here',exact:true}).isVisible(),true); + await page.screenshot({path:output+'/Overview-Initial.png',fullPage:true}); + await page.getByRole('link',{name:/Explore your manuscript/}).click();await page.waitForURL(`**/Books/Details/${scope.book}#chapters`); + assert.equal(await page.locator('#chapters').isVisible(),true);assert.equal(await page.getByRole('link',{name:'The crossing',exact:true}).count(),1); + await page.getByRole('link',{name:'The crossing',exact:true}).click(); + await page.waitForURL(`**/Chapters/Details/${scope.chapter}`);assert((await page.locator('body').textContent()).includes('Arrival')); + await page.goto(writer);await page.getByRole('link',{name:/Continue an existing manuscript/}).click(); + await page.locator('[name=Activity]').selectOption('Revising');await page.locator('[data-objective-chapter]').selectOption(String(scope.chapter));await page.locator('[data-objective-scene]').selectOption(String(scope.scene)); + await Promise.all([page.waitForURL(`**/Writer?bookId=${scope.book}`),page.getByRole('button',{name:'Save objective · start without a schedule'}).click()]); + } + assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true); + assert((await page.locator('.writer-current').textContent()).includes('Revising')); + if(!pwa)await page.screenshot({path:output+'/Overview-Objective.png',fullPage:true}); + await page.getByRole('link',{name:'Continue Writing',exact:true}).click();await page.waitForURL(`**/Scenes/Edit/${scope.scene}`); + assert((await page.locator('body').textContent()).includes('Arrival')); + await page.goto(writer);await page.getByRole('link',{name:'Open Chapters',exact:true}).click();await page.waitForURL(`**/Books/Details/${scope.book}#chapters`);assert.equal(await page.locator('#chapters').isVisible(),true); + await page.goto(writer);await page.getByRole('link',{name:'Create a writing plan',exact:true}).click();await page.waitForURL('**/Writer/ScheduleSetup?*'); + assert.equal(await page.locator('[name=BookID]').inputValue(),String(scope.book));assert.equal(await page.locator('[name=ProjectID]').inputValue(),String(scope.project)); + assert((await page.locator('[name=BookID]').textContent()).includes('All Books')); + await page.getByRole('link',{name:'Skip scheduling · return to Writer'}).click();assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true); + if(!pwa){ + for(const allBooks of [false,true]){ + await page.goto(`${base}/Writer/ScheduleSetup?projectId=${scope.project}&bookId=${scope.book}`); + await page.locator('[name=PlanName]').fill(allBooks?'Synthetic project-wide plan':'Synthetic book plan'); + if(allBooks)await page.locator('[name=BookID]').selectOption(''); + await Promise.all([page.waitForURL('**/Writer/SchedulePreview?writingPlanId=*'),page.getByRole('button',{name:'Create Plan and Generate Schedule'}).click()]); + await page.getByRole('link',{name:'Edit Plan',exact:true}).click();await page.waitForURL('**/Writer/EditWritingPlan?writingPlanId=*'); + assert((await page.locator('body').textContent()).includes(allBooks?'All Books':'Writer verification book')); + await page.locator('[name=PlanName]').fill(allBooks?'Updated project-wide plan':'Updated book plan'); + await Promise.all([page.waitForURL('**/Writer/WritingPlans?*'),page.getByRole('button',{name:'Save Plan',exact:true}).click()]); + assert((await page.locator('body').textContent()).includes(allBooks?'Updated project-wide plan':'Updated book plan')); + } + await page.goto(`${base}/Writer/WritingPlans?projectId=${scope.project}&bookId=${scope.book}`); + assert((await page.locator('body').textContent()).includes('Updated project-wide plan')); + assert((await page.locator('body').textContent()).includes('Updated book plan')); + } + for(const title of ['Writing Journey','Writing Plan','Workspaces','Reports']){ + await page.goto(writer);const link=page.locator('#ribbon-panel-writer a').filter({hasText:new RegExp('^'+title+'$')}); + assert.equal(await link.count(),1);await link.click();await page.waitForLoadState();assert.equal(await page.locator('h1').count(),1);assert(!(await page.locator('body').textContent()).includes('An error occurred')); + assert(new URL(page.url()).searchParams.get('bookId')===String(scope.book),`${title} retains book`); + } + await page.goto(`${base}/Writer?projectId=${scope.project}&bookId=${scope.other}`);assert.equal(await page.getByRole('heading',{name:'Start Here',exact:true}).isVisible(),true); + await page.goto(writer);assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true); + await page.getByRole('link',{name:'Change objective'}).click();assert.equal(await page.locator('[name=Activity]').inputValue(),'Revising');assert.equal(await page.locator('[data-objective-scene]').inputValue(),String(scope.scene)); + console.log(`PASS live Writer author journey: ${pwa?'simulated PWA':'browser'}; real chapter/scene destinations, saved objective, optional scheduling, ribbon and book isolation`); + await context.close(); + }}finally{await browser.close();} +})().catch(error=>{console.error(error.message);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/writer-workspace.cjs b/PlotLine.Tests/Browser/writer-workspace.cjs index 912706b8..eaae86b6 100644 --- a/PlotLine.Tests/Browser/writer-workspace.cjs +++ b/PlotLine.Tests/Browser/writer-workspace.cjs @@ -12,7 +12,7 @@ const base='http://127.0.0.1:5238'; let negotiations=0; await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue()); await page.goto(base+'/fixture?page=writer&layout=full'); - await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Unavailable'); + await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Status unavailable'); assert.equal(negotiations,1,'No tight retry loop after initial network failure'); await page.locator('#display-setup > summary').click(); assert.equal(await page.locator('[data-start-writing-workspace]').isVisible(),false,'A disconnected book has no linked-Word controls'); diff --git a/PlotLine.Tests/Browser/writer2-dashboard.cjs b/PlotLine.Tests/Browser/writer2-dashboard.cjs index 730023e9..eb44bf47 100644 --- a/PlotLine.Tests/Browser/writer2-dashboard.cjs +++ b/PlotLine.Tests/Browser/writer2-dashboard.cjs @@ -10,6 +10,15 @@ const fs=require('node:fs'); await page.setViewportSize({width,height:1000});await page.addInitScript(theme=>localStorage.setItem('plotdirector.applicationTheme',theme),theme); await page.goto(`http://127.0.0.1:5238/writer2-fixture?populated=${populated}`); assert.equal(await page.locator('h1').textContent(),'A Distant Shore'); + assert.equal(await page.getByRole('heading',{name:'Start Here',exact:true}).isVisible(),true); + assert.equal(await page.locator('.writer-start-paths a').count(),3); + assert((await page.getByRole('link',{name:/Explore your manuscript/}).getAttribute('href')).includes('/Books/Details/12#chapters')); + await page.getByRole('link',{name:/Continue an existing manuscript/}).click(); + await page.locator('[data-objective-chapter]').selectOption('21'); + await page.locator('[data-objective-scene]').selectOption('31'); + assert.equal(await page.locator('[data-objective-scene] option[value="32"]').evaluate(option=>option.disabled),true); + await page.locator('[data-objective-chapter]').selectOption('22'); + assert.equal(await page.locator('[data-objective-scene]').inputValue(),''); assert.equal(await page.locator('.pd-ribbon-navigation').filter({hasText:/^Writer$/}).count(),1); assert.equal(await page.locator('#ribbon-panel-writer').isVisible(),true); assert.equal(await page.locator('.writer-tabs a').count(),5); @@ -17,14 +26,23 @@ const fs=require('node:fs'); const choices=await page.locator('[data-app-book-choice]').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('href')));assert(choices.length>0);assert(choices.every(href=>new URL(href,'http://127.0.0.1:5238').pathname==='/Writer'),'Common book selection stays in Writer'); assert.equal(await page.locator('[data-start-writing-workspace]').isVisible(),false,'No linked document exposes no workspace reapply action'); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${theme} ${width} overflow`); + await page.locator('.writer-queue-details > summary').click(); assert.equal(await page.locator('[data-writer-queue="WriteNext"]').isVisible(),true); assert.equal(await page.locator('[data-writer-queue="Revision"]').isVisible(),false); - if(populated){assert.equal(await page.locator('.writer-day').count(),28);assert.equal(await page.locator('.writer-day-observed').count(),2);assert.equal(await page.locator('.writer-indicators strong').nth(0).textContent(),'120');assert((await page.locator('.writer-day-observed').first().getAttribute('href')).includes('day='));} - else{assert((await page.locator('.writer-empty').textContent()).includes('Earlier writing'));assert.equal(await page.locator('.writer-indicators strong').first().textContent(),'—');} + if(populated){assert.equal(await page.locator('.writer-day').count(),28);assert.equal(await page.locator('.writer-day-observed').count(),2);assert((await page.locator('.writer-activity-graphic').textContent()).includes('+120'));assert((await page.locator('.writer-day-observed').first().getAttribute('href')).includes('day='));} + else{assert((await page.locator('.writer-progress .writer-empty').textContent()).includes('Earlier writing'));assert.equal(await page.locator('.writer-activity-graphic').count(),0);} await page.getByRole('link',{name:'Connection & Display Setup'}).click();await page.waitForFunction(()=>document.getElementById('display-setup').open);assert.equal(await page.locator('#display-setup').getAttribute('open'),''); - if(theme==='warm-light'&&width===1440&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-sprint/writer2-desktop.png',fullPage:true}); - if(theme==='warm-light'&&width===390&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-sprint/writer2-small.png',fullPage:true}); + if(theme==='warm-light'&&width===1440&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-correction/overview-initial.png',fullPage:true}); + if(theme==='warm-light'&&width===390&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-correction/overview-small.png',fullPage:true}); } + await page.goto('http://127.0.0.1:5238/writer2-fixture?objective=true'); + assert.equal(await page.getByRole('heading',{name:'Continue Writing',exact:true}).isVisible(),true); + assert((await page.getByRole('link',{name:'Continue Writing',exact:true}).getAttribute('href')).includes('/Scenes/Edit/31')); + for(const state of [{connected:true,linked:false,text:'Connected · no linked manuscript open'},{connected:true,linked:true,text:'Connected · linked manuscript open'},{connected:false,linked:false,text:'Disconnected'}]){ + await page.evaluate(state=>{const leases=state.linked?[{bookId:12,wordAvailable:true}]:[];leases.connectionState=state.connected?'Connected':'Disconnected';window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));},state); + assert.equal(await page.locator('[data-writing-workspace-word]').textContent(),state.text); + } + if(!pwa)await page.screenshot({path:'/home/nick/writer2-correction/overview-objective.png',fullPage:true}); assert.deepEqual(errors,[]);await context.close(); } console.log('PASS Writer 2 overview: real Razor, 48 theme/viewport/history/PWA combinations, single navigation, book scope, honest empty states, chart links and contextual controls.'); diff --git a/PlotLine.Tests/Sql/WriterWorkingObjective.sql b/PlotLine.Tests/Sql/WriterWorkingObjective.sql new file mode 100644 index 00000000..a762a8ff --- /dev/null +++ b/PlotLine.Tests/Sql/WriterWorkingObjective.sql @@ -0,0 +1,42 @@ +-- Run only on the explicitly provisioned disposable correction copy. Fixtures roll back. +USE [PlotDirector_WriterCorrection_20261115]; +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(); +EXEC dbo.WriterObjective @u,@b,'save',@c,@scene,'Revising'; +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.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index c99d7ead..72a7721a 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -171,6 +171,9 @@ internal static class ToolbarBrowserHost app.UseWritingSolverReviewBoundary(); app.MapGet("/writer2-fixture",async (HttpContext context)=>{ var model=WriterFixture(); + model.Book = new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore",ChapterCount=3,SceneCount=7,CurrentWordCount=12400}; + model.ObjectiveChoices=[new(){ChapterID=21,ChapterTitle="The crossing",SceneID=31,SceneTitle="Arrival"},new(){ChapterID=22,ChapterTitle="The harbour",SceneID=32,SceneTitle="Departure"}]; + if(context.Request.Query["objective"]=="true") model.Objective=new(){BookID=12,ChapterID=21,SceneID=31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"}; if(context.Request.Query["populated"]=="true") { var now=DateTime.UtcNow; diff --git a/PlotLine.Tests/WriterDashboardTests.cs b/PlotLine.Tests/WriterDashboardTests.cs index 02a0e30b..67cbd618 100644 --- a/PlotLine.Tests/WriterDashboardTests.cs +++ b/PlotLine.Tests/WriterDashboardTests.cs @@ -12,7 +12,7 @@ internal static class WriterDashboardTests void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Writer dashboard "+message);} int? scheduledBook=null;var allowed=true; var workspace=Proxy((method,args)=>method=="GetDashboardAsync"?Task.FromResult(new WriterDashboardViewModel{ProjectID=1,WriteNext=[new(){BookID=2,SceneID=20},new(){BookID=3,SceneID=30}]}):throw new Exception(method)); - var schedule=Proxy((method,args)=>{if(method!="GetTodayDashboardAsync")throw new Exception(method);scheduledBook=(int?)args![1];return Task.FromResult(new WritingScheduleDashboardViewModel{TodayTasks=[new(){BookID=2,SceneID=20},new(){BookID=3,SceneID=30}]});}); + var schedule=Proxy((method,args)=>{if(method=="GetScheduleSetupAsync")return Task.FromResult(new WritingScheduleSetupViewModel{ProjectID=(int?)args![0]});if(method=="PopulateScheduleSetupOptionsAsync")return Task.CompletedTask;if(method!="GetTodayDashboardAsync")throw new Exception(method);scheduledBook=(int?)args![1];return Task.FromResult(new WritingScheduleDashboardViewModel{TodayTasks=[new(){BookID=2,SceneID=20},new(){BookID=3,SceneID=30}]});}); var books=Proxy((method,args)=>method switch{"ListByProjectAsync"=>Task.FromResult>([new(){BookID=2,ProjectID=1},new(){BookID=3,ProjectID=1}]),"GetAsync"=>Task.FromResult(new(){BookID=(int)args![0]!,ProjectID=1}),_=>throw new Exception(method)}); var access=Proxy((method,args)=>Task.FromResult(allowed)); var controller=new WriterController(workspace,schedule,books,access); @@ -20,6 +20,9 @@ internal static class WriterDashboardTests Check(model.BookID==3&&model.WriteNext.Single().SceneID==30&&model.WritingSchedule.TodayTasks.Single().SceneID==30,"book selection filters queues and tasks consistently"); Check(scheduledBook==3&&model.Workspace=="Revision","book scope reaches schedule service before selection and active workspace persists"); Check(await controller.Index(1,999) is NotFoundResult,"unknown book cannot fall back to another book"); + var setup = (ViewResult)await controller.ScheduleSetup(1, 3); + Check(((WritingScheduleSetupViewModel)setup.Model!).BookID == 3, "plan setup retains selected book instead of All Books"); + Check(await controller.ScheduleSetup(99, 3) is NotFoundResult, "plan setup refuses conflicting project and book"); allowed=false;Check(await controller.Index(null,3) is NotFoundResult,"book-only deep link checks access before metadata"); Check(controller.LegacyWrite(1,3) is RedirectToActionResult redirect&&(int?)redirect.RouteValues!["bookId"]==3,"legacy Write redirect preserves book scope"); var ribbon=ApplicationRibbon.Categories.Single(c=>c.Key=="writer");Check(ribbon.Groups.SelectMany(g=>g.Commands).Any(c=>c.Action=="Workspaces")&&ribbon.Groups.SelectMany(g=>g.Commands).Any(c=>c.Controller=="WritingActivity"),"Writer contextual commands target implemented workspaces and evidence"); diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index 422fd065..a7aa514f 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -12,7 +12,7 @@ namespace PlotLine.Controllers; public sealed class WriterController( IWriterWorkspaceService writerWorkspace, IWritingScheduleService writingSchedule, - IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null) : Controller + IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null) : Controller { public async Task Index(int? projectId,int? bookId=null,string? workspace=null,bool journey=false) { @@ -43,6 +43,12 @@ public sealed class WriterController( { try{model.Activity=await activity.Read(user,model.BookID.Value);}catch(SqlException e)when(e.Number==51000){ model.ActivityIsPrivate=true; } } if(activity!=null&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var reader))model.StoryHealthReminders=await activity.Reminders(reader,model.BookID.Value); } + if (objectives != null && model.BookID.HasValue && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var author)) + { + var working = await objectives.Read(author, model.BookID.Value); + model.Objective = working.Objective; + model.ObjectiveChoices = working.Choices; + } model.Workspace=workspace is "InProgress" or "Revision" or "FinalPass" or "StoryHealth"?workspace:"WriteNext"; model.Journey=journey; model.WritingSchedule = await writingSchedule.GetTodayDashboardAsync(projectId,model.BookID); @@ -56,6 +62,18 @@ public sealed class WriterController( [HttpGet("Write"),HttpGet("Write/Index")] public IActionResult LegacyWrite(int? projectId,int? bookId)=>RedirectToAction(nameof(Index),new{projectId,bookId}); + [HttpPost, ValidateAntiForgeryToken] + public async Task SaveObjective(PlotLine.Models.WriterObjective model, bool scheduleNow = false) + { + if (access == null || !await access.CanAccessEntityAsync("Book", model.BookID)) return NotFound(); + if (!ModelState.IsValid || objectives == null || !int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var author)) + { TempData["WriterWorkspaceError"] = "Choose a working activity and a place in this book."; return RedirectToAction(nameof(Index), new { bookId = model.BookID, setup = true }); } + 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(Index), new { bookId = model.BookID, setup = true }); } + return scheduleNow ? RedirectToAction(nameof(ScheduleSetup), new { bookId = model.BookID }) : RedirectToAction(nameof(Index), new { bookId = model.BookID }); + } + public async Task Chapter(int id) { var model = await writerWorkspace.GetChapterWorkflowAsync(id); @@ -68,9 +86,19 @@ public sealed class WriterController( return View(model); } - public async Task WritingPlans() + public async Task WritingPlans(int? projectId = null, int? bookId = null) { + PlotLine.Models.Book? selected = null; + if (bookId.HasValue && bookRepository != null) + { + if (access != null && !await access.CanAccessEntityAsync("Book", bookId.Value)) return NotFound(); + selected = await bookRepository.GetAsync(bookId.Value); + if (selected == null || selected.IsArchived || (projectId.HasValue && projectId != selected.ProjectID)) return NotFound(); + projectId = selected.ProjectID; + } var model = await writingSchedule.GetWritingPlansForManagementAsync(); + model.ProjectID = projectId; model.BookID = bookId; model.BookTitle = selected?.BookDisplayTitle; + model.Plans = model.Plans.Where(p => (!projectId.HasValue || p.ProjectID == projectId) && (!bookId.HasValue || p.BookID == null || p.BookID == bookId)).ToArray(); return View(model); } @@ -112,7 +140,8 @@ public sealed class WriterController( { await writingSchedule.UpdateWritingPlanSettingsAsync(model); TempData["WritingPlansMessage"] = "Writing plan updated."; - return RedirectToAction(nameof(WritingPlans)); + var saved = await writingSchedule.GetWritingPlanSettingsAsync(model.WritingPlanID); + return RedirectToAction(nameof(WritingPlans), new { projectId = saved.ProjectID, bookId = saved.BookID }); } catch (InvalidOperationException ex) { @@ -138,9 +167,18 @@ public sealed class WriterController( return View(nameof(SchedulePreview), model); } - public async Task ScheduleSetup(int? projectId) + public async Task ScheduleSetup(int? projectId, int? bookId = null) { + if (bookId.HasValue && bookRepository != null) + { + if (access != null && !await access.CanAccessEntityAsync("Book", bookId.Value)) return NotFound(); + var book = await bookRepository.GetAsync(bookId.Value); + if (book == null || book.IsArchived || (projectId.HasValue && projectId != book.ProjectID)) return NotFound(); + projectId = book.ProjectID; + } var model = await writingSchedule.GetScheduleSetupAsync(projectId); + model.BookID = bookId; + await writingSchedule.PopulateScheduleSetupOptionsAsync(model); return View(model); } @@ -312,24 +350,24 @@ public sealed class WriterController( [HttpPost] [ValidateAntiForgeryToken] - public async Task MarkScheduleItemComplete(int writingScheduleItemId, int? projectId) + public async Task MarkScheduleItemComplete(int writingScheduleItemId, int? projectId, int? bookId = null) { var updated = await writingSchedule.MarkScheduleItemCompleteAsync(writingScheduleItemId); TempData[updated ? "WriterWorkspaceMessage" : "WriterWorkspaceError"] = updated ? "Writing task marked complete." : "Only planned writing tasks can be marked complete."; - return RedirectToAction(nameof(Index), new { projectId }); + return RedirectToAction(nameof(Index), new { projectId, bookId }); } [HttpPost] [ValidateAntiForgeryToken] - public async Task SkipScheduleItem(int writingScheduleItemId, int? projectId) + public async Task SkipScheduleItem(int writingScheduleItemId, int? projectId, int? bookId = null) { var updated = await writingSchedule.SkipScheduleItemAsync(writingScheduleItemId); TempData[updated ? "WriterWorkspaceMessage" : "WriterWorkspaceError"] = updated ? "Writing task skipped." : "Only planned writing tasks can be skipped."; - return RedirectToAction(nameof(Index), new { projectId }); + return RedirectToAction(nameof(Index), new { projectId, bookId }); } [HttpPost] @@ -347,6 +385,7 @@ public sealed class WriterController( try { var existing = await writingSchedule.GetWritingPlanSettingsAsync(model.WritingPlanID); + model.ProjectID = existing.ProjectID; model.BookID = existing.BookID; model.ProjectName = existing.ProjectName; model.BookName = existing.BookName; model.GoalType = existing.GoalType; diff --git a/PlotLine/Data/WriterObjectiveRepository.cs b/PlotLine/Data/WriterObjectiveRepository.cs new file mode 100644 index 00000000..6c679a7d --- /dev/null +++ b/PlotLine/Data/WriterObjectiveRepository.cs @@ -0,0 +1,18 @@ +using System.Data; +using Dapper; +using PlotLine.Models; +namespace PlotLine.Data; +public sealed class WriterObjectiveRepository(ISqlConnectionFactory factory) +{ + public async Task<(WriterObjective? Objective, IReadOnlyList Choices)> Read(int user, int book) + { + using var db = factory.CreateConnection(); + using var rows = await db.QueryMultipleAsync("dbo.WriterObjective", new { UserID = user, BookID = book, Action = "read" }, commandType: CommandType.StoredProcedure); + return (await rows.ReadSingleOrDefaultAsync(), (await rows.ReadAsync()).ToArray()); + } + 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); + } +} diff --git a/PlotLine/Models/WriterObjective.cs b/PlotLine/Models/WriterObjective.cs new file mode 100644 index 00000000..851458ff --- /dev/null +++ b/PlotLine/Models/WriterObjective.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations; +namespace PlotLine.Models; + +public sealed class WriterObjective +{ + public int BookID { get; set; } + public int? ChapterID { get; set; } + public int? SceneID { get; set; } + [Required, RegularExpression("^(Drafting|Revising|Editing|Researching|Proofreading)$")] + public string Activity { get; set; } = "Drafting"; + public string? ChapterTitle { get; set; } + public string? SceneTitle { get; set; } +} +public sealed class WriterObjectiveChoice +{ + public int ChapterID { get; set; } + public string ChapterTitle { get; set; } = ""; + public int? SceneID { get; set; } + public string? SceneTitle { get; set; } +} diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 303cd5ad..0484afc0 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -199,6 +199,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/ApplicationNavigation.cs b/PlotLine/Services/ApplicationNavigation.cs index f6584146..264f0dbf 100644 --- a/PlotLine/Services/ApplicationNavigation.cs +++ b/PlotLine/Services/ApplicationNavigation.cs @@ -28,8 +28,9 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo var project = Project ?? Property(model, "Project") as Project ?? model as Project; var book = Property(model, "Book") as Book ?? (model as StoryPointViewModel)?.Snapshot?.Book; + var writingPlan = (model as WritingSchedulePreviewViewModel)?.SelectedPlan; var projectId = project?.ProjectID ?? PositiveId(Property(model, "ProjectID")) - ?? book?.ProjectID ?? PositiveId(request.Query["projectId"].FirstOrDefault()); + ?? book?.ProjectID ?? writingPlan?.ProjectID ?? PositiveId(request.Query["projectId"].FirstOrDefault()); if (projectId is not > 0) return result; // Resolve through the user-scoped repository even on models that only carry IDs. @@ -43,7 +44,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo TimelineViewModel timeline => timeline.SelectedBookID, StoryCalendarViewModel calendar => calendar.SelectedBookID, NamesLibraryViewModel names => names.Filter.BookID, - _ => book?.BookID ?? PositiveId(Property(model, "SelectedBookID")) + _ => book?.BookID ?? writingPlan?.BookID ?? PositiveId(Property(model, "SelectedBookID")) ?? PositiveId(Property(model, "BookID")) ?? PositiveId(Property(Property(model, "Filter"), "BookID")) ?? PositiveId(request.Query["bookId"].FirstOrDefault()) diff --git a/PlotLine/Services/ApplicationRibbon.cs b/PlotLine/Services/ApplicationRibbon.cs index f88931e6..c393fdd8 100644 --- a/PlotLine/Services/ApplicationRibbon.cs +++ b/PlotLine/Services/ApplicationRibbon.cs @@ -33,7 +33,7 @@ public static class ApplicationRibbon new("Selected book", new("Book overview", "bible", "Books", "Details", "book"), new("Edit book", "writer", "Books", "Edit", "book"), new("Add chapter", "threads", "Chapters", "Create", "chapter")), new("Manuscript review", S("review")), new("Library", S("overview"), new("Add book", "bible", "Books", "Create"))), new("writer", "Writer", - new("Writing", new("Overview","writer","Writer","Index","writerBook"),new("Writing Journey","calendar","Writer","Journey","writerBook"),new("Writing Plan","calendar","Writer","WritingPlans")), + new("Writing", new("Overview","writer","Writer","Index","writerBook"),new("Writing Journey","calendar","Writer","Journey","writerBook"),new("Writing Plan","calendar","Writer","WritingPlans","writerBook")), new("Work",new("Workspaces","threads","Writer","Workspaces","writerBook"),new("Reports","metrics","WritingActivity","Index","writerBook",OwnerOnly:true)), new("Workspace setup",new RibbonCommand("Display Setup","maps","Writer","DisplaySetup","writerBook"))), new("story", "Story", new("Story structure", S("timeline"), S("plotlines"), S("threads"), S("calendar"), S("point")), new("Analysis & planning", S("review"), S("scenarios"), S("continuity"))), diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 0cf443ec..bd6e563b 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -6475,6 +6475,7 @@ public sealed class WritingScheduleService( var model = new WritingPlanSettingsEditViewModel { WritingPlanID = plan.WritingPlanID, + ProjectID = plan.ProjectID, BookID = plan.BookID, PlanName = plan.PlanName, ProjectName = project?.ProjectName ?? string.Empty, BookName = book?.BookDisplayTitle ?? "All Books", diff --git a/PlotLine/Sql/261_WriterWorkingObjective.sql b/PlotLine/Sql/261_WriterWorkingObjective.sql new file mode 100644 index 00000000..6656e27b --- /dev/null +++ b/PlotLine/Sql/261_WriterWorkingObjective.sql @@ -0,0 +1,49 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID(N'dbo.WriterWorkingObjectives',N'U') IS NULL +BEGIN + CREATE TABLE dbo.WriterWorkingObjectives + ( + BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE, + UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE, + ChapterID int NULL, + SceneID int NULL, + Activity nvarchar(20) NOT NULL CHECK(Activity IN(N'Drafting',N'Revising',N'Editing',N'Researching',N'Proofreading')), + UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), + CONSTRAINT PK_WriterWorkingObjectives PRIMARY KEY(BookID,UserID) + ); +END; +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 +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.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,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID AND UserID=@UserID; + ELSE INSERT dbo.WriterWorkingObjectives(BookID,UserID,ChapterID,SceneID,Activity) VALUES(@BookID,@UserID,@ChapterID,@SceneID,@Activity); + COMMIT; +END; +GO diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index dd0e4e17..4def1b22 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -925,6 +925,8 @@ public sealed class ChapterWorkflowViewModel public sealed class WriterDashboardViewModel { + public WriterObjective? Objective { get; set; } + public IReadOnlyList ObjectiveChoices { get; set; } = []; public int? BookID { get; set; } public Book? Book { get; set; } public PlotLine.Models.WritingActivityPage? Activity { get; set; } @@ -978,6 +980,9 @@ public sealed class WritingPlanViewModel public sealed class WritingPlansManagementViewModel { + public int? ProjectID { get; set; } + public int? BookID { get; set; } + public string? BookTitle { get; set; } public IReadOnlyList Plans { get; set; } = []; } @@ -990,6 +995,8 @@ public sealed class WritingDayAvailabilityViewModel public sealed class WritingPlanSettingsEditViewModel { + public int ProjectID { get; set; } + public int? BookID { get; set; } public int WritingPlanID { get; set; } [Required, StringLength(200)] diff --git a/PlotLine/Views/Books/Details.cshtml b/PlotLine/Views/Books/Details.cshtml index 43e9ce2e..ae721d09 100644 --- a/PlotLine/Views/Books/Details.cshtml +++ b/PlotLine/Views/Books/Details.cshtml @@ -177,7 +177,7 @@
-

Chapters

+

Chapters

Read manuscript @if (!Model.Chapters.Any()) { diff --git a/PlotLine/Views/Writer/EditWritingPlan.cshtml b/PlotLine/Views/Writer/EditWritingPlan.cshtml index fe6ae8a1..206f0a49 100644 --- a/PlotLine/Views/Writer/EditWritingPlan.cshtml +++ b/PlotLine/Views/Writer/EditWritingPlan.cshtml @@ -5,8 +5,8 @@ } @@ -112,7 +112,7 @@
- Cancel + Cancel
diff --git a/PlotLine/Views/Writer/Index.cshtml b/PlotLine/Views/Writer/Index.cshtml index 7a71a8e7..9bb74e8b 100644 --- a/PlotLine/Views/Writer/Index.cshtml +++ b/PlotLine/Views/Writer/Index.cshtml @@ -6,9 +6,10 @@ var seed=Model.WriteNext.Concat(Model.ContinueWriting).Concat(Model.RevisionQueue).Concat(Model.PolishingQueue).FirstOrDefault(); var bookId=Model.BookID??seed?.BookID; var bookTitle=Model.Book?.BookDisplayTitle??seed?.BookDisplayTitle??"Choose a book"; - var next=Model.ContinueWriting.FirstOrDefault()??Model.WriteNext.FirstOrDefault()??Model.RevisionQueue.FirstOrDefault()??Model.PolishingQueue.FirstOrDefault(); + if(string.IsNullOrWhiteSpace(bookTitle)) bookTitle = Model.BookID.HasValue ? "Untitled book" : "Choose a book"; var opportunity=Model.WritingSchedule.TodayTasks.FirstOrDefault()??Model.WritingSchedule.UpcomingTasks.FirstOrDefault(); var totals=Model.Activity?.Totals.HasAcceptedEvidence==true?Model.Activity.Totals:null; + var showWorkspace = Context.Request.RouteValues["action"]?.ToString() == "Workspaces"; var queues=new[]{("WriteNext","Write Next",Model.WriteNext),("InProgress","In Progress",Model.ContinueWriting),("Revision","Revision",Model.RevisionQueue),("FinalPass","Final Pass",Model.PolishingQueue)}; var days=Model.Activity?.Days??Array.Empty(); var maximum=Math.Max(1L,days.Select(x=>x.Added+x.Removed).DefaultIfEmpty(1).Max()); @@ -16,63 +17,69 @@
+ @if(!string.IsNullOrWhiteSpace(Model.Book?.CoverThumbnailPath)){Cover of @bookTitle}else{}

@(Model.Journey?"Writing Journey":"Your writing desk")

@bookTitle

@(Model.Journey?"Accepted activity and the work ahead.":"Continue your manuscript, review your work, or choose what comes next.")

-
Word Companion Checking…Connection & Display Setup
+
Companion Checking…Connection & Display Setup
@if(TempData["WriterWorkspaceMessage"] is string message){

@message

} @if(TempData["WriterWorkspaceError"] is string error){} @if(!Model.Journey) {
- -

Next writing opportunity · Planned

+ +
@if(!Model.ActivityIsPrivate) { -
- Observed additions@(totals==null?"—":totals.Added.ToString("N0"))Words between accepted snapshots - Observed deletions@(totals==null?"—":totals.Removed.ToString("N0"))Revision can include removing words - Net manuscript change@(totals==null?"—":totals.Net.ToString("+0;-0;0"))Last 30 days · receipt dates (UTC) - Revision workspace@Model.RevisionQueue.CountScenes marked Needs Work · workflow status +
+

Writing Progress · last 30 days

Your Manuscript

+

@(Model.Book?.CurrentWordCount.ToString("N0") ?? "—") words · @(Model.Book?.ChapterCount ?? 0) chapters · @(Model.Book?.SceneCount ?? 0) scenes

@if(bookId.HasValue){Open Chapters}
+ @if(totals != null && (totals.Added > 0 || totals.Removed > 0)) + { +

+@totals.Added.ToString("N0") added · −@totals.Removed.ToString("N0") removed · @totals.Net.ToString("+0;-0;0") net

+ } + else{

@(totals?.HasAcceptedEvidence == true ? "Tracking begins at your manuscript baseline. New accepted changes will appear here." : "Activity begins with your first accepted manuscript baseline. Earlier writing cannot be reconstructed.")

} +
@foreach(var q in queues.Where(x=>x.Item3.Count>0)){}
+
@foreach(var q in queues){@q.Item3.Count @q.Item2}
+ @if(bookId.HasValue){Reports & activity settings}
} } -
-

Writing calendar · last 28 days

The shape of your recent work

Writing Journey
+
+

@(Model.Journey ? "Writing calendar · last 28 days" : "Activity summary · last 28 days")

Recent Activity

Writing Journey
@if(totals==null||totals.RecordedEvents==0) { -

@(Model.Activity?.Totals.HasAcceptedEvidence==true?"No accepted change is recorded in this period. Retained baseline evidence is available in activity settings.":"Your accepted manuscript can become the starting point. Earlier writing will not be counted as new activity.")

- @if(bookId.HasValue&&!Model.ActivityIsPrivate){Activity & baseline settings} +

@(!Model.Journey?"No new accepted changes yet.":Model.Activity?.Totals.HasAcceptedEvidence==true?"No accepted change is recorded in this period. Retained baseline evidence is available in activity settings.":"Your accepted manuscript can become the starting point. Earlier writing will not be counted as new activity.")

+ @if(Model.Journey&&bookId.HasValue&&!Model.ActivityIsPrivate){Activity & baseline settings} } else {
- @for(var i=27;i>=0;i--){var date=DateTime.UtcNow.Date.AddDays(-i);var day=days.FirstOrDefault(x=>x.Day.Date==date);@date.ToString("ddd")@date.Day@(day==null?"—":$"+{day.Added} / −{day.Removed}")} + @for(var i=27;i>=0;i--){var date=DateTime.UtcNow.Date.AddDays(-i);var day=days.FirstOrDefault(x=>x.Day.Date==date);@if(Model.Journey){@date.ToString("ddd")@date.Day@(day==null?"—":$"+{day.Added} / −{day.Removed}")}}
-

@totals.ActiveDays observed change days in the last 30 days. Receipt dates use UTC; they do not establish when the author wrote each word. Grey means no recorded change, not a missed opportunity. @if(totals.PartialComparisons>0){@totals.PartialComparisons comparisons contain qualified minimum estimates.}

-
Manuscript changes by day
+ + } @if(Model.ActivityIsPrivate){

Activity evidence is private to the book owner. Your existing writing workspaces remain available.

} -@if(Model.Activity?.Events.Count>0) +@if(Model.Journey&&Model.Activity?.Events.Count>0) {
Recent activity · source evidence
} @if(Model.Journey&&Model.WritingSchedule.UpcomingTasks.Count>0){

Planned work ahead

    @foreach(var item in Model.WritingSchedule.UpcomingTasks){
  • @item.ScheduledDate.ToString("ddd d MMM") · @item.SceneTitle · @item.TaskType
  • }
}
-

Workspaces

Choose your next step

Browse chapters
+

Workspaces

Choose your next step

@if(bookId.HasValue){Browse chapters}
+
Chapter and scene workspaces @foreach(var q in queues){} +
-@if(Model.WritingSchedule.TodayTasks.Count>0){
Today's planned writing · @Model.WritingSchedule.TodayTasks.Count tasks@foreach(var task in Model.WritingSchedule.TodayTasks){
@task.SceneTitle@task.TaskType · @task.EstimatedMinutes estimated minutes
}

Task completion is author-declared, not measured writing time.

} +@if(Model.WritingSchedule.TodayTasks.Count>0){
Today's planned writing · @Model.WritingSchedule.TodayTasks.Count tasks@foreach(var task in Model.WritingSchedule.TodayTasks){
@task.SceneTitle@task.TaskType · @task.EstimatedMinutes estimated minutes
}

Task completion is author-declared, not measured writing time.

}
Word Companion & Display Setup

Open Context and Intent as reference windows. Linked Word controls appear when a document is connected. Display placement depends on browser permission and popup support; moving Word itself is controlled by Windows.

Selected book Waiting for Word
Context Checking…
Intent Checking…
Layout Adaptive
@@ -84,5 +91,6 @@ else @section Scripts { + } diff --git a/PlotLine/Views/Writer/SchedulePreview.cshtml b/PlotLine/Views/Writer/SchedulePreview.cshtml index f7de9259..29c0d16b 100644 --- a/PlotLine/Views/Writer/SchedulePreview.cshtml +++ b/PlotLine/Views/Writer/SchedulePreview.cshtml @@ -6,8 +6,8 @@ } @@ -18,7 +18,7 @@

Generated writing schedule items.

- Back to Writing Plans + Back to Writing Plans @if (Model.SelectedPlan is not null) { Edit Plan diff --git a/PlotLine/Views/Writer/ScheduleSetup.cshtml b/PlotLine/Views/Writer/ScheduleSetup.cshtml index a90d8c34..d556c656 100644 --- a/PlotLine/Views/Writer/ScheduleSetup.cshtml +++ b/PlotLine/Views/Writer/ScheduleSetup.cshtml @@ -5,7 +5,7 @@ } @@ -13,7 +13,7 @@

Writing schedule

Schedule Setup

-

Create a writing plan and generate its first schedule.

+

Plan for the selected book, or choose All Books for a project-wide plan.

Skip scheduling · return to Writer
diff --git a/PlotLine/Views/Writer/WritingPlans.cshtml b/PlotLine/Views/Writer/WritingPlans.cshtml index 50f0d6e9..ad63b746 100644 --- a/PlotLine/Views/Writer/WritingPlans.cshtml +++ b/PlotLine/Views/Writer/WritingPlans.cshtml @@ -7,7 +7,7 @@ } @@ -15,10 +15,10 @@

Schedule admin

Writing Plans

-

Manage writing plans and their generated schedules.

+

@(Model.BookID.HasValue ? $"Plans for {Model.BookTitle}, including project-wide All Books plans." : "Manage writing plans and their generated schedules.")

View plans across all projects and books
diff --git a/PlotLine/Views/Writer/_WorkingObjective.cshtml b/PlotLine/Views/Writer/_WorkingObjective.cshtml new file mode 100644 index 00000000..3b6ad94b --- /dev/null +++ b/PlotLine/Views/Writer/_WorkingObjective.cshtml @@ -0,0 +1,39 @@ +@model WriterDashboardViewModel +@{ var objective = Model.Objective; var editing = Context.Request.Query["setup"] == "true"; } +@if (objective != null && !editing) +{ + +} +else if(Model.BookID.HasValue) +{ +
+

@Model.Book?.BookDisplayTitle

Start Here

+

Choose what you want to work on. You can start without a writing plan.

+ +
+ Choose your working objective +
+ + + + +
+
+
+
+} +else +{ +

Start Here

Select a project and book in the application bar to begin.

Your projects
+} diff --git a/PlotLine/wwwroot/css/writer-dashboard.css b/PlotLine/wwwroot/css/writer-dashboard.css index a11f04c9..2c854f13 100644 --- a/PlotLine/wwwroot/css/writer-dashboard.css +++ b/PlotLine/wwwroot/css/writer-dashboard.css @@ -5,3 +5,8 @@ @media(max-width:1050px){.writer-indicators{grid-template-columns:repeat(2,minmax(0,1fr))}.writer-calendar{grid-template-columns:repeat(7,minmax(0,1fr))}} @media(max-width:650px){.writer-heading{display:block}.writer-connection{margin-top:1rem}.writer-next-grid{grid-template-columns:1fr}.writer-card{padding:1rem}.writer-section-heading{align-items:flex-start;gap:.7rem}.writer-section-heading>a{font-size:.8rem}.writer-calendar{gap:.25rem}.writer-indicators{gap:.6rem}.writer-indicators strong{font-size:1.8rem}.writer-indicators .eyebrow{font-size:.6rem}.writer-change-row{grid-template-columns:50px 1fr 85px;font-size:.7rem}.writer-display-setup .writing-workspace-display-controls{display:flex;flex-direction:column;align-items:stretch}} .writer-recent{padding:0;list-style:none}.writer-recent li{padding:.7rem 0;border-bottom:1px solid var(--pd-border,#ccc);display:flex;gap:1rem;justify-content:space-between;font-size:.85rem}.writer-recent span{max-width:60ch} +/* Working intention is the primary action; evidence remains a compact summary. */ +.writer-heading{justify-content:flex-start}.writer-heading>div:not(.writer-book-cover):not(.writer-connection){flex:1}.writer-book-cover{width:76px;height:108px;object-fit:cover;border-radius:5px;box-shadow:0 6px 18px #0002;flex-shrink:0}.writer-cover-fallback{display:grid;place-items:center;background:var(--pd-primary,#576b78);color:#fff;font:2.5rem Georgia,serif;border-left:6px solid #ffffff40} +.writer-next-grid{grid-template-columns:minmax(0,2fr) minmax(230px,1fr)}.writer-start{border-top:4px solid var(--pd-primary,#576b78)}.writer-start-paths{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem;margin:1.3rem 0}.writer-path{display:flex;flex-direction:column;gap:.6rem;padding:1rem;border-left:3px solid var(--pd-primary,#576b78);background:var(--surface-alt,#8881);text-decoration:none;color:inherit}.writer-path:hover{background:#8882}.writer-path span{font-size:.9rem}.writer-objective-form{display:grid;gap:1rem;margin-top:1rem}.writer-objective-form label{display:grid;gap:.4rem}.writer-progress{display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin:1rem 0}.writer-progress .writer-workflow-strip{grid-column:1/-1}.writer-workflow-strip{display:flex;flex-wrap:wrap;gap:1rem}.writer-workflow-strip a{text-decoration:none;padding:.5rem .8rem;background:#8881;border-radius:20px}.writer-workflow-strip strong{font-size:1.2rem;margin-right:.3rem}.writer-change-track{height:22px;display:flex;border-radius:12px;overflow:hidden;background:#8882;margin:1rem 0}.writer-change-added{background:#418a73}.writer-change-removed{background:#bd795d}.writer-journey-compact .writer-calendar{display:flex;gap:5px;flex-wrap:wrap}.writer-journey-compact .writer-day{width:18px;height:18px;min-height:18px;padding:0;border-radius:4px}.writer-journey-compact .writer-empty{margin-bottom:.5rem} +@media(max-width:900px){.writer-next-grid{grid-template-columns:1fr}.writer-start-paths{grid-template-columns:1fr}.writer-progress{grid-template-columns:1fr}.writer-heading{flex-wrap:wrap}.writer-heading .writer-connection{width:100%}.writer-book-cover{width:52px;height:74px}} +.writer-progress{border:0;background:linear-gradient(120deg,var(--pd-surface,#ffffff10),#8881);padding-block:1.5rem}.writer-progress h2{font-size:1.65rem}.writer-workflow-progress{display:flex;height:9px;border-radius:8px;overflow:hidden;grid-column:1/-1;background:#8882}.writer-stage-WriteNext{background:#9eabc2}.writer-stage-InProgress{background:#ad8a55}.writer-stage-Revision{background:#916884}.writer-stage-FinalPass{background:#538879}.writer-journey-compact{border:0;background:transparent;padding:1rem 0;box-shadow:none}.writer-journey-compact h2{font-size:1.4rem}.writer-journey-compact .writer-section-heading{margin-bottom:.7rem}.writer-queue-details>summary{cursor:pointer;margin-block:.8rem}.writer-queue-details[open]>summary{margin-bottom:1.2rem}.writer-next-grid>article:not(.writer-current):not(.writer-start){border:0;border-left:1px solid #8885;border-radius:0;background:transparent;box-shadow:none} diff --git a/PlotLine/wwwroot/js/writer-objective.js b/PlotLine/wwwroot/js/writer-objective.js new file mode 100644 index 00000000..613c57ee --- /dev/null +++ b/PlotLine/wwwroot/js/writer-objective.js @@ -0,0 +1,14 @@ +(() => { + document.querySelector('[data-open-objective]')?.addEventListener('click', () => { document.getElementById('objective-setup').open = true; }); + const chapter = document.querySelector('[data-objective-chapter]'), scene = document.querySelector('[data-objective-scene]'); + if (!chapter || !scene) return; + const filter = () => { + for (const option of scene.options) { + option.hidden = Boolean(option.value && option.dataset.chapter !== chapter.value); + option.disabled = option.hidden; + } + if (scene.selectedOptions[0]?.disabled) scene.value = ''; + scene.disabled = !chapter.value; + }; + chapter.addEventListener('change', filter); filter(); +})(); diff --git a/PlotLine/wwwroot/js/writing-workspace-launcher.js b/PlotLine/wwwroot/js/writing-workspace-launcher.js index 599e32df..56ba77f8 100644 --- a/PlotLine/wwwroot/js/writing-workspace-launcher.js +++ b/PlotLine/wwwroot/js/writing-workspace-launcher.js @@ -98,6 +98,16 @@ fill(intentDisplaySelect, baseIntent, currentIntent); }; + let nativePresence = document.querySelector('#native-companion-status')?.nativePresence; + const renderCompanion = () => { + if (root.dataset.compactWriter !== "true" || !nativePresence) return; + if (document.querySelector('#native-companion-status')?.dataset.nativeAuthority === 'false') return; + const linked = nativePresence.some(lease => lease.wordAvailable && Number(lease.bookId) === fallbackScope.bookID); + text(statusNodes.word, nativePresence.connectionState === 'Connected' + ? (linked ? 'Connected · linked manuscript open' : 'Connected · no linked manuscript open') + : (nativePresence.connectionState === 'Disconnected' ? 'Disconnected' : nativePresence.connectionState)); + }; + window.addEventListener('native-companion-presence', event => { nativePresence = event.detail; renderCompanion(); }); const render = (status = latestStatus) => { const incomingScope = workspace.statusScope(status); if (status && ((activeScope.projectID && incomingScope.projectID && activeScope.projectID !== incomingScope.projectID) @@ -105,7 +115,8 @@ // Presence broadcasts cover all this author's books. They must not change // the workspace chosen here by a canonical position or explicit command. if(root.dataset.compactWriter === "true"){if(startButton)startButton.hidden=true;root.dataset.linkedDocument="false";} - text(statusNodes.word, status.wordCompanionConnected || status.WordCompanionConnected ? "Connected" : "Not connected"); + text(statusNodes.word, status.wordCompanionConnected || status.WordCompanionConnected ? "Linked manuscript open" : "No linked manuscript open"); + renderCompanion(); return; } if (root.dataset.compactWriter === "true") { @@ -117,8 +128,9 @@ latestStatus = status; activeScope = workspace.statusScope(status, activeScope); text(statusNodes.book, activeScope.bookID ? `Book ${activeScope.bookID}` : "Waiting for book"); - text(statusNodes.word, status?.wordCompanionConnected || status?.WordCompanionConnected ? "Connected" : "Not connected"); + text(statusNodes.word, status?.wordCompanionConnected || status?.WordCompanionConnected ? "Linked manuscript open" : "No linked manuscript open"); if(root.dataset.compactWriter === "true" && (status?.wordCompanionConnected || status?.WordCompanionConnected) && root.dataset.linkedDocument !== "true") text(statusNodes.word,"Connected · no linked document"); + renderCompanion(); text(statusNodes.context, statusText(status, "Context")); text(statusNodes.intent, statusText(status, "Intent")); const contextOpen = statusText(status, "Context") !== "Not open"; @@ -255,7 +267,8 @@ updateDisplayOptions(screenInfo); text(statusNodes.layout, screenInfo.layout?.mode || "adaptive"); }).catch(error => { - text(statusNodes.word, "Unavailable"); + text(statusNodes.word, "Status unavailable"); + renderCompanion(); text(statusNodes.context, "Unavailable"); text(statusNodes.intent, "Unavailable"); setMessage("Writing workspace presence is unavailable. Check your connection and retry opening a reference window; other PlotDirector sections remain available.");