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; using PlotLine.Models; using PlotLine.Services.Writer; 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, INarrativeFocus? narrativeFocus=null, ContextSavedData? savedData=null) : Controller { public Task Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false) { if(journey)return Task.FromResult(RedirectToAction(nameof(Reflect),new{projectId,bookId,year,month,day})); if(!setup&&!journey&&workspace!=null)return Task.FromResult(RedirectToAction(nameof(Workspaces),new{projectId,bookId,workspace})); return LoadDestination(setup ? "Write" : journey ? "Legacy" : "Home", projectId, bookId, workspace, journey, year, month, day); } public Task Write(int? projectId, int? bookId = null) => LoadDestination("Write", projectId, bookId); public Task Explore(int? projectId, int? bookId = null) => LoadDestination("Explore", projectId, bookId); public Task Plan(int? projectId, int? bookId = null) => LoadDestination("Plan", projectId, bookId); [ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public async Task Review(int? projectId,int? bookId=null,int? chapterId=null,bool focus=false,bool reading=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{ // Initial/deep-link chapter loading is local; deliberate navigation publishes through SharedFocus. chapterId ??= model.NarrativeFocus?.ChapterID; 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;model.ReviewReader.ReadingMode=reading;} catch(UnauthorizedAccessException){return NotFound();} catch(SqlException e)when(e.Number==51000){return NotFound();} catch(NarrativeFocusConflictException){return Conflict(new{message="Current focus changed in another window. Retry this navigation."});} 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; } [HttpGet,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public async Task ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,int? chapterId=null,bool localFocus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null) { var result=await Review(projectId,bookId,chapterId,focus,reading,reader); if(result is ViewResult {Model:WriterDashboardViewModel model}) { if(!localFocus&&model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."}); return PartialView("_WriterReview",model); } return result; } public Task Reflect(int? projectId, int? bookId = null, int? year=null, int? month=null, DateTime? day=null) => LoadDestination("Reflect", projectId, bookId, journey:true, year:year, month:month, day:day); public Task Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId); public Task Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId); private async Task 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; } if(narrativeFocus != null && model.ProjectID is int focusProject && model.BookID is int focusBook && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var focusUser)) model.NarrativeFocus=await narrativeFocus.Read(focusUser,focusProject,focusBook); 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=destination=="Plan"?(await work.State(workAuthor,model.BookID.Value)).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 (destination == "Home") { model.ScheduleDailyFocus = await planning.DailyFocus(planner, model.BookID.Value); model.CurrentWorkingGroup = (await planning.WorkingGroups(planner, model.BookID.Value)) .FirstOrDefault(group => group.IsCurrent && group.ChapterIDs.Count > 0); } } 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); } } if(model.NarrativeFocus is {} currentFocus && model.WorkingContext != null) model.WorkingContext=model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.Working, new(currentFocus.ProjectID,currentFocus.BookID,currentFocus.ChapterID,currentFocus.SceneID)); 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 Workspaces(int? projectId,int? bookId,string? workspace=null)=>LoadDestination("Legacy",projectId,bookId,workspace); public IActionResult Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>RedirectToAction(nameof(Reflect),new{projectId,bookId,year,month,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 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 }); } if(Request.Headers["X-Requested-With"]=="XMLHttpRequest") { var confirmed=(await objectives.Read(author,model.BookID)).Objective!; return Json(new { saved=true, activity=confirmed.Activity, chapterID=confirmed.ChapterID, sceneID=confirmed.SceneID, title=confirmed.SceneTitle??confirmed.ChapterTitle??"Across the book", intention=confirmed.Intention, sessionKind=PlotLine.Services.Writer.WriterFocusActivities.SessionKind(confirmed.Activity), continueUrl=confirmed.SceneID.HasValue?Url.Action("Edit","Scenes",new{id=confirmed.SceneID}):confirmed.ChapterID.HasValue?Url.Action("Chapter",new{id=confirmed.ChapterID}):Url.Action("Details","Books",new{id=model.BookID}), inspectUrl=confirmed.ChapterID.HasValue?Url.Action("Inspect","WriterAuthoring",new{bookId=model.BookID,chapterId=confirmed.ChapterID,sceneId=confirmed.SceneID}):null }); } return scheduleNow ? RedirectToAction(nameof(ScheduleSetup), new { bookId = model.BookID }) : RedirectToAction(nameof(Write), new { bookId = model.BookID }); } [HttpGet, ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public async Task Focus(int bookId) { if(access==null||!await access.CanAccessEntityAsync("Book",bookId)||objectives==null)return NotFound(); var saved=await objectives.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),bookId); return PartialView("_WriterFocusForm",new WriterDashboardViewModel {BookID=bookId,Objective=saved.Objective,ObjectiveChoices=saved.Choices}); } public async Task Chapter(int id) { var model = await writerWorkspace.GetChapterWorkflowAsync(id); 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, string? focusActivity = null, int? workingGroupId = 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; model.WorkingGroupID = workingGroupId; if (planning != null && bookId.HasValue && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var groupOwner)) { model.WorkingGroups = await planning.WorkingGroups(groupOwner, bookId.Value); model.ObservedDraftingWordsPerHour = await planning.ObservedDraftingRate(groupOwner, bookId.Value); } 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] [RequestFormLimits(ValueCountLimit = 20000)] public async Task ScheduleSetup(WritingScheduleSetupViewModel model, string? step) { if (planning is null) return StatusCode(503); if (!ModelState.IsValid) { await writingSchedule.PopulateScheduleSetupOptionsAsync(model); return View(model); } try { model.RebalanceMode = "Ask"; var plan = await writingSchedule.PrepareScheduleFromSetupAsync(model); model.WorkingGroups = plan.BookID.HasValue ? await planning.WorkingGroups(plan.UserID, plan.BookID.Value) : []; model.ObservedDraftingWordsPerHour = plan.BookID.HasValue ? await planning.ObservedDraftingRate(plan.UserID, plan.BookID.Value) : null; if (step == "use-observed-rate" && model.ObservedDraftingWordsPerHour is > 0 and int observedRate) model.DraftingWordsPerHour = observedRate; var workingGroup = model.WorkingGroups.SingleOrDefault(group => group.GroupID == model.WorkingGroupID); if (model.WorkingGroupID.HasValue && (workingGroup is null || workingGroup.ChapterIDs.Count == 0)) throw new ArgumentException("Choose a group with active chapters in this book."); var candidates = await planning.ReviewCandidates(plan); if (workingGroup != null) { var members = workingGroup.ChapterIDs.ToHashSet(); var included = candidates.Where(row => row.ChapterID.HasValue && members.Contains(row.ChapterID.Value)).ToArray(); candidates = [new() { BookID = plan.BookID!.Value, GroupID = workingGroup.GroupID, Title = workingGroup.Name, BookTitle = included.FirstOrDefault()?.BookTitle ?? "", Words = included.Length > 0 && included.All(row => row.Words is > 0) ? included.Sum(row => row.Words) : null }]; } var posted = model.Candidates; var reviewed = model.ReviewFingerprint; model.ReviewFingerprint = null; model.Candidates = candidates; ModelState.Clear(); var eligible = candidates.ToDictionary(row => (row.ChapterID, row.SceneID, row.GroupID)); var seen = new HashSet<(int?, int?, int?)>(); foreach (var candidate in candidates) { candidate.Selected = candidate.GroupID.HasValue; candidate.Kind = plan.GoalType == "FirstDraft" ? "Draft" : plan.GoalType == "Revision" ? "Edit" : "Review"; candidate.Minutes = candidate.Kind == "Draft" && candidate.Words is > 0 ? WriterPlanning.DraftingBudget(candidate.Words.Value, model.DraftingWordsPerHour) : 30; } if (step is "preview" or "save") { foreach (var row in posted) { var key = (row.ChapterID, row.SceneID, row.GroupID); if (!seen.Add(key) || !eligible.TryGetValue(key, out var candidate)) throw new ArgumentException("The available work changed. Review the current chapters and scenes."); candidate.Selected = row.Selected; candidate.Minutes = row.Minutes; candidate.Kind = row.Kind; } var selected = candidates.Where(row => row.Selected).ToArray(); model.Capacity = WriterPlanning.Review(model, selected); model.OverlapDates = await planning.CapacityOverlap(plan.UserID, null, model.Capacity.Allocations); var reviewedInputs = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new { plan.UserID, plan.ProjectID, plan.BookID, plan.PlanName, plan.GoalType, model.CreationToken, plan.StartDate, plan.DeadlineDate, plan.AvailableDaysJson, plan.IncludeBlockedScenes, model.ContingencyPercent, model.DraftingWordsPerHour, model.Capacity.Allocations }); model.ReviewFingerprint = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(reviewedInputs)); if (step == "save" && reviewed != model.ReviewFingerprint) ModelState.AddModelError(string.Empty, "Review the updated preview before saving."); if (step == "save" && reviewed == model.ReviewFingerprint && model.Capacity.Allocations.Count > 0) { var id = await planning.SaveNewSchedule(plan, model, model.Capacity.Allocations); TempData["SchedulePreviewMessage"] = "Writing schedule saved."; return RedirectToAction(nameof(SchedulePreview), new { writingPlanId = id }); } } } catch (Exception ex) when (ex is InvalidOperationException or ArgumentException) { ModelState.AddModelError(string.Empty, ex.Message); } catch (SqlException ex) when (ex.Number == 51020) { ModelState.AddModelError(string.Empty, "This work already has time allocated for the same activity in another active plan. Review existing schedules before saving."); } catch (SqlException ex) when (ex.Number is 51000 or 547 or 1205) { ModelState.AddModelError(string.Empty, "The schedule could not be saved. Check the selected work or return to your schedules before retrying."); } 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 (savedData is not null) await savedData.Chapter(model.ChapterID, "intent"); 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. } } }