PlotDirector/PlotLine/Controllers/WriterController.cs

470 lines
24 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using PlotLine.Services;
using PlotLine.ViewModels;
using PlotLine.Data;
using System.Security.Claims;
using Microsoft.Data.SqlClient;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WriterController(
IWriterWorkspaceService writerWorkspace,
IWritingScheduleService writingSchedule,
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null) : Controller
{
public Task<IActionResult> Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false)
=> LoadDestination(setup ? "Write" : journey || workspace != null ? "Legacy" : "Home", projectId, bookId, workspace, journey, year, month, day);
public Task<IActionResult> Write(int? projectId, int? bookId = null) => LoadDestination("Write", projectId, bookId);
public Task<IActionResult> Explore(int? projectId, int? bookId = null) => LoadDestination("Explore", projectId, bookId);
public Task<IActionResult> Plan(int? projectId, int? bookId = null) => LoadDestination("Plan", projectId, bookId);
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public async Task<IActionResult> Review(int? projectId,int? bookId=null,int? chapterId=null,bool focus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
{
Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";
var result=await LoadDestination("Review",projectId,bookId);
if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){
try{model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;}
catch(UnauthorizedAccessException){return NotFound();}
catch(SqlException e)when(e.Number==51000){return NotFound();}
catch(Exception e)when(e is SqlException or TimeoutException or System.Text.Json.JsonException){Response.StatusCode=503;return View("~/Views/ManuscriptReader/Unavailable.cshtml",new{BookId=model.BookID,ChapterId=chapterId});}
}
return result;
}
public Task<IActionResult> Reflect(int? projectId, int? bookId = null) => LoadDestination("Reflect", projectId, bookId);
public Task<IActionResult> Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId);
public Task<IActionResult> Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId);
private async Task<IActionResult> LoadDestination(string destination, int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null)
{
if(bookId.HasValue&&!projectId.HasValue&&bookRepository!=null)
{
if(access!=null&&!await access.CanAccessEntityAsync("Book",bookId.Value))return NotFound();
var selected=await bookRepository.GetAsync(bookId.Value);if(selected==null||selected.IsArchived)return NotFound();projectId=selected.ProjectID;
}
var model = await writerWorkspace.GetDashboardAsync(projectId, bookId);
if(!projectId.HasValue && int.TryParse(model.ProjectOptions.FirstOrDefault()?.Value,out var firstProject))
{ projectId=firstProject;model=await writerWorkspace.GetDashboardAsync(projectId, bookId); }
if(bookRepository!=null && projectId.HasValue)
{
var available=(await bookRepository.ListByProjectAsync(projectId.Value)).Where(b=>!b.IsArchived).ToArray();
model.Book=bookId.HasValue?available.SingleOrDefault(b=>b.BookID==bookId):available.FirstOrDefault();
if(bookId.HasValue&&model.Book==null)return NotFound();
model.BookID=model.Book?.BookID;
// Resolve a default book before the database applies its per-queue limit.
if (!bookId.HasValue && model.BookID.HasValue)
{
var scoped = await writerWorkspace.GetDashboardAsync(projectId, model.BookID);
model.WriteNext = scoped.WriteNext;
model.ContinueWriting = scoped.ContinueWriting;
model.RevisionQueue = scoped.RevisionQueue;
model.PolishingQueue = scoped.PolishingQueue;
}
}
else model.BookID=bookId;
if(model.BookID.HasValue)
{
if(access!=null&&!await access.CanAccessEntityAsync("Book",model.BookID.Value))return NotFound();
model.WriteNext=model.WriteNext.Where(x=>x.BookID==model.BookID).ToArray();
model.ContinueWriting=model.ContinueWriting.Where(x=>x.BookID==model.BookID).ToArray();
model.RevisionQueue=model.RevisionQueue.Where(x=>x.BookID==model.BookID).ToArray();
model.PolishingQueue=model.PolishingQueue.Where(x=>x.BookID==model.BookID).ToArray();
if(activity!=null&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user))
{ 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);
if(model.BookID.HasValue)
{ model.WritingSchedule.TodayTasks=model.WritingSchedule.TodayTasks.Where(x=>x.BookID==model.BookID).ToArray();model.WritingSchedule.UpcomingTasks=model.WritingSchedule.UpcomingTasks.Where(x=>x.BookID==model.BookID).ToArray(); }
if (work != null && model.BookID.HasValue && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var workAuthor) && !model.ActivityIsPrivate)
{
var selectedYear = journey && year is >=2000 and <=2100 ? year.Value : DateTime.UtcNow.Year;
var sessions = journey ? await work.History(workAuthor, model.BookID.Value,day) : Array.Empty<PlotLine.Models.WriterWorkSession>();
var calendar = await work.Calendar(workAuthor,model.BookID.Value,selectedYear);
if(!journey&&DateTime.UtcNow.DayOfYear<28)calendar=calendar.Concat(await work.Calendar(workAuthor,model.BookID.Value,selectedYear-1)).ToArray();
model.Work = new(){BookID=model.BookID.Value,Year=selectedYear,Month=month is >=1 and <=12 ? month.Value : DateTime.UtcNow.Month,Day=day,Sessions=sessions,Current=sessions.FirstOrDefault(x=>x.EndedUtc==null),Days=calendar};
}
if(planning!=null&&model.BookID.HasValue&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var planner)) model.PlannedActivities=await planning.Upcoming(planner,model.BookID.Value);
if (model.ProjectID is > 0 && model.BookID is > 0)
{
model.WorkingContext = new PlotLine.Services.Writer.WriterContext(model.ProjectID.Value, model.BookID.Value);
if (model.Objective is {} focus)
{
var selected = new PlotLine.Services.Writer.WriterSelection(model.ProjectID.Value, model.BookID.Value, focus.ChapterID, focus.SceneID);
model.WorkingContext = model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.SavedObjective, selected)
.Select(PlotLine.Services.Writer.WriterFocusRole.Working, selected);
}
}
model.Suggestions = (suggestions ?? new PlotLine.Services.Writer.WriterSuggestionProvider()).Suggest(model);
model.Destination = destination;
return View(destination == "Home" ? "Index" : destination == "Legacy" ? "Legacy" : "Destination", model);
}
public Task<IActionResult> Workspaces(int? projectId,int? bookId,string? workspace=null)=>LoadDestination("Legacy",projectId,bookId,workspace);
public Task<IActionResult> Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>LoadDestination("Legacy",projectId,bookId,journey:true,year:year,month:month,day:day);
public IActionResult DisplaySetup(int? projectId,int? bookId)=>Redirect(Url.Action(nameof(Overview),new{projectId,bookId})+"#display-setup");
[HttpGet("Write"),HttpGet("Write/Index")]
public IActionResult LegacyWrite(int? projectId,int? bookId)=>RedirectToAction(nameof(Index),new{projectId,bookId});
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> 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(Write), 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(Write), new { bookId = model.BookID, setup = true }); }
return scheduleNow ? RedirectToAction(nameof(ScheduleSetup), new { bookId = model.BookID }) : RedirectToAction(nameof(Write), new { bookId = model.BookID });
}
public async Task<IActionResult> Chapter(int id)
{
var model = await writerWorkspace.GetChapterWorkflowAsync(id);
return model is null ? NotFound() : View(model);
}
public async Task<IActionResult> SchedulePreview(int? writingPlanId, int? projectId = null, int? bookId = null)
{
if (projectId.HasValue && access != null && !await access.CanAccessProjectAsync(projectId.Value)) return NotFound();
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.GetSchedulePreviewAsync(writingPlanId, projectId, bookId);
if (writingPlanId.HasValue && model.SelectedPlan == null) return NotFound();
if(planning!=null&&model.SelectedPlan!=null)model.DerivedActivities=await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.SelectedPlan.WritingPlanID);
return View(model);
}
public async Task<IActionResult> 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);
}
public async Task<IActionResult> EditWritingPlan(int writingPlanId)
{
try
{
var model = await writingSchedule.GetWritingPlanSettingsAsync(writingPlanId);
return View(model);
}
catch (InvalidOperationException)
{
return NotFound();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditWritingPlan(WritingPlanSettingsEditViewModel model)
{
if (!model.WritingDayAvailability.Any(x => x.IsAvailable))
{
ModelState.AddModelError(string.Empty, "Select at least one writing day.");
ModelState.AddModelError(nameof(model.WritingDayAvailability), "Select at least one writing day.");
}
if (model.DeadlineDate.Date < model.StartDate.Date)
{
ModelState.AddModelError(nameof(model.DeadlineDate), "Deadline date must be on or after the start date.");
}
if (!ModelState.IsValid)
{
await PopulatePlanSettingsDisplayAsync(model);
return View(model);
}
try
{
await writingSchedule.UpdateWritingPlanSettingsAsync(model);
TempData["WritingPlansMessage"] = "Writing plan updated.";
var saved = await writingSchedule.GetWritingPlanSettingsAsync(model.WritingPlanID);
return RedirectToAction(nameof(WritingPlans), new { projectId = saved.ProjectID, bookId = saved.BookID });
}
catch (InvalidOperationException ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
await PopulatePlanSettingsDisplayAsync(model);
return View(model);
}
}
public async Task<IActionResult> PreviewRebalance(int writingPlanId)
{
var preview = await SchedulePreview(writingPlanId);
if (preview is not ViewResult page || page.Model is not WritingSchedulePreviewViewModel model) return preview;
try
{
model.RebalancePreview = await writingSchedule.PreviewRebalanceAsync(writingPlanId);
}
catch (InvalidOperationException ex)
{
TempData["SchedulePreviewError"] = ex.Message;
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId });
}
return View(nameof(SchedulePreview), model);
}
public async Task<IActionResult> ScheduleSetup(int? projectId, int? bookId = null, string? focusActivity = 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;
if(objectives!=null&&bookId.HasValue&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author)){var objective=(await objectives.Read(author,bookId.Value)).Objective;if(objective?.Activity is "Revising" or "Editing" or "Proofreading")model.GoalType="Revision";}
if (PlotLine.Services.Writer.WriterFocusActivities.ObjectiveKinds.Contains(focusActivity))
model.GoalType = focusActivity is "Revising" or "Editing" or "Proofreading" ? "Revision" : "FirstDraft";
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ScheduleSetup(WritingScheduleSetupViewModel model)
{
if (!model.WritingDayAvailability.Any(x => x.IsAvailable))
{
ModelState.AddModelError(string.Empty, "Select at least one writing day.");
ModelState.AddModelError(nameof(model.WritingDayAvailability), "Select at least one writing day.");
}
if (model.DeadlineDate.Date < model.StartDate.Date)
{
ModelState.AddModelError(nameof(model.DeadlineDate), "Deadline date must be on or after the start date.");
}
if (!ModelState.IsValid)
{
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
return View(model);
}
try
{
var result = await writingSchedule.CreateScheduleFromSetupAsync(model);
if (string.IsNullOrWhiteSpace(result.ValidationMessage))
{
TempData["SchedulePreviewMessage"] = $"Writing plan created. {result.GeneratedItemCount} item{(result.GeneratedItemCount == 1 ? "" : "s")} generated.";
}
else
{
TempData["SchedulePreviewError"] = result.ValidationMessage;
}
if(result.GeneratedItemCount==0){TempData.Remove("SchedulePreviewMessage");return RedirectToAction("Index","WriterPlanning",new{writingPlanId=result.WritingPlanID});}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId = result.WritingPlanID });
}
catch (InvalidOperationException ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
return View(model);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GenerateSchedule(int writingPlanId)
{
try{if(planning!=null&&(await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),writingPlanId)).Count>0)return RedirectToAction("Index","WriterPlanning",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
try
{
var items = await writingSchedule.GenerateSchedule(writingPlanId);
TempData["SchedulePreviewMessage"] = $"{items.Count} item{(items.Count == 1 ? "" : "s")} generated.";
}
catch (InvalidOperationException ex)
{
TempData["SchedulePreviewError"] = ex.Message;
}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteGeneratedSchedule(int writingPlanId)
{
try
{
await writingSchedule.DeleteScheduleAsync(writingPlanId);
TempData["SchedulePreviewMessage"] = "Generated schedule deleted.";
}
catch (InvalidOperationException ex)
{
TempData["SchedulePreviewError"] = ex.Message;
}
catch
{
TempData["SchedulePreviewError"] = "Generated schedule could not be deleted.";
}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApplyRebalance(int writingPlanId)
{
try
{
await writingSchedule.ApplyRebalanceAsync(writingPlanId);
TempData["SchedulePreviewMessage"] = "Schedule rebalanced successfully.";
}
catch (InvalidOperationException ex)
{
TempData["SchedulePreviewError"] = ex.Message;
}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ActivateWritingPlan(int writingPlanId, int? projectId = null, int? bookId = null)
{
try
{
await writingSchedule.ActivateWritingPlanAsync(writingPlanId);
TempData["WritingPlansMessage"] = "Writing plan activated.";
}
catch (InvalidOperationException ex)
{
TempData["WritingPlansError"] = ex.Message;
}
return RedirectToAction(nameof(WritingPlans), new { projectId, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeactivateWritingPlan(int writingPlanId, int? projectId = null, int? bookId = null)
{
try
{
await writingSchedule.DeactivateWritingPlanAsync(writingPlanId);
TempData["WritingPlansMessage"] = "Writing plan deactivated.";
}
catch (InvalidOperationException ex)
{
TempData["WritingPlansError"] = ex.Message;
}
return RedirectToAction(nameof(WritingPlans), new { projectId, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteWritingPlan(int writingPlanId, int? projectId = null, int? bookId = null)
{
try
{
await writingSchedule.DeleteWritingPlanAsync(writingPlanId);
TempData["WritingPlansMessage"] = "Writing plan deleted.";
}
catch (InvalidOperationException ex)
{
TempData["WritingPlansError"] = ex.Message;
}
return RedirectToAction(nameof(WritingPlans), new { projectId, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegenerateWritingPlanSchedule(int writingPlanId, int? projectId = null, int? bookId = null)
{
try{if(planning!=null&&(await planning.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),writingPlanId)).Count>0)return RedirectToAction("Index","WriterPlanning",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
try
{
var items = await writingSchedule.RegenerateScheduleAsync(writingPlanId);
TempData["WritingPlansMessage"] = $"{items.Count} item{(items.Count == 1 ? "" : "s")} generated.";
}
catch (InvalidOperationException ex)
{
TempData["WritingPlansError"] = ex.Message;
}
return RedirectToAction(nameof(WritingPlans), new { projectId, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> 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, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> 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, bookId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveChapterGoal(ChapterGoalEditViewModel model)
{
await writerWorkspace.SaveChapterGoalAsync(model);
if (string.Equals(Request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
return Json(new { ok = true });
return RedirectToAction(nameof(Chapter), new { id = model.ChapterID });
}
private async Task PopulatePlanSettingsDisplayAsync(WritingPlanSettingsEditViewModel model)
{
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;
model.StartDate = existing.StartDate;
model.RebalanceModeOptions = existing.RebalanceModeOptions;
}
catch (InvalidOperationException)
{
// The service will surface the ownership/not-found validation message on submit.
}
}
}