PlotDirector/PlotLine/Controllers/WriterPlanningController.cs

135 lines
8.1 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Security.Claims;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Writer;
using PlotLine.ViewModels;
using System.Security.Cryptography;
using System.Text.Json;
namespace PlotLine.Controllers;
[Authorize,Route("Writer/PlanActivities")]
public sealed class WriterPlanningController(WriterPlanningRepository repository,IWritingScheduleService schedule):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Index(int writingPlanId)
{try
{
var model = await Load(writingPlanId);
return model.Plan.ContingencyPercent.HasValue
? RedirectToAction(nameof(Recalculate), new { writingPlanId })
: View(model);
}catch(InvalidOperationException){return NotFound();}catch(SqlException e)when(e.Number==51000){return NotFound();}}
[HttpPost,ValidateAntiForgeryToken,RequestFormLimits(ValueCountLimit=20000)]
public async Task<IActionResult> Index(WriterPlanningPage input)
{
WriterPlanningPage model;
try{model=await Load(input.WritingPlanID);}catch(InvalidOperationException){return NotFound();}catch(SqlException e)when(e.Number==51000){return NotFound();}
if (model.Plan.ContingencyPercent.HasValue) return RedirectToAction(nameof(Recalculate), new { writingPlanId = input.WritingPlanID });
try
{
if(!input.Confirm)throw new ArgumentException("Review the activity budgets and confirm before saving.");
var chosen=input.Candidates.Where(x=>x.Selected).ToArray();var selected=new List<WriterPlanActivity>();
foreach(var row in chosen){var actual=model.Candidates.SingleOrDefault(x=>x.ChapterID==row.ChapterID&&x.SceneID==row.SceneID);if(actual==null)throw new ArgumentException("A chapter or scene is no longer available. Reload the preview.");if(selected.Any(x=>x.ChapterID==row.ChapterID&&x.SceneID==row.SceneID))throw new ArgumentException("Choose each activity once.");actual.Minutes=row.Minutes;actual.Kind=row.Kind;selected.Add(actual);}
await repository.Save(Actor,input.WritingPlanID,WriterPlanning.Allocate(model.Plan,selected));
TempData["SchedulePreviewMessage"]="Reviewed activities were allocated within your saved availability.";
return RedirectToAction("SchedulePreview","Writer",new{writingPlanId=input.WritingPlanID});
}
catch(ArgumentException e){model.Error=e.Message;}
catch(SqlException e)when(e.Number==51000){model.Error="Activities changed or this plan already contains completed work. Reload, or create a plan for a new pass.";}
return View(model);
}
[HttpGet("Recalculate")]
public Task<IActionResult> Recalculate(int writingPlanId)
=> ReviewRecalculation(new() { WritingPlanID = writingPlanId }, null);
[HttpPost("Recalculate"), ValidateAntiForgeryToken]
public Task<IActionResult> Recalculate(WriterScheduleRecalculation model, string? step, int? authorUtcOffset)
=> ReviewRecalculation(model, step, authorUtcOffset);
private async Task<IActionResult> ReviewRecalculation(WriterScheduleRecalculation model, string? step,
int? authorUtcOffset = null)
{
model.Capacity = null;
var reviewed = model.ReviewFingerprint;
model.ReviewFingerprint = null;
try
{
var plan = await schedule.GetWritingPlanSettingsAsync(model.WritingPlanID);
if (!plan.ContingencyPercent.HasValue) return NotFound();
model.Plan = plan;
model.ContingencyPercent ??= plan.ContingencyPercent.Value;
var scheduleRows = await repository.Read(Actor, model.WritingPlanID);
var pending = scheduleRows.Where(row => row.Status == "Planned").ToArray();
model.PendingCount = pending.Length;
if (step is null || pending.Length == 0) return View(nameof(Recalculate), model);
if (authorUtcOffset is not (>= -840 and <= 840))
throw new ArgumentException("Set your local date using the online schedule page.");
var today = DateTime.UtcNow.AddMinutes(authorUtcOffset.Value).Date;
if (!ModelState.IsValid || !model.StartDate.HasValue || model.StartDate.Value.Date < today)
throw new ArgumentException("Choose today or a later date to schedule the remaining work.");
var start = model.StartDate.Value.Date;
model.Capacity = WriterPlanning.Review(new WritingScheduleSetupViewModel
{
StartDate = start, DeadlineDate = plan.DeadlineDate,
ContingencyPercent = model.ContingencyPercent.Value, WritingDayAvailability = plan.WritingDayAvailability
}, pending, minimumBudget: 1, completed: scheduleRows.Where(row => row.Status == "Done").ToArray());
model.OverlapDates = await repository.CapacityOverlap(Actor, model.WritingPlanID, model.Capacity.Allocations);
model.ReviewFingerprint = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
{
model.WritingPlanID, plan.ModifiedDateUtc, start, model.ContingencyPercent,
Pending = pending.Select(row => row.ActivityID),
model.Capacity.Allocations, model.OverlapDates
})));
if (step == "save" && model.Capacity.Allocations.Count > 0)
{
if (reviewed != model.ReviewFingerprint)
throw new ArgumentException("The schedule changed. Review the updated preview before saving.");
await repository.Recalculate(Actor, plan, start, pending, model.Capacity.Allocations, model.ContingencyPercent.Value);
TempData["SchedulePreviewMessage"] = "Remaining writing time recalculated.";
return RedirectToAction("SchedulePreview", "Writer", new { writingPlanId = model.WritingPlanID });
}
}
catch (InvalidOperationException) { return NotFound(); }
catch (ArgumentException ex) { ModelState.AddModelError(string.Empty, ex.Message); }
catch (SqlException ex) when (ex.Number == 51000)
{
if (model.Plan is null) return NotFound();
model.Capacity = null;
model.ReviewFingerprint = null;
ModelState.AddModelError(string.Empty, "Remaining work or plan settings changed. Preview again.");
}
ModelState.Remove(nameof(model.ReviewFingerprint));
return View(nameof(Recalculate), model);
}
[HttpPost("Complete"),ValidateAntiForgeryToken]
public async Task<IActionResult> Complete(int writingPlanId,int activityId)
{try{await repository.Complete(Actor,writingPlanId,activityId);return RedirectToAction("SchedulePreview","Writer",new{writingPlanId});}catch(SqlException e)when(e.Number==51000){return NotFound();}}
[HttpPost("Skip"), ValidateAntiForgeryToken]
public async Task<IActionResult> Skip(int writingPlanId, int activityId)
{
try
{
await repository.Complete(Actor, writingPlanId, activityId, skip: true);
return RedirectToAction("SchedulePreview", "Writer", new { writingPlanId });
}
catch (SqlException ex) when (ex.Number == 51000) { return NotFound(); }
}
private async Task<WriterPlanningPage> Load(int id)
{
var plan=await schedule.GetWritingPlanSettingsAsync(id);
var rows=(await repository.Read(Actor,id,"candidates")).ToList();
foreach(var row in rows){row.Minutes=WriterPlanning.StartingBudget(row.Words);row.Kind=plan.GoalType=="FirstDraft"?"Draft":plan.GoalType=="Revision"?"Edit":"Review";}
string? reason=null;
if(rows.Count==0){var context=await repository.Context(Actor,id);reason=context.Chapters==0?"There are no active chapters in this plan's scope. Add a chapter or choose a different book.":$"No unscheduled eligible scene remains: {context.Blocked} scenes are marked blocked and {context.ExistingTasks} already have manual tasks in this plan. Review the existing schedule, or change the blocked-scene setting in Edit availability / deadline.";}
return new(){WritingPlanID=id,Plan=plan,Candidates=rows,Scheduled=await repository.Read(Actor,id),EmptyReason=reason};
}
}