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 async Task Index(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(); 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); return View("Index",model); } public Task Workspaces(int? projectId,int? bookId,string? workspace=null)=>Index(projectId,bookId,workspace); public Task Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>Index(projectId,bookId,journey:true,year:year,month:month,day:day); public IActionResult DisplaySetup(int? projectId,int? bookId)=>Redirect(Url.Action(nameof(Index),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 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); return model is null ? NotFound() : View(model); } public async Task 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 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 EditWritingPlan(int writingPlanId) { try { var model = await writingSchedule.GetWritingPlanSettingsAsync(writingPlanId); return View(model); } catch (InvalidOperationException) { return NotFound(); } } [HttpPost] [ValidateAntiForgeryToken] public async Task 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 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 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; 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";} await writingSchedule.PopulateScheduleSetupOptionsAsync(model); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task 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 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 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 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 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 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 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 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 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 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 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. } } }