diff --git a/PlotLine/Controllers/WriterActivitiesController.cs b/PlotLine/Controllers/WriterActivitiesController.cs new file mode 100644 index 00000000..b6b27206 --- /dev/null +++ b/PlotLine/Controllers/WriterActivitiesController.cs @@ -0,0 +1,27 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Data; +using PlotLine.Models; +namespace PlotLine.Controllers; +[Authorize] +public sealed class WriterActivitiesController(WriterActivityRepository activities,WriterObjectiveRepository objectives,IBookRepository books):Controller +{ + int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + [HttpGet]public async Task Panel(int bookId,string view="list")=>await Guard(async()=>PartialView("~/Views/Writer/_ActivityPlanner.cshtml",new WriterActivityPage(bookId,view is "board" or "schedule"?view:"list",await activities.Read(Actor,bookId),await activities.Entities(Actor,bookId)))); + [HttpPost,ValidateAntiForgeryToken]public Task Save(WriterActivity item)=>Guard(async()=>{ + if(!ModelState.IsValid||item.ID==Guid.Empty||!WriterActivity.Kinds.Contains(item.Kind)||!WriterActivity.Statuses.Contains(item.Status))return BadRequest(new{message="Choose a title, activity type and status. Your text is retained."}); + string? entityKind=null;int? entityID=null;if(!string.IsNullOrEmpty(item.EntityKey)){var entity=(await activities.Entities(Actor,item.BookID)).SingleOrDefault(e=>e.Key==item.EntityKey);if(entity==null)return BadRequest(new{message="Choose an available related entity."});entityKind=entity.EntityKind;entityID=entity.EntityID;} + await activities.Execute(new{Action="save",UserID=Actor,item.BookID,item.ID,item.Version,item.Title,item.Kind,item.Notes,EntityKind=entityKind,EntityID=entityID,item.Status,item.TargetDate});return Ok(new{saved=true});}); + [HttpPost,ValidateAntiForgeryToken]public Task Change(int bookId,Guid id,int version,string operation,string status="Next",int direction=0,bool confirm=false)=>Guard(async()=>{ + if(operation is not("status" or "archive" or "restore" or "move")||operation=="archive"&&!confirm)return BadRequest(); + await activities.Execute(new{Action=operation,UserID=Actor,BookID=bookId,ID=id,Version=version,Status=status,Direction=direction});return Ok();}); + [HttpPost,ValidateAntiForgeryToken]public Task Start(int bookId,Guid id,int version)=>Guard(async()=>{ + var row=(await activities.Read(Actor,bookId)).SingleOrDefault(x=>x.ID==id&&!x.IsArchived&&x.Version==version);if(row==null)return Conflict(new{message="This activity changed. Reload the planner."}); + if(row.EntityID.HasValue&&row.EntityTitle==null)return Conflict(new{message="The linked entity is unavailable. Edit the activity to select another."}); + var book=await books.GetAsync(bookId);if(book==null)return NotFound(); + if(row.ChapterID.HasValue)await objectives.Save(Actor,new(){BookID=bookId,ChapterID=row.ChapterID,SceneID=row.SceneID,Activity=row.Kind is "Editing" or "Review" or "AudioReview"?"Revising":row.Kind=="Research"?"Researching":"Drafting",Intention=row.Title}); + return row.Kind is "Review" or "AudioReview"?RedirectToAction("Review","Writer",new{bookId,chapterId=row.ChapterID}):row.EntityKind=="Character"?RedirectToAction("Edit","Characters",new{id=row.EntityID}):row.EntityKind=="Location"?RedirectToAction("Edit","Locations",new{id=row.EntityID}):row.EntityKind is "PlotLine" or "Thread"||row.Kind=="Plot"?RedirectToAction("Index","PlotLineWorkspace",new{projectId=book.ProjectID,bookId}):RedirectToAction("Write","Writer",new{bookId}); + }); + async Task Guard(Func> action){Response.Headers.CacheControl="no-store";try{return await action();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number is 51000 or 51002){return StatusCode(e.Number==51002?409:404,new{message="The activity or book is unavailable or changed. Your entered text is retained; reload before retrying."});}} +} diff --git a/PlotLine/Data/WriterActivityRepository.cs b/PlotLine/Data/WriterActivityRepository.cs new file mode 100644 index 00000000..70d6e1ae --- /dev/null +++ b/PlotLine/Data/WriterActivityRepository.cs @@ -0,0 +1,10 @@ +using System.Data; +using Dapper; +using PlotLine.Models; +namespace PlotLine.Data; +public sealed class WriterActivityRepository(ISqlConnectionFactory factory) +{ + public async Task> Read(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterActivities_Manage",new{Action="read",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} + public async Task> Entities(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterActivities_Manage",new{Action="entities",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} + public async Task Execute(object args){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterActivities_Manage",args,commandType:CommandType.StoredProcedure);} +} diff --git a/PlotLine/Models/WriterActivity.cs b/PlotLine/Models/WriterActivity.cs new file mode 100644 index 00000000..da377e2f --- /dev/null +++ b/PlotLine/Models/WriterActivity.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations; +namespace PlotLine.Models; +public sealed class WriterActivity +{ + public Guid ID{get;set;} public int BookID{get;set;} public int Version{get;set;} + [Required,StringLength(200)]public string Title{get;set;}=""; + [Required]public string Kind{get;set;}="Planning"; + [StringLength(10000)]public string? Notes{get;set;} + public string? EntityKind{get;set;} public int? EntityID{get;set;} public string? EntityTitle{get;set;} public int? ChapterID{get;set;}public int? SceneID{get;set;} + public string Status{get;set;}="Next";public int SortOrder{get;set;}public DateTime? TargetDate{get;set;} public bool IsArchived{get;set;} + public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;} + public string? EntityKey{get;set;} + public static readonly string[] Statuses=["Next","In progress","Completed","Deferred"]; + public static readonly string[] Kinds=["Writing","Editing","Planning","Research","Character","Plot","Review","AudioReview"]; +} +public sealed class WriterActivityEntity{public string EntityKind{get;set;}="";public int EntityID{get;set;}public string Title{get;set;}="";public int? ChapterID{get;set;}public int? SceneID{get;set;}public string Key=>$"{EntityKind}:{EntityID}";} +public sealed record WriterActivityPage(int BookID,string View,IReadOnlyList Activities,IReadOnlyList Entities); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 21042bf7..e7adbebe 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -210,6 +210,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddScoped(); diff --git a/PlotLine/Sql/281_WriterActivities.sql b/PlotLine/Sql/281_WriterActivities.sql new file mode 100644 index 00000000..c1862efc --- /dev/null +++ b/PlotLine/Sql/281_WriterActivities.sql @@ -0,0 +1,74 @@ +-- Author intentions only: no sessions, canonical prose or schedule engine is mutated. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.WriterActivities','U') IS NULL +BEGIN + CREATE TABLE dbo.WriterActivities(ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,BookID int NOT NULL, + Title nvarchar(200) NOT NULL,Kind varchar(30) NOT NULL,Notes nvarchar(max) NULL,EntityKind varchar(20) NULL,EntityID int NULL, + Status varchar(20) NOT NULL DEFAULT 'Next',SortOrder int NOT NULL DEFAULT 0,TargetDate date NULL,IsArchived bit NOT NULL DEFAULT 0,Version int NOT NULL DEFAULT 1, + CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), + CONSTRAINT FK_WriterActivities_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE, + CONSTRAINT FK_WriterActivities_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE, + CONSTRAINT CK_WriterActivities_Status CHECK(Status IN('Next','In progress','Completed','Deferred')), + CONSTRAINT CK_WriterActivities_Entity CHECK((EntityKind IS NULL AND EntityID IS NULL) OR (EntityKind IN('Chapter','Scene','Character','Location','PlotLine','Thread') AND EntityID>0))); + CREATE INDEX IX_WriterActivities_Book ON dbo.WriterActivities(UserID,BookID,IsArchived,SortOrder,ID); +END; +GO +CREATE OR ALTER PROCEDURE dbo.WriterActivities_Manage @Action varchar(15),@UserID int,@BookID int,@ID uniqueidentifier=NULL,@Version int=0, + @Title nvarchar(200)=NULL,@Kind varchar(30)=NULL,@Notes nvarchar(max)=NULL,@EntityKind varchar(20)=NULL,@EntityID int=NULL,@Status varchar(20)='Next',@TargetDate date=NULL,@Direction int=0 +AS +BEGIN + SET NOCOUNT ON; SET XACT_ABORT ON; + DECLARE @Project int; + SELECT @Project=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0; + IF @Project IS NULL THROW 51000,'Book access unavailable',1; + DECLARE @Entities TABLE(EntityKind varchar(20),EntityID int,Title nvarchar(500),ChapterID int NULL,SceneID int NULL); + INSERT @Entities + SELECT 'Chapter',ChapterID,ChapterTitle,ChapterID,NULL FROM dbo.Chapters WHERE BookID=@BookID AND IsArchived=0 + UNION ALL SELECT 'Scene',s.SceneID,s.SceneTitle,c.ChapterID,s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID AND c.IsArchived=0 AND s.IsArchived=0 + UNION ALL SELECT 'Character',CharacterID,CharacterName,NULL,NULL FROM dbo.Characters WHERE ProjectID=@Project AND IsArchived=0 + UNION ALL SELECT 'Location',LocationID,LocationName,NULL,NULL FROM dbo.Locations WHERE ProjectID=@Project AND IsArchived=0 + UNION ALL SELECT 'PlotLine',PlotLineID,PlotLineName,NULL,NULL FROM dbo.PlotLines WHERE ProjectID=@Project AND (BookID IS NULL OR BookID=@BookID) AND IsArchived=0 + UNION ALL SELECT 'Thread',t.PlotThreadID,t.ThreadTitle,NULL,NULL FROM dbo.PlotThreads t JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@Project AND (p.BookID IS NULL OR p.BookID=@BookID) AND p.IsArchived=0 AND t.IsArchived=0; + IF @Action='entities' BEGIN SELECT * FROM @Entities ORDER BY EntityKind,Title;RETURN;END; + IF @Action='read' BEGIN SELECT a.*,e.Title EntityTitle,e.ChapterID,e.SceneID FROM dbo.WriterActivities a LEFT JOIN @Entities e ON e.EntityKind=a.EntityKind AND e.EntityID=a.EntityID WHERE a.UserID=@UserID AND a.BookID=@BookID ORDER BY a.SortOrder,a.CreatedUtc,a.ID;RETURN;END; + IF @Action NOT IN('save','status','archive','restore','move') OR @ID IS NULL THROW 51000,'Invalid planner action',1; + BEGIN TRANSACTION; + IF @Action='save' + BEGIN + IF LEN(COALESCE(@Notes,''))>10000 OR LEN(TRIM(COALESCE(@Title,'')))=0 OR @Kind NOT IN('Writing','Editing','Planning','Research','Character','Plot','Review','AudioReview') OR @Status NOT IN('Next','In progress','Completed','Deferred') THROW 51000,'Choose a title, activity and status',1; + IF (@EntityID IS NULL AND @EntityKind IS NOT NULL) OR (@EntityID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM @Entities WHERE EntityKind=@EntityKind AND EntityID=@EntityID)) THROW 51000,'Related entity is not in this book or project',1; + IF @Version=0 + BEGIN + IF EXISTS(SELECT 1 FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.WriterActivities WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Title=@Title AND Kind=@Kind AND ISNULL(Notes,'')=ISNULL(@Notes,'') AND ISNULL(EntityKind,'')=ISNULL(@EntityKind,'') AND ISNULL(EntityID,0)=ISNULL(@EntityID,0) AND Status=@Status AND ISNULL(TargetDate,'00010101')=ISNULL(@TargetDate,'00010101')) THROW 51002,'Activity changed; reload before retrying',1; + END + ELSE BEGIN + DECLARE @Order int=(SELECT ISNULL(MAX(SortOrder),0)+10 FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID); + INSERT dbo.WriterActivities(ID,UserID,BookID,Title,Kind,Notes,EntityKind,EntityID,Status,TargetDate,SortOrder) VALUES(@ID,@UserID,@BookID,@Title,@Kind,@Notes,@EntityKind,@EntityID,@Status,@TargetDate,@Order); + END; + END + ELSE BEGIN + UPDATE dbo.WriterActivities SET Title=@Title,Kind=@Kind,Notes=@Notes,EntityKind=@EntityKind,EntityID=@EntityID,Status=@Status,TargetDate=@TargetDate,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Version=@Version; + IF @@ROWCOUNT<>1 THROW 51002,'Activity changed; reload before retrying',1; + END; + END + ELSE BEGIN + DECLARE @Sort int;SELECT @Sort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Version=@Version; + IF @Sort IS NULL THROW 51002,'Activity changed; reload before retrying',1; + IF @Action='status' AND @Status NOT IN('Next','In progress','Completed','Deferred') THROW 51000,'Invalid status',1; + IF @Action='move' + BEGIN + IF @Direction NOT IN(-1,1) THROW 51000,'Invalid order',1; + DECLARE @Other uniqueidentifier,@OtherSort int; + IF @Direction=-1 SELECT TOP(1) @Other=ID,@OtherSort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND IsArchived=0 AND SortOrder<@Sort ORDER BY SortOrder DESC; + ELSE SELECT TOP(1) @Other=ID,@OtherSort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND IsArchived=0 AND SortOrder>@Sort ORDER BY SortOrder; + IF @Other IS NOT NULL BEGIN UPDATE dbo.WriterActivities SET SortOrder=@Sort,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@Other;UPDATE dbo.WriterActivities SET SortOrder=@OtherSort,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID;END; + END + ELSE UPDATE dbo.WriterActivities SET Status=CASE WHEN @Action='status' THEN @Status ELSE Status END,IsArchived=CASE WHEN @Action='archive' THEN 1 WHEN @Action='restore' THEN 0 ELSE IsArchived END,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID; + END; + COMMIT; +END; +GO diff --git a/PlotLine/Views/Writer/_ActivityCard.cshtml b/PlotLine/Views/Writer/_ActivityCard.cshtml new file mode 100644 index 00000000..4046c794 --- /dev/null +++ b/PlotLine/Views/Writer/_ActivityCard.cshtml @@ -0,0 +1,12 @@ +@model PlotLine.Models.WriterActivity +
+

@Model.Title

@Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){}

+ @if(!string.IsNullOrWhiteSpace(Model.Notes)){

@Model.Notes

} + Updated @Model.UpdatedUtc.ToString("d MMM yyyy HH:mm") UTC +
+
+ @foreach(var direction in new[]{-1,1}){
} +
+
Edit activity
+
Archive activity

Keep this record in the archive and remove it from active views.

+
diff --git a/PlotLine/Views/Writer/_ActivityEditor.cshtml b/PlotLine/Views/Writer/_ActivityEditor.cshtml new file mode 100644 index 00000000..e6bc7541 --- /dev/null +++ b/PlotLine/Views/Writer/_ActivityEditor.cshtml @@ -0,0 +1,12 @@ +@model PlotLine.Models.WriterActivity +@{var choices=(IReadOnlyList)ViewData["ActivityEntities"]!;var key="activity-"+Model.ID;} +
+ + + + + + + +

+
diff --git a/PlotLine/Views/Writer/_ActivityPlanner.cshtml b/PlotLine/Views/Writer/_ActivityPlanner.cshtml new file mode 100644 index 00000000..387c2959 --- /dev/null +++ b/PlotLine/Views/Writer/_ActivityPlanner.cshtml @@ -0,0 +1,14 @@ +@model PlotLine.Models.WriterActivityPage +@{ViewData["ActivityEntities"]=Model.Entities;var active=Model.Activities.Where(x=>!x.IsArchived).ToArray();} +
+
@foreach(var view in new[]{"list","board","schedule"}){}
+

Add planned activity
+ @if(active.Length==0){

No planned activities yet. Add one when it helps you organise your work.

} + @if(Model.View=="board"){
@foreach(var status in PlotLine.Models.WriterActivity.Statuses){

@status

@foreach(var item in active.Where(x=>x.Status==status)){}
}
} + else if(Model.View=="schedule"){ +

Dated activities

@foreach(var item in active.Where(x=>x.TargetDate.HasValue).OrderBy(x=>x.TargetDate)){} +

Undated activities

@foreach(var item in active.Where(x=>!x.TargetDate.HasValue)){} +

Existing allocated writing time and schedules are shown below. Target dates do not reserve writing time or generate sessions.

+ }else{@foreach(var item in active){}} +
Archived activities (@Model.Activities.Count(x=>x.IsArchived))@foreach(var item in Model.Activities.Where(x=>x.IsArchived)){

@item.Title

@item.Notes

}
+
diff --git a/PlotLine/Views/Writer/_WriterPlan.cshtml b/PlotLine/Views/Writer/_WriterPlan.cshtml index b48dd3b5..6af2bfb0 100644 --- a/PlotLine/Views/Writer/_WriterPlan.cshtml +++ b/PlotLine/Views/Writer/_WriterPlan.cshtml @@ -1,13 +1,8 @@ @model WriterDashboardViewModel
-
-

Next activities

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

- @if(Model.Work?.Current is {} recording && recording.StartedUtc>DateTime.UtcNow.AddHours(-12)){

Recording in progress

@recording.Kind · @(recording.ChapterTitle??"Across the book")

Return to your session

This actual recording is separate from your intended next work.

} -

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.

+
+

Planned activities

What you intend to accomplish. Starting work is separate from recording a session.

+

Loading your activities…

@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/wwwroot/js/writer-planner.js b/PlotLine/wwwroot/js/writer-planner.js new file mode 100644 index 00000000..3b11ce8f --- /dev/null +++ b/PlotLine/wwwroot/js/writer-planner.js @@ -0,0 +1,7 @@ +(()=>{const root=document.querySelector('[data-activity-planner]');if(!root)return;let view=new URLSearchParams(location.search).get('view')||'list',busy=false,dirty=false,allow=false; +async function load(){const url=new URL(root.dataset.url,location.href);url.searchParams.set('view',view);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('The planner could not load. Reload when connected.');const doc=new DOMParser().parseFromString(await r.text(),'text/html'),panel=doc.querySelector('[data-planner-view]');if(!panel)throw Error('Sign in to resume your planner.');root.replaceChildren(panel);dirty=false;} +root.addEventListener('input',()=>dirty=true); +root.addEventListener('click',async event=>{const tab=event.target.closest('[data-planner-tab]');if(!tab||busy)return;if(dirty&&!confirm('Leave unsaved activity edits?'))return;view=tab.dataset.plannerTab;try{await load();}catch(e){root.querySelector('[data-planner-message]').textContent=e.message;}}); +root.addEventListener('submit',async event=>{const form=event.target;if(form.matches('[data-activity-start]')){if(form.dataset.pending==='true'||dirty&&!confirm('Leave unsaved activity edits and start this work?')){event.preventDefault();return;}form.dataset.pending='true';allow=true;return;}if(!form.matches('[data-activity-change],[data-activity-save]'))return;event.preventDefault();if(busy)return;busy=true;const button=event.submitter;button.disabled=true;let committed=false;const message=form.querySelector('[data-activity-error]')||root.querySelector('[data-planner-message]');message.textContent='Saving…';try{const r=await fetch(form.action,{method:'POST',body:new FormData(form)});if(!r.ok){const data=await r.json().catch(()=>null);throw Error(data?.message||'Save not confirmed. Your text is retained. Reload before retrying.');}committed=true;dirty=false;await load();}catch(e){message.textContent=committed?'Saved, but the refreshed planner could not load. Reload the page before making another change.':e.message;}finally{busy=false;button.disabled=committed&&form.isConnected;}}); +window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allow){e.preventDefault();e.returnValue='';}});load().catch(e=>{root.textContent=e.message;}); +})();