Guide Writer planning and preserve reviewed writing schedules

This commit is contained in:
Codex 2026-12-06 00:19:46 +00:00
parent a25c120048
commit 126888e5cb
45 changed files with 2003 additions and 111 deletions

View File

@ -22,12 +22,15 @@ internal static class ApplicationDomainBoundaryTests
}
foreach(var path in new[]{"/Projects","/Pricing/Checkout","/help/getting-started/first-book","/word-companion","/api/native-companion","/hubs/word-companion-follow","/problem-solver/workspace/characters"})
{var c=new DefaultHttpContext{RequestServices=services};c.Request.Path=path;pipeline(c).GetAwaiter().GetResult();Check(c.Response.StatusCode==204,"Preserve application route "+path);}
Check(new HomeController().Index() is RedirectToActionResult {ControllerName:"Projects",ActionName:"Index"},"Root lands on Projects");
var home = new HomeController();
Check(home.Index(null!, new PlotLine.Services.CurrentUserService(new HttpContextAccessor { HttpContext = new DefaultHttpContext() }),
null!, null!).GetAwaiter().GetResult() is RedirectToActionResult {ControllerName:"Projects",ActionName:"Index"},
"Anonymous root lands on Projects");
var http=new DefaultHttpContext();http.User=new ClaimsPrincipal(new ClaimsIdentity(new[]{new Claim(ClaimTypes.NameIdentifier,"1")},"Test"));
var controller=new AccountController(null!){ControllerContext=new(new ActionContext(http,new Microsoft.AspNetCore.Routing.RouteData(),new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor()))};controller.Url=new UrlHelper(controller.ControllerContext);
Check(controller.Login() is RedirectToActionResult {ControllerName:"Projects"},"Authenticated sign in opens Projects");
Check(controller.Login() is RedirectToActionResult {ControllerName:"Home"},"Authenticated sign in resolves the configured start page");
Check(controller.Login("/Books/Details/123") is LocalRedirectResult {Url:"/Books/Details/123"},"Safe deep link survives");
foreach(var url in new[]{"https://example.com/","//example.com/","/\\example.com/"})Check(controller.Login(url) is RedirectToActionResult {ControllerName:"Projects"},"Reject open redirect");
foreach(var url in new[]{"https://example.com/","//example.com/","/\\example.com/"})Check(controller.Login(url) is RedirectToActionResult {ControllerName:"Home"},"Reject open redirect");
var publication = Path.Combine(Path.GetTempPath(), "pd-help-publication-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(publication);
try

View File

@ -0,0 +1,129 @@
const assert = require('node:assert/strict');
const { open } = require('./dev-acceptance.cjs');
async function run() {
let session;
let step = 'fixture';
try {
session = await open();
const project = await session.project();
const book = await session.create('Books', '?projectId=' + project, {
BookTitle: 'Writer planning acceptance', BookNumber: 1
});
const chapters = [];
for (let index = 1; index <= 3; index++) {
chapters.push(await session.create('Chapters', '?bookId=' + book,
{ ChapterTitle: 'Chapter ' + index, ChapterNumber: index }));
}
const page = session.page;
const scope = `projectId=${project}&bookId=${book}`;
const groups = '/WriterGroups?bookId=' + book;
const schedules = '/Writer/WritingPlans?' + scope;
const create = '/Writer/ScheduleSetup?' + scope;
const button = name => page.getByRole('button', { name, exact: true });
step = 'multiple working groups and reload';
await session.goto(groups);
await page.locator('#Name').fill('Opening and ending');
await page.locator('#IsCurrent').check();
await page.locator(`input[name="ChapterIDs"][value="${chapters[0]}"]`).check();
await page.locator(`input[name="ChapterIDs"][value="${chapters[2]}"]`).check();
await button('Save working group').click();
await page.getByRole('link', { name: 'Schedule time for Opening and ending' }).waitFor();
await page.locator('#Name').fill('Middle');
await page.locator(`input[name="ChapterIDs"][value="${chapters[1]}"]`).check();
await button('Save working group').click();
await page.getByRole('link', { name: 'Edit Middle' }).waitFor();
await page.reload();
await page.getByRole('link', { name: 'Schedule time for Opening and ending' }).waitFor();
step = 'impossible capacity and cancellation';
await session.goto(create);
await page.locator('#PlanName').fill('Impossible cancelled plan');
const start = await page.locator('#StartDate').inputValue();
await page.locator('#DeadlineDate').fill(start);
const available = page.locator('input[type="checkbox"][name$=".IsAvailable"]');
for (const checkbox of await available.all()) await checkbox.check();
await button('Review activities').click();
await page.locator('input[type="checkbox"][name$=".Selected"]').first().check();
const selectedBudget = page.locator('input[name="Candidates[0].Minutes"]');
await selectedBudget.fill('1440');
await button('Preview schedule').click();
await page.getByText('The selected work exceeds usable time.', { exact: false }).waitFor();
assert.equal(await button('Save writing schedule').count(), 0);
await page.getByRole('link', { name: 'Cancel', exact: true }).click();
await session.goto(schedules);
assert.equal(await page.getByText('Impossible cancelled plan', { exact: true }).count(), 0);
step = 'persist group allocations and preserve completed work';
await session.goto(groups);
await page.getByRole('link', { name: 'Schedule time for Opening and ending' }).click();
await page.locator('#PlanName').fill('Reviewed group plan');
for (const checkbox of await available.all()) await checkbox.check();
await button('Review activities').click();
await page.locator('input[name="Candidates[0].Minutes"]').fill('100');
await button('Preview schedule').click();
await page.getByRole('heading', { name: 'Schedule preview', exact: true }).waitFor();
await assert.doesNotReject(() => button('Save writing schedule').click());
await page.waitForURL(url => url.pathname === '/Writer/SchedulePreview');
await page.reload();
await page.getByRole('heading', { name: 'Reviewed writing activities' }).waitFor();
await button('Mark complete').first().click();
await page.getByText('Done', { exact: true }).first().waitFor();
await page.getByRole('link', { name: 'Review or recalculate writing activities' }).click();
await button('Preview remaining work').click();
await button('Save revised allocations').click();
await page.waitForURL(url => url.pathname === '/Writer/SchedulePreview');
await page.reload();
await page.getByText('Done', { exact: true }).first().waitFor();
step = 'board drag across and reorder within a column';
await session.goto('/Writer/Plan?' + scope + '&view=board');
for (const title of ['First board activity', 'Second board activity']) {
await page.getByText('Add planned activity', { exact: true }).click();
await page.locator('details[open] [data-activity-save] input[name="Title"]').fill(title);
await button('Save activity').click();
await page.getByText(title, { exact: true }).first().waitFor();
}
const next = page.locator('[data-board-status="Next"]');
const doing = page.locator('[data-board-status="In progress"]');
await next.getByText('First board activity', { exact: true }).dragTo(doing.locator('h3'));
await doing.getByText('First board activity', { exact: true }).waitFor();
await next.getByText('Second board activity', { exact: true }).dragTo(doing.locator('h3'));
await doing.getByText('Second board activity', { exact: true }).waitFor();
await page.reload();
await doing.getByText('First board activity', { exact: true }).waitFor();
assert.deepEqual(await doing.locator('[data-board-handle]').allTextContents(),
['Second board activity', 'First board activity']);
step = 'map pasted notes and checklist to canonical chapter Intent';
await session.goto('/Writer/ImportIntent?bookId=' + book);
await page.locator('#Text').fill('# Opening\nFirst planning note\n\nChapter 3\n- Shared checklist item');
await button('Preview pasted intentions').click();
await page.locator('[name="Mappings[0].ChapterID"]').selectOption(String(chapters[0]));
await page.locator('[name="Mappings[1].ChapterID"]').selectOption(String(chapters[2]));
await page.locator('[name="Mappings[1].Mode"]').selectOption('checklist');
await button('Save chapter intentions').click();
await page.waitForURL('**/Writer/Write?*');
await session.close();
session = await open();
await session.goto(`/Writing/Context?${scope}&chapterId=${chapters[2]}&panel=intent&pinned=true`);
await session.page.getByText('Shared checklist item', { exact: true }).waitFor();
await session.goto(`/Writer/WritingPlans?${scope}`);
await session.page.getByText('Reviewed group plan', { exact: true }).waitFor();
console.log('PASS Writer planning groups, failure/cancellation, persistence, recalculation and canonical Intent');
} catch {
console.error('Writer planning acceptance failed at ' + step);
process.exitCode = 1;
} finally {
if (session) {
try { await session.cleanup(); }
finally { await session.close(); }
}
}
}
run().catch(() => {
console.error('Writer planning acceptance cleanup or fixture initialization failed.');
process.exitCode = 1;
});

View File

@ -17,6 +17,13 @@ internal static class ContextIntentTextTests
Reject(() => Parse(string.Join('\n', Enumerable.Repeat("- a", 201))));
Reject(() => Parse(new string(' ', 64_001)));
var chapters = ParseChapters("# Opening\r\nA summary\r\n- First beat\n\nChapter 4: Return\n1. Second beat");
Check(chapters.Select(chapter => chapter.Heading).SequenceEqual(["Opening", "Chapter 4: Return"]),
"Chapter headings split a paste without inferring chapter IDs.");
Check(chapters[0].Body.Contains("A summary") && Parse(chapters[1].Body).Single().Text == "Second beat",
"Notes retain prose and bullets can become checklist items.");
Reject(() => ParseChapters(string.Join('\n', Enumerable.Repeat("# Heading\n- item", 21))));
Entity[] library = [
new("character:1", "Mira Vale", ["Mira", "Captain"], ["Recorded scene appearance"]),
new("character:1", "Mira Vale", ["M. Vale"], ["Author plan"]),

View File

@ -28,6 +28,33 @@ internal static class WriterIntelligenceTests
Check(activities.Count==3&&activities.Sum(x=>x.Minutes)==180&&activities.Where(x=>x.ScheduledDate.Day==17).Sum(x=>x.Minutes)==60,"activities share daily capacity and split across dates without exceeding availability");
refused=false;try{WriterPlanning.Allocate(plan,[new(){Minutes=181}]);}catch(ArgumentException){refused=true;}Check(refused,"insufficient capacity explains failure before persistence");
Check(WriterPlanning.StartingBudget(1000)!=WriterPlanning.StartingBudget(10000),"known lengths produce distinct adjustable budgets rather than equal chapter effort");
var setup = new WritingScheduleSetupViewModel
{
StartDate = plan.StartDate, DeadlineDate = plan.DeadlineDate,
WritingDayAvailability = plan.WritingDayAvailability
};
var fits = WriterPlanning.Review(setup, [new() { Minutes = 144, Kind = "Draft" }]);
Check(fits.Available == 180 && fits.Reserved == 36 && fits.Usable == 144 &&
fits.Required == 144 && fits.Forecast == new DateTime(2026, 11, 17) &&
fits.Allocations.Sum(item => item.Minutes) == 144, "review reserves 20 percent before allocating and forecasts within the target");
var impossible = WriterPlanning.Review(setup, [new() { Minutes = 145 }]);
Check(impossible.Shortfall == 1 && impossible.Forecast is null && impossible.Allocations.Count == 0,
"insufficient usable time produces a shortfall without saveable allocations");
setup.ContingencyPercent = 50;
Check(WriterPlanning.Review(setup, [new() { Minutes = 90 }]).Usable == 90,
"changing contingency changes usable capacity and retains the target date");
setup.StartDate = plan.DeadlineDate;
Check(WriterPlanning.Review(setup, [new() { Minutes = 1 }], minimumBudget: 1).Allocations.Single().Minutes == 1,
"recalculation preserves small remaining allocation fragments");
Check(WriterPlanning.DraftingBudget(1500, 750) == 120 &&
WriterPlanning.DraftingBudget(1500, 1500) == 60, "drafting estimates use the author-selected rate");
var sameDay = WriterPlanning.Review(setup, [new() { GroupID = 9, Minutes = 20, Kind = "Draft" }],
completed: [new() { ScheduledDate = setup.StartDate, Minutes = 15, Status = "Done" }]);
Check(sameDay.AlreadyAllocated == 15 && sameDay.Usable == 15 && sameDay.Shortfall == 5,
"recalculation deducts completed allocation from available time on the same date");
var grouped = WriterPlanning.Review(setup, [new() { BookID = 2, GroupID = 9, Minutes = 25, Kind = "Draft" }]);
Check(grouped.Allocations.Single() is { GroupID: 9, ChapterID: null, SceneID: null },
"group capacity is saved as a group allocation without picking a chapter");
var provider=new WriterSuggestionProvider();Check(provider.Suggest(new()).Count==0,"empty context produces no invented manuscript observations");
var model=new WriterDashboardViewModel{BookID=2,Book=new(){ChapterCount=3},ObjectiveChoices=[new(){ChapterID=12,ChapterTitle="Actual chapter"}],RevisionQueue=[new(){SceneID=22,SceneTitle="Actual scene"}],Activity=new(){Totals=new(){Added=2000,Removed=2000}}};
var suggestions=provider.Suggest(model);Check(suggestions.Any(x=>x.Key=="changes")&&suggestions.Any(x=>x.Key=="listen")&&suggestions.Count<=4,"zero-net revision and actual chapter evidence supply bounded actionable suggestions");

View File

@ -53,7 +53,7 @@ public sealed class AccountController(IAuthService authService,PlotLine.Services
{
return !string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)
? LocalRedirect(returnUrl)
: RedirectToAction("Index", "Projects");
: RedirectToAction("Index", "Home");
}
return View(new LoginViewModel { ReturnUrl = returnUrl, IsCompanionLogin = IsCompanionLogin(returnUrl, companion) });
}
@ -87,7 +87,7 @@ public sealed class AccountController(IAuthService authService,PlotLine.Services
return LocalRedirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Projects");
return RedirectToAction("Index", "Home");
}
private static bool IsCompanionLogin(string? returnUrl, bool explicitCompanion)
@ -285,7 +285,7 @@ public sealed class AccountController(IAuthService authService,PlotLine.Services
return LocalRedirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Projects");
return RedirectToAction("Index", "Home");
}
[HttpGet]
@ -330,6 +330,6 @@ public sealed class AccountController(IAuthService authService,PlotLine.Services
return LocalRedirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Projects");
return RedirectToAction("Index", "Home");
}
}

View File

@ -3,18 +3,58 @@ using Microsoft.AspNetCore.Authorization;
using PlotLine.Models;
using PlotLine.Services;
using System.Diagnostics;
using PlotLine.Data;
namespace PlotLine.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
[AllowAnonymous]
[HttpGet("/", Name = PublicRouteNames.Home)]
public IActionResult Index()
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public async Task<IActionResult> Index([FromServices] ApplicationStartup startup,
[FromServices] ICurrentUserService user, [FromServices] IProjectRepository projects,
[FromServices] IBookRepository books)
{
return RedirectToAction("Index", "Projects");
if (user.UserId is not int userId)
return RedirectToAction("Index", "Projects");
var choice = startup.ReadChoice(HttpContext, userId);
if (choice == ApplicationStartup.Projects)
return RedirectToAction("Index", "Projects");
var recent = startup.ReadRecent(HttpContext, userId);
var project = recent != null ? await projects.GetForUserAsync(recent.ProjectID, userId) : null;
project ??= (await projects.ListForUserAsync(userId)).FirstOrDefault();
if (project is null) return RedirectToAction("Index", "Projects");
var page = choice == ApplicationStartup.Resume ? recent?.Page ?? "writer" : choice;
var destination = ApplicationStartup.Resolve(page);
if (destination is null) return RedirectToAction("Index", "Projects");
var projectBooks = (await books.ListByProjectAsync(project.ProjectID)).Where(book => !book.IsArchived).ToArray();
var book = projectBooks.FirstOrDefault(book => book.BookID == recent?.BookID) ?? projectBooks.FirstOrDefault();
return destination.ProjectAsId
? RedirectToAction(destination.Action, destination.Controller, new { id = project.ProjectID })
: RedirectToAction(destination.Action, destination.Controller,
new { projectId = project.ProjectID, bookId = book?.BookID });
}
[Authorize, HttpGet("Startup")]
public IActionResult Startup([FromServices] ApplicationStartup startup, [FromServices] ICurrentUserService user)
=> user.UserId is int id ? View(startup.ReadChoice(HttpContext, id)) : Challenge();
[Authorize, HttpPost("Startup"), ValidateAntiForgeryToken]
public IActionResult Startup(string page, [FromServices] ApplicationStartup startup,
[FromServices] ICurrentUserService user)
{
if (user.UserId is not int id) return Challenge();
if (!ApplicationStartup.Destinations.ContainsKey(page ?? "")) return BadRequest();
startup.SaveChoice(HttpContext, id, page!);
return RedirectToAction(nameof(Index));
}
[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{

View File

@ -16,6 +16,16 @@ public sealed class WriterActivitiesController(WriterActivityRepository activiti
[HttpPost,ValidateAntiForgeryToken]public Task<IActionResult> 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<IActionResult> MoveOnBoard(int bookId, Guid id, int version, string status, Guid? beforeId)
=> Guard(async () =>
{
if (!ModelState.IsValid || id == Guid.Empty || !WriterActivity.Statuses.Contains(status))
return BadRequest();
await activities.MoveOnBoard(Actor, bookId, id, version, status, beforeId);
return Ok();
});
[HttpPost,ValidateAntiForgeryToken]public Task<IActionResult> 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."});

View File

@ -5,6 +5,8 @@ using PlotLine.ViewModels;
using PlotLine.Data;
using System.Security.Claims;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
using PlotLine.Services.Writer;
namespace PlotLine.Controllers;
@ -115,7 +117,17 @@ public sealed class WriterController(
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 (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);
@ -266,7 +278,7 @@ public sealed class WriterController(
return View(nameof(SchedulePreview), model);
}
public async Task<IActionResult> ScheduleSetup(int? projectId, int? bookId = null, string? focusActivity = null)
public async Task<IActionResult> ScheduleSetup(int? projectId, int? bookId = null, string? focusActivity = null, int? workingGroupId = null)
{
if (bookId.HasValue && bookRepository != null)
{
@ -277,6 +289,12 @@ public sealed class WriterController(
}
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";
@ -286,19 +304,10 @@ public sealed class WriterController(
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ScheduleSetup(WritingScheduleSetupViewModel model)
[RequestFormLimits(ValueCountLimit = 20000)]
public async Task<IActionResult> ScheduleSetup(WritingScheduleSetupViewModel model, string? step)
{
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 (planning is null) return StatusCode(503);
if (!ModelState.IsValid)
{
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
@ -307,25 +316,92 @@ public sealed class WriterController(
try
{
var result = await writingSchedule.CreateScheduleFromSetupAsync(model);
if (string.IsNullOrWhiteSpace(result.ValidationMessage))
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)
{
TempData["SchedulePreviewMessage"] = $"Writing plan created. {result.GeneratedItemCount} item{(result.GeneratedItemCount == 1 ? "" : "s")} generated.";
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
}];
}
else
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)
{
TempData["SchedulePreviewError"] = result.ValidationMessage;
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(result.GeneratedItemCount==0){TempData.Remove("SchedulePreviewMessage");return RedirectToAction("Index","WriterPlanning",new{writingPlanId=result.WritingPlanID});}
return RedirectToAction(nameof(SchedulePreview), new { writingPlanId = result.WritingPlanID });
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 (InvalidOperationException ex)
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
{
ModelState.AddModelError(string.Empty, ex.Message);
await writingSchedule.PopulateScheduleSetupOptionsAsync(model);
return View(model);
}
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]

View File

@ -0,0 +1,77 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Controllers;
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class WriterGroupsController(WriterPlanningRepository planning, IChapterRepository chapters) : Controller
{
private int Actor => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
public sealed class GroupPage
{
public int BookID { get; set; }
public int GroupID { get; set; }
[Required, StringLength(200)] public string Name { get; set; } = "";
public bool IsCurrent { get; set; }
public int[] ChapterIDs { get; set; } = [];
public IReadOnlyList<WriterWorkingGroup> Groups { get; set; } = [];
public IReadOnlyList<Chapter> Chapters { get; set; } = [];
}
[HttpGet]
public async Task<IActionResult> Index(int bookId, int? groupId)
{
try
{
var model = new GroupPage { BookID = bookId };
await Populate(model);
if (groupId.HasValue)
{
var group = model.Groups.SingleOrDefault(row => row.GroupID == groupId);
if (group is null) return NotFound();
model.GroupID = group.GroupID;
model.Name = group.Name;
model.IsCurrent = group.IsCurrent;
model.ChapterIDs = group.ChapterIDs.ToArray();
}
return View(model);
}
catch (SqlException ex) when (ex.Number == 51000) { return NotFound(); }
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Index(GroupPage model)
{
try { await Populate(model); }
catch (SqlException ex) when (ex.Number == 51000) { return NotFound(); }
if (model.ChapterIDs.Length == 0)
ModelState.AddModelError(nameof(model.ChapterIDs), "Choose at least one chapter.");
if (!ModelState.IsValid) return View(model);
try
{
await planning.SaveWorkingGroup(Actor, model.BookID, model.GroupID, model.Name.Trim(),
model.IsCurrent, model.ChapterIDs);
TempData["WriterWorkspaceMessage"] = "Working group saved.";
return RedirectToAction(nameof(Index), new { bookId = model.BookID });
}
catch (SqlException ex) when (ex.Number == 51000)
{
ModelState.AddModelError(string.Empty, "The group or selected chapters are no longer available.");
return View(model);
}
}
private async Task Populate(GroupPage model)
{
model.Groups = await planning.WorkingGroups(Actor, model.BookID);
model.Chapters = (await chapters.ListByBookAsync(model.BookID)).Where(chapter => !chapter.IsArchived).ToArray();
}
}

View File

@ -0,0 +1,73 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize]
[Route("Writer/ImportIntent")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class WriterIntentImportController(
IProjectAccessService access, IChapterRepository chapters, ContextIntentChecklist intent) : Controller
{
public sealed class ImportPage
{
public int BookID { get; set; }
public string? Text { get; set; }
public List<Mapping> Mappings { get; set; } = [];
public IReadOnlyList<Chapter> Chapters { get; set; } = [];
public IReadOnlyList<ContextIntentText.ChapterPasteSection> Sections { get; set; } = [];
}
public sealed record Mapping(int ChapterID, string? Mode);
[HttpGet]
public async Task<IActionResult> Index(int bookId)
{
if (!await access.CanAccessEntityAsync("Book", bookId)) return NotFound();
return View(new ImportPage { BookID = bookId });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ImportPage model, string? step)
{
if (!await access.CanAccessEntityAsync("Book", model.BookID)) return NotFound();
model.Chapters = (await chapters.ListByBookAsync(model.BookID)).Where(chapter => !chapter.IsArchived).ToArray();
try
{
model.Sections = ContextIntentText.ParseChapters(model.Text ?? "");
if (step != "save")
{
model.Mappings = model.Sections.Select(_ => new Mapping(0, "notes")).ToList();
ModelState.Clear();
return View(model);
}
if (!ModelState.IsValid || model.Mappings.Count != model.Sections.Count ||
model.Mappings.Any(row => row.Mode is not ("notes" or "checklist")
|| !model.Chapters.Any(chapter => chapter.ChapterID == row.ChapterID)))
throw new ArgumentException("Map every pasted section to an existing chapter and choose how to save it.");
var imports = model.Sections.Zip(model.Mappings, (section, mapping) =>
new ContextIntentChecklist.ChapterImport(mapping.ChapterID, section, mapping.Mode == "checklist")).ToArray();
await intent.AppendChapters(model.BookID, imports);
TempData["WriterWorkspaceMessage"] = "Pasted intentions added to the selected chapters.";
return RedirectToAction("Write", "Writer", new { bookId = model.BookID });
}
catch (ArgumentException ex) { ModelState.AddModelError(string.Empty, ex.Message); }
catch (InvalidOperationException ex) { ModelState.AddModelError(string.Empty, ex.Message); }
catch (UnauthorizedAccessException) { return Forbid(); }
catch (SqlException ex) when (ex.Number is 51010 or 51011 or 51012)
{
ModelState.AddModelError(string.Empty, "Intent changed or is unavailable. Review the mappings and try again.");
}
if (model.Mappings.Count != model.Sections.Count)
model.Mappings = model.Sections.Select(_ => new Mapping(0, "notes")).ToList();
return View(model);
}
}

View File

@ -6,6 +6,9 @@ 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
@ -13,12 +16,19 @@ public sealed class WriterPlanningController(WriterPlanningRepository repository
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Index(int writingPlanId)
{try{return View(await Load(writingPlanId));}catch(InvalidOperationException){return NotFound();}catch(SqlException e)when(e.Number==51000){return NotFound();}}
{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.");
@ -32,9 +42,86 @@ public sealed class WriterPlanningController(WriterPlanningRepository repository
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);

View File

@ -7,4 +7,11 @@ public sealed class WriterActivityRepository(ISqlConnectionFactory factory)
public async Task<IReadOnlyList<WriterActivity>> Read(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<WriterActivity>("dbo.WriterActivities_Manage",new{Action="read",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task<IReadOnlyList<WriterActivityEntity>> Entities(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<WriterActivityEntity>("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);}
public async Task MoveOnBoard(int userId, int bookId, Guid id, int version, string status, Guid? beforeId)
{
using var connection = factory.CreateConnection();
await connection.ExecuteAsync("dbo.WriterActivities_MoveOnBoard",
new { UserID = userId, BookID = bookId, ID = id, Version = version, Status = status, BeforeID = beforeId },
commandType: CommandType.StoredProcedure);
}
}

View File

@ -2,17 +2,123 @@ using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Data;
public sealed class WriterPlanningRepository(ISqlConnectionFactory factory)
{
private sealed record GroupRow(int GroupID, string Name, bool IsCurrent, int? ChapterID);
public async Task<IReadOnlyList<WriterWorkingGroup>> WorkingGroups(int userId, int bookId)
{
using var connection = factory.CreateConnection();
var rows = await connection.QueryAsync<GroupRow>("dbo.WriterWorkingGroups_Manage",
new { UserID = userId, BookID = bookId }, commandType: CommandType.StoredProcedure);
return rows.GroupBy(row => (row.GroupID, row.Name, row.IsCurrent))
.Select(group => new WriterWorkingGroup(group.Key.GroupID, group.Key.Name, group.Key.IsCurrent,
group.Where(row => row.ChapterID.HasValue).Select(row => row.ChapterID!.Value).ToArray()))
.ToArray();
}
public async Task SaveWorkingGroup(int userId, int bookId, int groupId, string name, bool isCurrent, int[] chapters)
{
using var connection = factory.CreateConnection();
await connection.ExecuteAsync("dbo.WriterWorkingGroups_Manage",
new { UserID = userId, BookID = bookId, GroupID = groupId, Name = name, IsCurrent = isCurrent,
Chapters = JsonSerializer.Serialize(chapters) }, commandType: CommandType.StoredProcedure);
}
public async Task<List<WriterPlanActivity>> ReviewCandidates(WritingPlanViewModel plan)
{
using var connection = factory.CreateConnection();
return (await connection.QueryAsync<WriterPlanActivity>("dbo.WriterScheduleReviewCandidates",
new { plan.UserID, plan.ProjectID, plan.BookID, plan.IncludeBlockedScenes },
commandType: CommandType.StoredProcedure)).AsList();
}
public async Task<int> SaveNewSchedule(WritingPlanViewModel plan, WritingScheduleSetupViewModel setup,
IReadOnlyList<WriterPlanActivity> allocations)
{
using var connection = factory.CreateConnection();
connection.Open();
using var transaction = connection.BeginTransaction();
var existing = await connection.QuerySingleAsync<int?>("dbo.WriterScheduleFindSaved", new
{
plan.UserID, setup.CreationToken, CreationFingerprint = setup.ReviewFingerprint
}, transaction, commandType: CommandType.StoredProcedure);
if (existing.HasValue)
{
transaction.Commit();
return existing.Value;
}
var id = await connection.QuerySingleAsync<int>("dbo.CreateWritingPlan", new
{
plan.UserID, plan.ProjectID, plan.BookID, plan.PlanName, plan.GoalType,
plan.StartDate, plan.DeadlineDate, plan.AvailableDaysJson, plan.SessionLengthMinutes,
plan.IncludeBlockedScenes, plan.RebalanceMode, plan.IsActive
}, transaction, commandType: CommandType.StoredProcedure);
await connection.ExecuteAsync("dbo.WriterScheduleSaveReviewSettings", new
{
plan.UserID, WritingPlanID = id, setup.ContingencyPercent, setup.DraftingWordsPerHour,
setup.CreationToken, CreationFingerprint = setup.ReviewFingerprint
}, transaction, commandType: CommandType.StoredProcedure);
await connection.ExecuteAsync("dbo.WriterPlanning", new
{
Action = "save", plan.UserID, WritingPlanID = id, Items = JsonSerializer.Serialize(allocations)
}, transaction, commandType: CommandType.StoredProcedure);
transaction.Commit();
return id;
}
public async Task Recalculate(int userId, WritingPlanSettingsEditViewModel plan, DateTime start,
IReadOnlyList<WriterPlanActivity> pending, IReadOnlyList<WriterPlanActivity> allocations, int contingencyPercent)
{
using var connection = factory.CreateConnection();
var parameters = new DynamicParameters(new
{
UserID = userId, plan.WritingPlanID, ContingencyPercent = contingencyPercent,
StartDate = start, ExpectedPending = JsonSerializer.Serialize(pending.Select(row => row.ActivityID)),
Allocations = JsonSerializer.Serialize(allocations)
});
parameters.Add("ExpectedModifiedUtc", plan.ModifiedDateUtc, DbType.DateTime2);
await connection.ExecuteAsync("dbo.WriterScheduleRecalculate", parameters, commandType: CommandType.StoredProcedure);
}
public async Task<int?> ObservedDraftingRate(int userId, int bookId)
{
using var connection = factory.CreateConnection();
return await connection.QuerySingleAsync<int?>("dbo.WriterScheduleObservedDrafting",
new { UserID = userId, BookID = bookId }, commandType: CommandType.StoredProcedure);
}
public async Task<IReadOnlyList<WriterScheduleDailyFocus>> DailyFocus(int userId, int bookId)
{
using var connection = factory.CreateConnection();
return (await connection.QueryAsync<WriterScheduleDailyFocus>("dbo.WriterScheduleDailyFocus",
new { UserID = userId, BookID = bookId, UtcDate = DateTime.UtcNow.Date },
commandType: CommandType.StoredProcedure)).AsList();
}
public async Task<IReadOnlyList<DateTime>> CapacityOverlap(int userId, int? planId,
IReadOnlyList<WriterPlanActivity> allocations)
{
if (allocations.Count == 0) return [];
using var connection = factory.CreateConnection();
var dates = allocations.Select(row => DateOnly.FromDateTime(row.ScheduledDate)).Distinct();
return (await connection.QueryAsync<DateTime>("dbo.WriterScheduleCapacityOverlap",
new { UserID = userId, WritingPlanID = planId, Dates = JsonSerializer.Serialize(dates) },
commandType: CommandType.StoredProcedure)).AsList();
}
public async Task<IReadOnlyList<WriterPlanActivity>> Read(int user,int plan,string action="list")
{using var db=factory.CreateConnection();return(await db.QueryAsync<WriterPlanActivity>("dbo.WriterPlanning",new{Action=action,UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task<WriterPlanningContext> Context(int user,int plan)
{using var db=factory.CreateConnection();return await db.QuerySingleAsync<WriterPlanningContext>("dbo.WriterPlanning",new{Action="context",UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure);}
public async Task Save(int user,int plan,IReadOnlyList<WriterPlanActivity> items)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action="save",UserID=user,WritingPlanID=plan,Items=JsonSerializer.Serialize(items)},commandType:CommandType.StoredProcedure);}
public async Task Complete(int user,int plan,int activity)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action="complete",UserID=user,WritingPlanID=plan,ActivityID=activity},commandType:CommandType.StoredProcedure);}
public async Task Complete(int user,int plan,int activity,bool skip=false)
{using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action=skip?"skip":"complete",UserID=user,WritingPlanID=plan,ActivityID=activity},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<WriterPlanActivity>> Upcoming(int user,int book)
{using var db=factory.CreateConnection();return(await db.QueryAsync<WriterPlanActivity>("dbo.WriterPlanningUpcoming",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
}

View File

@ -2326,6 +2326,9 @@ public sealed class WriterDashboardScene
public sealed class WritingPlan
{
public DateTime? OriginalTargetDate { get; set; }
public int? ContingencyPercent { get; set; }
public int? DraftingWordsPerHour { get; set; }
public int WritingPlanID { get; set; }
public int UserID { get; set; }
public int ProjectID { get; set; }

View File

@ -3,7 +3,8 @@ public sealed class WriterPlanActivity
{
public int ActivityID { get; set; }
public int BookID { get; set; }
public int ChapterID { get; set; }
public int? ChapterID { get; set; }
public int? GroupID { get; set; }
public int? SceneID { get; set; }
public string Title { get; set; } = "";
public string BookTitle { get; set; } = "";
@ -29,3 +30,23 @@ public sealed class WriterPlanningPage
}
public sealed class WriterPlanningContext { public int Chapters { get; set; } public int Scenes { get; set; } public int Blocked { get; set; } public int ExistingTasks { get; set; } }
public sealed class WriterScheduleRecalculation
{
public int WritingPlanID { get; set; }
public DateTime? StartDate { get; set; }
[System.ComponentModel.DataAnnotations.Range(1, 99)]
public int? ContingencyPercent { get; set; }
public string? ReviewFingerprint { get; set; }
public IReadOnlyList<DateTime> OverlapDates { get; set; } = [];
public PlotLine.ViewModels.WritingPlanSettingsEditViewModel? Plan { get; set; }
public PlotLine.Services.Writer.WriterCapacityPreview? Capacity { get; set; }
public int PendingCount { get; set; }
}
public sealed record WriterWorkingGroup(int GroupID, string Name, bool IsCurrent, IReadOnlyList<int> ChapterIDs);
public sealed record WriterScheduleDailyFocus(DateTime ScheduledDate, int Minutes, decimal SuggestedWords);

View File

@ -164,6 +164,7 @@ public class Program
builder.Services.AddScoped<IFeatureRequestRepository, FeatureRequestRepository>();
builder.Services.AddScoped<IProjectRepository, ProjectRepository>();
builder.Services.AddScoped<ApplicationNavigation>();
builder.Services.AddScoped<ApplicationStartup>();
builder.Services.AddScoped<IWritingSolverRepository, WritingSolverRepository>();
builder.Services.AddScoped<PlotLine.Data.IInvestigationRepository,PlotLine.Data.InvestigationRepository>();
builder.Services.AddScoped<PlotLine.Data.IInvestigationGuidanceRepository,PlotLine.Data.InvestigationGuidanceRepository>();

View File

@ -6,7 +6,7 @@ namespace PlotLine.Services;
// Request-scoped: existing project partials register their already-authorised context
// while the body renders, before the shared layout renders the application menu.
public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepository books, ICurrentUserService currentUser, INarrativeFocus? narrativeFocus = null)
public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepository books, ICurrentUserService currentUser, INarrativeFocus? narrativeFocus = null, ApplicationStartup? startup = null)
{
public Project? Project { get; set; }
@ -55,6 +55,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo
result.Project = project;
result.Books = projectBooks.Where(x => !x.IsArchived).ToList();
result.Book = result.Books.FirstOrDefault(x => x.BookID == selectedBookId);
startup?.Remember(request.HttpContext, userId, project.ProjectID, result.Book?.BookID);
if (narrativeFocus != null && result.Book is {} selectedBook)
result.NarrativeFocus = await narrativeFocus.Read(userId, project.ProjectID, selectedBook.BookID);
if(result.Book is null && request.HttpContext.Items["NarrativeFocus.Navigation"] is NarrativeFocusState opened && opened.ProjectID==project.ProjectID && result.Books.Any(b=>b.BookID==opened.BookID))

View File

@ -0,0 +1,72 @@
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
namespace PlotLine.Services;
public sealed class ApplicationStartup(IDataProtectionProvider protection)
{
public sealed record Destination(string Label, string Controller, string Action, bool ProjectAsId = false);
public sealed record Recent(string Page, int ProjectID, int? BookID);
public const string Projects = "projects";
public const string Resume = "resume";
public static readonly IReadOnlyDictionary<string, Destination> Destinations = new Dictionary<string, Destination>
{
[Projects] = new("Projects", "Projects", "Index"),
["overview"] = new("Project Overview", "Projects", "Details", ProjectAsId: true),
["timeline"] = new("Timeline", "Timeline", "Index"),
["plotlines"] = new("Plotlines", "PlotLineWorkspace", "Index"),
["writer"] = new("Writer Home", "Writer", "Index"),
[Resume] = new("Where I left off", "Home", "Index")
};
private static readonly IReadOnlyDictionary<string, Destination> WriterDestinations = new Dictionary<string, Destination>
{
["write"] = new("Write", "Writer", "Write"),
["plan"] = new("Plan", "Writer", "Plan"),
["explore"] = new("Explore", "Writer", "Explore"),
["review"] = new("Review", "Writer", "Review"),
["reflect"] = new("Reflect", "Writer", "Reflect")
};
public static Destination? Resolve(string page) => Destinations.GetValueOrDefault(page) ?? WriterDestinations.GetValueOrDefault(page);
public string ReadChoice(HttpContext context, int userId)
=> Read<string>(context, userId, "choice") is { } page && Destinations.ContainsKey(page) ? page : Projects;
public void SaveChoice(HttpContext context, int userId, string choice)
=> Write(context, userId, "choice", choice);
public Recent? ReadRecent(HttpContext context, int userId) => Read<Recent>(context, userId, "recent");
public void Remember(HttpContext context, int userId, int projectId, int? bookId)
{
if (!HttpMethods.IsGet(context.Request.Method) || context.Response.HasStarted) return;
var controller = context.Request.RouteValues["controller"]?.ToString();
var action = context.Request.RouteValues["action"]?.ToString();
var page = Destinations.Concat(WriterDestinations).FirstOrDefault(pair =>
pair.Value.Controller == controller && pair.Value.Action == action).Key;
if (page is null or Projects or Resume) return;
var recent = new Recent(page, projectId, bookId);
if (recent != ReadRecent(context, userId)) Write(context, userId, "recent", recent);
}
private T? Read<T>(HttpContext context, int userId, string key)
{
if (!context.Request.Cookies.TryGetValue(CookieName(userId, key), out var value)) return default;
try { return JsonSerializer.Deserialize<T>(Protector(userId, key).Unprotect(value)); }
catch (Exception ex) when (ex is CryptographicException or JsonException) { return default; }
}
private void Write<T>(HttpContext context, int userId, string key, T value) =>
context.Response.Cookies.Append(CookieName(userId, key), Protector(userId, key).Protect(JsonSerializer.Serialize(value)),
new CookieOptions { HttpOnly = true, Secure = context.Request.IsHttps, SameSite = SameSiteMode.Lax,
MaxAge = TimeSpan.FromDays(365), Path = "/" });
private IDataProtector Protector(int userId, string key) =>
protection.CreateProtector("PlotDirector.ApplicationStartup.v1", userId.ToString(), key);
private static string CookieName(int userId, string key) => $"pd-start-{userId}-{key}";
}

View File

@ -147,7 +147,49 @@ public sealed class ContextIntentChecklist(ISqlConnectionFactory connections, IC
catch (JsonException) { return false; }
}
public async Task<IntentChecklistFrame> Load(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save = null)
public sealed record ChapterImport(int ChapterID, ContextIntentText.ChapterPasteSection Section, bool Checklist);
public async Task AppendChapters(int bookId, IReadOnlyList<ChapterImport> imports)
{
var author = user.UserId ?? throw new UnauthorizedAccessException();
var changed = new List<(int ChapterID, int ProjectID)>();
using (var scope = new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Required,
new System.Transactions.TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
System.Transactions.TransactionScopeAsyncFlowOption.Enabled))
{
foreach (var import in imports.OrderBy(row => row.ChapterID))
{
var frame = await Load(bookId, import.ChapterID, null);
if (!frame.CanEdit) throw new UnauthorizedAccessException();
if (import.Checklist)
{
var added = ContextIntentText.Parse(import.Section.Body)
.Select(row => new IntentChecklistItem(null, row.Text, false, false, null));
var save = new IntentChecklistSave(bookId, import.ChapterID, null,
frame.Version, frame.Items.Concat(added).ToArray());
await LoadCore(bookId, import.ChapterID, null, save, notify: false);
}
else
{
using var connection = connections.CreateConnection();
await connection.ExecuteAsync("dbo.ContextIntent_AppendChapterNotes", new
{
UserID = author, BookID = bookId, import.ChapterID, Notes = import.Section.Body
}, commandType: CommandType.StoredProcedure);
}
changed.Add((import.ChapterID, frame.ProjectID));
}
scope.Complete();
}
foreach (var entry in changed.Distinct())
await notifications.Invalidate(author, bookId, entry.ChapterID, null, entry.ProjectID, kind: "intent");
}
public Task<IntentChecklistFrame> Load(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save = null)
=> LoadCore(bookId, chapterId, sceneId, save, notify: true);
private async Task<IntentChecklistFrame> LoadCore(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save, bool notify)
{
ContextIntentPalette.Validate(new(bookId, chapterId, sceneId));
var author = user.UserId ?? throw new UnauthorizedAccessException();
@ -209,7 +251,7 @@ public sealed class ContextIntentChecklist(ISqlConnectionFactory connections, IC
ExpectedVersion = save?.Version, Items = items, ManuscriptRevision = manuscriptRevision },
commandType: CommandType.StoredProcedure);
if (save is not null)
if (save is not null && notify)
await notifications.Invalidate(author, bookId, chapterId, sceneId, state.ProjectID, kind: "intent");
return new(state.ProjectID, state.CanEdit, state.Version, state.Objective, state.Outcome,

View File

@ -41,6 +41,42 @@ public static partial class ContextIntentText
return result;
}
public sealed record ChapterPasteSection(string Heading, string Body);
[GeneratedRegex(@"^\s*(?:#{1,6}\s+(?<heading>.+)|(?<heading>Chapter\s+.+?))\s*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex ChapterHeading();
public static IReadOnlyList<ChapterPasteSection> ParseChapters(string input)
{
if (input.Length > 64_000) throw new ArgumentException("Paste 64,000 characters or fewer.");
var sections = new List<ChapterPasteSection>();
var heading = "Untitled section";
var body = new System.Text.StringBuilder();
foreach (var line in input.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'))
{
var match = ChapterHeading().Match(line);
if (match.Success)
{
AddSection();
heading = match.Groups["heading"].Value;
body.Clear();
}
else
body.AppendLine(line);
}
AddSection();
if (sections.Count is < 1 or > 20)
throw new ArgumentException("Paste between one and twenty sections with content.");
return sections;
void AddSection()
{
if (body.ToString().Trim() is { Length: > 0 } text)
sections.Add(new(heading, text));
}
}
// Keys are supplied from authorised canonical identities or persisted candidate IDs.
// Equal labels never merge identities. Repeated appearances of one identity do.
public static IReadOnlyList<Entity> Deduplicate(IEnumerable<Entity> entities)

View File

@ -619,7 +619,7 @@ public interface IWritingScheduleService
Task<IReadOnlyList<WritingScheduleItemViewModel>> RegenerateScheduleAsync(int writingPlanId);
Task<WritingScheduleSetupViewModel> GetScheduleSetupAsync(int? projectId);
Task PopulateScheduleSetupOptionsAsync(WritingScheduleSetupViewModel model);
Task<WritingScheduleSetupResult> CreateScheduleFromSetupAsync(WritingScheduleSetupViewModel model);
Task<WritingPlanViewModel> PrepareScheduleFromSetupAsync(WritingScheduleSetupViewModel model);
Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null, int? bookId = null);
Task<bool> MarkScheduleItemCompleteAsync(int writingScheduleItemId);
Task<bool> SkipScheduleItemAsync(int writingScheduleItemId);
@ -6518,6 +6518,10 @@ public sealed class WritingScheduleService(
var model = new WritingPlanSettingsEditViewModel
{
ContingencyPercent = plan.ContingencyPercent,
OriginalTargetDate = plan.OriginalTargetDate,
DraftingWordsPerHour = plan.DraftingWordsPerHour,
ModifiedDateUtc = plan.ModifiedDateUtc,
WritingPlanID = plan.WritingPlanID,
ProjectID = plan.ProjectID, BookID = plan.BookID,
PlanName = plan.PlanName,
@ -6638,7 +6642,7 @@ public sealed class WritingScheduleService(
}
}
public async Task<WritingScheduleSetupResult> CreateScheduleFromSetupAsync(WritingScheduleSetupViewModel model)
public async Task<WritingPlanViewModel> PrepareScheduleFromSetupAsync(WritingScheduleSetupViewModel model)
{
if (!currentUser.UserId.HasValue)
{
@ -6667,7 +6671,11 @@ public sealed class WritingScheduleService(
}
}
var planId = await CreateWritingPlanAsync(new WritingPlanViewModel
model.WritingDayAvailability = BuildWritingDayAvailabilityInputs(availability, model.SessionLengthMinutes).ToList();
if (model.GoalType is not ("FirstDraft" or "Revision" or "BetaReady" or "Custom"))
throw new InvalidOperationException("Choose a valid type of work.");
return new WritingPlanViewModel
{
UserID = currentUser.UserId.Value,
ProjectID = model.ProjectID!.Value,
@ -6681,10 +6689,7 @@ public sealed class WritingScheduleService(
IncludeBlockedScenes = model.IncludeBlockedScenes,
RebalanceMode = model.RebalanceMode,
IsActive = true
});
// Availability is saved first; chapters/scenes and budgets are reviewed before allocation.
return new WritingScheduleSetupResult { WritingPlanID = planId, GeneratedItemCount = 0 };
};
}
public async Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null, int? bookId = null)

View File

@ -1,29 +1,131 @@
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Writer;
public sealed record WriterCapacityPreview(int Available, int Reserved, int Required,
int Shortfall, DateTime? Forecast, IReadOnlyList<WriterPlanActivity> Allocations)
{
public int AlreadyAllocated { get; init; }
public int Usable => Available - Reserved - AlreadyAllocated;
}
public static class WriterPlanning
{
public static IReadOnlyList<WriterPlanActivity> Allocate(WritingPlanSettingsEditViewModel plan,IReadOnlyList<WriterPlanActivity> selected)
{
if(selected.Count==0)throw new ArgumentException("Select at least one chapter or scene. Add a chapter to the selected book if none exists.");
if(plan.DeadlineDate.Date<plan.StartDate.Date||(plan.DeadlineDate-plan.StartDate).TotalDays>3650)throw new ArgumentException("Choose a planning window of at most ten years.");
var availability=plan.WritingDayAvailability.Where(x=>x.IsAvailable).ToDictionary(x=>Enum.Parse<DayOfWeek>(x.Day),x=>x.Minutes);
if(availability.Count==0||availability.Values.Any(x=>x is <1 or >720))throw new ArgumentException("Choose valid writing availability.");
var result=new List<WriterPlanActivity>();var date=plan.StartDate.Date;var used=0;
foreach(var candidate in selected)
{
if(candidate.Minutes is <5 or >1440)throw new ArgumentException("Choose a working budget between 5 and 1,440 minutes for each activity.");
if(candidate.Kind is not("Draft" or "Edit" or "Plan" or "Review" or "AudioReview"))throw new ArgumentException("Choose a supported activity.");
var remaining=candidate.Minutes;
while(remaining>0)
{
while(date<=plan.DeadlineDate.Date&&(!availability.TryGetValue(date.DayOfWeek,out var capacity)||used>=capacity)){date=date.AddDays(1);used=0;}
if(date>plan.DeadlineDate.Date)throw new ArgumentException("Selected working budgets exceed the available time before your deadline. Reduce budgets, deselect activities, extend the deadline or edit availability. No schedule was changed.");
var minutes=Math.Min(remaining,availability[date.DayOfWeek]-used);remaining-=minutes;used+=minutes;
result.Add(new(){BookID=candidate.BookID,ChapterID=candidate.ChapterID,SceneID=candidate.SceneID,Title=candidate.Title,BookTitle=candidate.BookTitle,Minutes=minutes,ScheduledDate=date,Kind=candidate.Kind});
}
}
return result;
}
public static int StartingBudget(int? words)=>words is >0?Math.Clamp((int)Math.Ceiling(words.Value/200d/5)*5,5,120):30;
private sealed record DayCapacity(DateTime Date, int Available, int Reserved, int AlreadyAllocated)
{
public int Usable => Available - Reserved - AlreadyAllocated;
}
public static WriterCapacityPreview Review(WritingScheduleSetupViewModel setup,
IReadOnlyList<WriterPlanActivity> selected, int minimumBudget = 5,
IReadOnlyList<WriterPlanActivity>? completed = null)
{
if (setup.ContingencyPercent is < 1 or > 99)
throw new ArgumentException("Choose contingency between 1 and 99 percent.");
var dates = Capacity(setup.StartDate, setup.DeadlineDate,
setup.WritingDayAvailability, setup.ContingencyPercent, completed ?? []);
ValidateBudgets(selected, minimumBudget);
var required = selected.Sum(item => item.Minutes);
var shortfall = Math.Max(0, required - dates.Sum(date => date.Usable));
var allocations = selected.Count > 0 && shortfall == 0 ? Fit(dates, selected) : [];
return new(dates.Sum(date => date.Available), dates.Sum(date => date.Reserved),
required, shortfall, allocations.LastOrDefault()?.ScheduledDate, allocations)
{
AlreadyAllocated = dates.Sum(date => date.AlreadyAllocated)
};
}
public static IReadOnlyList<WriterPlanActivity> Allocate(WritingPlanSettingsEditViewModel plan,
IReadOnlyList<WriterPlanActivity> selected)
{
if (selected.Count == 0)
throw new ArgumentException("Select at least one chapter or scene.");
ValidateBudgets(selected, minimumBudget: 5);
var dates = Capacity(plan.StartDate, plan.DeadlineDate, plan.WritingDayAvailability, 0, []);
if (dates.Sum(date => date.Usable) < selected.Sum(item => item.Minutes))
throw new ArgumentException("The selected budgets exceed available time before the target. Reduce budgets or edit availability. The saved schedule is unchanged.");
return Fit(dates, selected);
}
public static int DraftingBudget(int words, int wordsPerHour)
=> (int)Math.Clamp(Math.Ceiling(words * 60m / wordsPerHour), 5, int.MaxValue);
public static int StartingBudget(int? words)
=> words is > 0 ? Math.Clamp((int)Math.Ceiling(words.Value / 200d / 5) * 5, 5, 120) : 30;
private static IReadOnlyList<DayCapacity> Capacity(DateTime start, DateTime target,
IReadOnlyList<WritingDayAvailabilityViewModel> days, int contingency, IReadOnlyList<WriterPlanActivity> completed)
{
var length = (target.Date - start.Date).Days + 1;
if (length < 1) throw new ArgumentException("The target date is before the proposed start. Choose another start or explicitly edit the target date.");
if (length > 3651) throw new ArgumentException("Choose a planning window of at most ten years.");
var enabled = days.Where(day => day.IsAvailable).ToArray();
if (enabled.Length == 0 || enabled.Any(day =>
!Enum.TryParse<DayOfWeek>(day.Day, out var weekday) || weekday.ToString() != day.Day || day.Minutes is < 1 or > 720)
|| enabled.Select(day => day.Day).Distinct().Count() != enabled.Length)
throw new ArgumentException("Choose valid weekly writing availability.");
var availability = enabled.ToDictionary(day => Enum.Parse<DayOfWeek>(day.Day), day => day.Minutes);
var completedByDay = completed.GroupBy(item => item.ScheduledDate.Date)
.ToDictionary(group => group.Key, group => group.Sum(item => item.Minutes));
var dates = new List<DayCapacity>(length);
var totalAvailable = 0;
var totalReserved = 0;
for (var offset = 0; offset < length; offset++)
{
var date = start.Date.AddDays(offset);
var available = availability.GetValueOrDefault(date.DayOfWeek);
totalAvailable += available;
var targetReserve = (int)Math.Ceiling(totalAvailable * contingency / 100m);
var reserved = targetReserve - totalReserved;
totalReserved = targetReserve;
var occupied = Math.Min(available - reserved, completedByDay.GetValueOrDefault(date));
dates.Add(new(date, available, reserved, occupied));
}
return dates;
}
private static void ValidateBudgets(IReadOnlyList<WriterPlanActivity> work, int minimumBudget)
{
if (work.Any(item => item.Minutes < minimumBudget || item.Minutes > 1440))
throw new ArgumentException($"Enter a budget between {minimumBudget} and 1,440 minutes for each selected activity.");
if (work.Any(item => item.Kind is not ("Draft" or "Edit" or "Plan" or "Review" or "AudioReview")))
throw new ArgumentException("Choose a supported activity.");
}
private static List<WriterPlanActivity> Fit(IReadOnlyList<DayCapacity> dates, IReadOnlyList<WriterPlanActivity> work)
{
var usable = dates.Where(date => date.Usable > 0).ToArray();
var result = new List<WriterPlanActivity>();
var day = 0;
var used = 0;
foreach (var candidate in work)
{
var remaining = candidate.Minutes;
while (remaining > 0)
{
var capacity = usable[day];
var minutes = Math.Min(remaining, capacity.Usable - used);
result.Add(new()
{
BookID = candidate.BookID, ChapterID = candidate.ChapterID, SceneID = candidate.SceneID,
GroupID = candidate.GroupID, Title = candidate.Title, BookTitle = candidate.BookTitle,
Minutes = minutes, ScheduledDate = capacity.Date, Kind = candidate.Kind
});
remaining -= minutes;
used += minutes;
if (used == capacity.Usable)
{
day++;
used = 0;
}
}
}
return result;
}
}

View File

@ -37,7 +37,7 @@ public static class WriterNavigation
{
"Write" => new RibbonGroup("Current work", new("Chapters","bible","Books","Details","book"), new("Scene queues","threads","Writer","Workspaces","writerBook"), new("Writing Dashboard","metrics","Writer","Dashboard","writerBook"), new("Writing Plan","calendar","Writer","WritingPlans","writerBook")),
"Explore" => new RibbonGroup("Story exploration", new("Guided investigation","point","Writer","Explore","writerBook"), new("Story overview","timeline","Timeline","Index","writerBook")),
"Plan" => new RibbonGroup("Writing plans", new("Writing Plan","calendar","Writer","WritingPlans","writerBook"), new("Schedule Preview","calendar","Writer","SchedulePreview","writerBook")),
"Plan" => new RibbonGroup("Writing plans", new("Writing Plan","calendar","Writer","WritingPlans","writerBook"), new("Schedule Preview","calendar","Writer","SchedulePreview","writerBook"), new("Create Writing Schedule","calendar","Writer","ScheduleSetup","writerBook")),
"Review" => new RibbonGroup("Writing tools", new RibbonCommand("Writing Dashboard","metrics","Writer","Dashboard","writerBook")),
"Reflect" => new RibbonGroup("Writing history", new RibbonCommand("Reports","metrics","WritingActivity","Index","writerBook",OwnerOnly:true)),
_ => new RibbonGroup("Your writing", new RibbonCommand("Writing Dashboard","metrics","Writer","Dashboard","writerBook"))

View File

@ -0,0 +1,198 @@
IF COL_LENGTH('dbo.WritingPlans', 'ContingencyPercent') IS NULL
ALTER TABLE dbo.WritingPlans ADD ContingencyPercent int NULL
CHECK (ContingencyPercent BETWEEN 1 AND 99);
IF COL_LENGTH('dbo.WritingPlans', 'DraftingWordsPerHour') IS NULL
ALTER TABLE dbo.WritingPlans ADD DraftingWordsPerHour int NULL
CHECK (DraftingWordsPerHour > 0);
IF COL_LENGTH('dbo.WritingPlans', 'OriginalTargetDate') IS NULL
ALTER TABLE dbo.WritingPlans ADD OriginalTargetDate date NULL;
IF COL_LENGTH('dbo.WritingPlans', 'CreationToken') IS NULL
ALTER TABLE dbo.WritingPlans ADD CreationToken uniqueidentifier NULL, CreationFingerprint char(64) NULL;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleReviewCandidates
@UserID int, @ProjectID int, @BookID int = NULL, @IncludeBlockedScenes bit
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess
WHERE UserID = @UserID AND ProjectID = @ProjectID AND IsActive = 1)
THROW 51000, 'Project access denied', 1;
SELECT TOP (1000) b.BookID, c.ChapterID, s.SceneID, b.BookTitle,
COALESCE(s.SceneTitle, c.ChapterTitle) AS Title,
CASE WHEN sw.EstimatedWordCount >= COALESCE(sw.ActualWordCount, 0)
THEN sw.EstimatedWordCount - COALESCE(sw.ActualWordCount, 0)
WHEN sw.EstimatedWordCount IS NOT NULL THEN 0 END AS Words
FROM dbo.Books b
JOIN dbo.Chapters c ON c.BookID = b.BookID AND c.IsArchived = 0
LEFT JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID AND s.IsArchived = 0
LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID = s.SceneID
WHERE b.ProjectID = @ProjectID AND b.IsArchived = 0
AND (@BookID IS NULL OR b.BookID = @BookID)
AND (@IncludeBlockedScenes = 1 OR COALESCE(sw.IsBlocked, 0) = 0)
ORDER BY b.SortOrder, b.BookID, c.SortOrder, c.ChapterID, s.SortOrder, s.SceneID;
END;
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.WritingPlans') AND name = 'UX_WritingPlans_CreationToken')
CREATE UNIQUE INDEX UX_WritingPlans_CreationToken ON dbo.WritingPlans(UserID, CreationToken) WHERE CreationToken IS NOT NULL;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleFindSaved
@UserID int, @CreationToken uniqueidentifier, @CreationFingerprint char(64)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ID int, @ExistingFingerprint char(64);
SELECT @ID = WritingPlanID, @ExistingFingerprint = CreationFingerprint
FROM dbo.WritingPlans WITH (UPDLOCK, HOLDLOCK)
WHERE UserID = @UserID AND CreationToken = @CreationToken;
IF @ID IS NOT NULL AND @ExistingFingerprint <> @CreationFingerprint
THROW 51000, 'This form already saved a schedule. Start a new schedule to make another one.', 1;
SELECT @ID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleSaveReviewSettings
@UserID int, @WritingPlanID int, @ContingencyPercent int, @DraftingWordsPerHour int,
@CreationToken uniqueidentifier, @CreationFingerprint char(64)
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.WritingPlans
SET ContingencyPercent = @ContingencyPercent, DraftingWordsPerHour = @DraftingWordsPerHour,
OriginalTargetDate = COALESCE(OriginalTargetDate, DeadlineDate),
CreationToken = @CreationToken, CreationFingerprint = @CreationFingerprint
WHERE WritingPlanID = @WritingPlanID AND UserID = @UserID;
IF @@ROWCOUNT <> 1 THROW 51000, 'Plan access denied', 1;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterActivities_MoveOnBoard
@UserID int, @BookID int, @ID uniqueidentifier, @Version int,
@Status varchar(20), @BeforeID uniqueidentifier = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF NOT EXISTS (
SELECT 1 FROM dbo.Books b
JOIN dbo.ProjectUserAccess a ON a.ProjectID = b.ProjectID
WHERE b.BookID = @BookID AND b.IsArchived = 0 AND a.UserID = @UserID AND a.IsActive = 1)
THROW 51000, 'Book access unavailable', 1;
DECLARE @Order TABLE (ID uniqueidentifier PRIMARY KEY, Position int, Status varchar(20), Version int);
INSERT @Order
SELECT ID, ROW_NUMBER() OVER (ORDER BY SortOrder, CreatedUtc, ID), Status, Version
FROM dbo.WriterActivities WITH (UPDLOCK, HOLDLOCK)
WHERE UserID = @UserID AND BookID = @BookID AND IsArchived = 0;
IF @Status NOT IN ('Next', 'In progress', 'Completed', 'Deferred')
THROW 51000, 'Invalid status', 1;
IF NOT EXISTS (SELECT 1 FROM @Order WHERE ID = @ID AND Version = @Version)
THROW 51002, 'Activity changed; reload before retrying', 1;
IF @BeforeID IS NOT NULL AND
(@ID = @BeforeID OR NOT EXISTS (SELECT 1 FROM @Order WHERE ID = @BeforeID AND Status = @Status))
THROW 51002, 'Destination changed; reload before retrying', 1;
DECLARE @BeforePosition int = (SELECT Position FROM @Order WHERE ID = @BeforeID);
IF @BeforePosition IS NULL
SELECT @BeforePosition = COALESCE(MAX(Position), 0) + 1 FROM @Order;
UPDATE @Order SET Position = Position * 2;
UPDATE @Order SET Position = @BeforePosition * 2 - 1, Status = @Status WHERE ID = @ID;
;WITH Reordered AS
(
SELECT ID, Status, ROW_NUMBER() OVER (ORDER BY Position) * 10 AS SortOrder
FROM @Order
)
UPDATE a SET SortOrder = o.SortOrder, Status = o.Status,
Version = a.Version + 1, UpdatedUtc = SYSUTCDATETIME()
FROM dbo.WriterActivities a JOIN Reordered o ON o.ID = a.ID
WHERE a.SortOrder <> o.SortOrder OR a.Status <> o.Status;
COMMIT TRANSACTION;
END;
GO
CREATE OR ALTER PROCEDURE dbo.GetWritingPlanByID
@WritingPlanID int
AS
BEGIN
SET NOCOUNT ON;
SELECT WritingPlanID, UserID, ProjectID, BookID, PlanName, GoalType, StartDate, DeadlineDate,
AvailableDaysJson, SessionLengthMinutes, IncludeBlockedScenes, RebalanceMode, IsActive,
CreatedDateUtc, ModifiedDateUtc, ContingencyPercent, DraftingWordsPerHour, OriginalTargetDate
FROM dbo.WritingPlans
WHERE WritingPlanID = @WritingPlanID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleCapacityOverlap
@UserID int, @Dates nvarchar(max), @WritingPlanID int = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT dateList.ScheduledDate
FROM OPENJSON(@Dates) WITH (ScheduledDate date '$') dateList
WHERE EXISTS (
SELECT 1
FROM dbo.WritingPlans p
JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
WHERE p.UserID = @UserID AND p.IsActive = 1
AND (@WritingPlanID IS NULL OR p.WritingPlanID <> @WritingPlanID)
AND (EXISTS (SELECT 1 FROM dbo.WriterPlannedActivities r
WHERE r.WritingPlanID = p.WritingPlanID AND r.ScheduledDate = dateList.ScheduledDate AND r.Status = 'Planned')
OR EXISTS (SELECT 1 FROM dbo.WritingScheduleItems r
WHERE r.WritingPlanID = p.WritingPlanID AND r.ScheduledDate = dateList.ScheduledDate AND r.ScheduleStatus = 'Planned'))
)
ORDER BY dateList.ScheduledDate;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextIntent_AppendChapterNotes
@UserID int, @BookID int, @ChapterID int, @Notes nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF NOT EXISTS (
SELECT 1 FROM dbo.Chapters c WITH (HOLDLOCK)
JOIN dbo.Books b WITH (HOLDLOCK) ON b.BookID = c.BookID AND b.IsArchived = 0
JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
JOIN dbo.ProjectUserAccess a WITH (HOLDLOCK) ON a.ProjectID = p.ProjectID
WHERE c.ChapterID = @ChapterID AND b.BookID = @BookID AND c.IsArchived = 0
AND a.UserID = @UserID AND a.IsActive = 1 AND a.AccessRole IN ('Owner', 'Collaborator'))
THROW 51010, 'This Intent scope is unavailable.', 1;
UPDATE dbo.ChapterGoals WITH (UPDLOCK, HOLDLOCK)
SET GoalSummary = CONCAT(NULLIF(GoalSummary, ''),
CASE WHEN NULLIF(GoalSummary, '') IS NOT NULL THEN NCHAR(10) + NCHAR(10) END, @Notes),
UpdatedDate = SYSUTCDATETIME()
WHERE ChapterID = @ChapterID;
IF @@ROWCOUNT = 0
INSERT dbo.ChapterGoals (ChapterID, GoalSummary) VALUES (@ChapterID, @Notes);
COMMIT TRANSACTION;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleObservedDrafting
@UserID int, @BookID int
AS
BEGIN
SET NOCOUNT ON;
SELECT CONVERT(int, ROUND(SUM(CONVERT(decimal(28, 4), measured.NetWords)) * 3600 /
NULLIF(SUM(CONVERT(bigint, measured.EngagedSeconds)), 0), 0))
FROM (
SELECT TOP (50) s.EngagedSeconds, words.NetWords
FROM dbo.WriterWorkSessions s
JOIN dbo.Books b ON b.BookID = s.BookID AND b.IsArchived = 0
JOIN dbo.ProjectUserAccess a ON a.ProjectID = b.ProjectID AND a.UserID = s.UserID
AND a.IsActive = 1 AND a.AccessRole = 'Owner'
CROSS APPLY (
SELECT SUM(CONVERT(bigint, e.Added) - e.Removed) AS NetWords
FROM dbo.WritingActivityEvents e
WHERE e.SessionID = s.SessionID AND e.BookID = s.BookID AND e.UserID = s.UserID
AND e.Kind = 'Change' AND e.Provenance = 'Observed'
AND e.ReceivedUtc BETWEEN s.StartedUtc AND s.EndedUtc
) words
WHERE s.UserID = @UserID AND s.BookID = @BookID AND s.Kind = 'Writing'
AND s.EndedUtc IS NOT NULL AND s.EngagedSeconds >= 600 AND words.NetWords > 0
ORDER BY s.EndedUtc DESC, s.SessionID
) measured;
END;
GO

View File

@ -0,0 +1,243 @@
IF OBJECT_ID('dbo.WriterWorkingGroups', 'U') IS NULL
BEGIN
CREATE TABLE dbo.WriterWorkingGroups (
GroupID int IDENTITY PRIMARY KEY,
UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,
BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,
Name nvarchar(200) NOT NULL,
IsCurrent bit NOT NULL DEFAULT 0
);
CREATE UNIQUE INDEX UX_WriterWorkingGroups_Current ON dbo.WriterWorkingGroups(UserID, BookID) WHERE IsCurrent = 1;
CREATE TABLE dbo.WriterWorkingGroupChapters (
GroupID int NOT NULL REFERENCES dbo.WriterWorkingGroups(GroupID) ON DELETE CASCADE,
ChapterID int NOT NULL,
CONSTRAINT PK_WriterWorkingGroupChapters PRIMARY KEY (GroupID, ChapterID)
);
END;
IF COL_LENGTH('dbo.WriterPlannedActivities', 'GroupID') IS NULL
BEGIN
ALTER TABLE dbo.WriterPlannedActivities DROP CONSTRAINT FK_WriterPlanned_Chapter;
ALTER TABLE dbo.WriterPlannedActivities ALTER COLUMN ChapterID int NULL;
ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT FK_WriterPlanned_Chapter
FOREIGN KEY (ChapterID) REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE;
ALTER TABLE dbo.WriterPlannedActivities ADD GroupID int NULL;
END;
GO
IF OBJECT_ID('dbo.CK_WriterPlannedActivities_WorkScope', 'C') IS NULL
BEGIN
ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT CK_WriterPlannedActivities_WorkScope
CHECK ((GroupID IS NULL AND ChapterID IS NOT NULL) OR
(GroupID IS NOT NULL AND ChapterID IS NULL AND SceneID IS NULL));
END;
IF OBJECT_ID('dbo.CK_WriterPlannedActivities_Status', 'C') IS NULL
BEGIN
DECLARE @OldStatusConstraint sysname = (
SELECT name FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID('dbo.WriterPlannedActivities')
AND parent_column_id = COLUMNPROPERTY(OBJECT_ID('dbo.WriterPlannedActivities'), 'Status', 'ColumnId'));
IF @OldStatusConstraint IS NOT NULL
EXEC (N'ALTER TABLE dbo.WriterPlannedActivities DROP CONSTRAINT ' + QUOTENAME(@OldStatusConstraint));
ALTER TABLE dbo.WriterPlannedActivities ADD CONSTRAINT CK_WriterPlannedActivities_Status
CHECK (Status IN ('Planned', 'Done', 'Skipped'));
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterWorkingGroups_Manage
@UserID int, @BookID int, @GroupID int = 0, @Name nvarchar(200) = NULL,
@IsCurrent bit = 0, @Chapters nvarchar(max) = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF NOT EXISTS (
SELECT 1 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)
THROW 51000, 'Book access unavailable', 1;
IF @Name IS NULL
BEGIN
SELECT g.GroupID, g.Name, g.IsCurrent, c.ChapterID
FROM dbo.WriterWorkingGroups g
LEFT JOIN dbo.WriterWorkingGroupChapters gc ON gc.GroupID = g.GroupID
LEFT JOIN dbo.Chapters c ON c.ChapterID = gc.ChapterID AND c.BookID = g.BookID AND c.IsArchived = 0
WHERE g.UserID = @UserID AND g.BookID = @BookID
ORDER BY g.IsCurrent DESC, g.Name, g.GroupID, c.SortOrder, c.ChapterID;
RETURN;
END;
BEGIN TRANSACTION;
DECLARE @Lock int;
SELECT @Lock = GroupID FROM dbo.WriterWorkingGroups WITH (UPDLOCK, HOLDLOCK)
WHERE UserID = @UserID AND BookID = @BookID;
DECLARE @Members TABLE (ChapterID int PRIMARY KEY);
INSERT @Members SELECT DISTINCT TRY_CONVERT(int, value) FROM OPENJSON(@Chapters)
WHERE TRY_CONVERT(int, value) IS NOT NULL;
IF LEN(TRIM(@Name)) = 0 OR NOT EXISTS (SELECT 1 FROM @Members) OR EXISTS (
SELECT 1 FROM @Members m LEFT JOIN dbo.Chapters c ON c.ChapterID = m.ChapterID
WHERE c.ChapterID IS NULL OR c.BookID <> @BookID OR c.IsArchived = 1)
THROW 51000, 'Choose existing chapters in this book', 1;
IF @GroupID <> 0 AND NOT EXISTS (
SELECT 1 FROM dbo.WriterWorkingGroups WHERE GroupID = @GroupID AND UserID = @UserID AND BookID = @BookID)
THROW 51000, 'Group access unavailable', 1;
IF @IsCurrent = 1
UPDATE dbo.WriterWorkingGroups SET IsCurrent = 0 WHERE UserID = @UserID AND BookID = @BookID AND IsCurrent = 1;
IF @GroupID = 0
BEGIN
INSERT dbo.WriterWorkingGroups (UserID, BookID, Name, IsCurrent)
VALUES (@UserID, @BookID, @Name, @IsCurrent);
SET @GroupID = CONVERT(int, SCOPE_IDENTITY());
END;
ELSE
UPDATE dbo.WriterWorkingGroups SET Name = @Name, IsCurrent = @IsCurrent WHERE GroupID = @GroupID;
DELETE dbo.WriterWorkingGroupChapters WHERE GroupID = @GroupID;
INSERT dbo.WriterWorkingGroupChapters (GroupID, ChapterID)
SELECT @GroupID, ChapterID FROM @Members;
COMMIT TRANSACTION;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterPlanning @Action varchar(20),@UserID int,@WritingPlanID int,@Items nvarchar(max)=NULL,@ActivityID int=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @project int,@book int,@start date,@end date,@blocked bit;
SELECT @project=p.ProjectID,@book=p.BookID,@start=p.StartDate,@end=p.DeadlineDate,@blocked=p.IncludeBlockedScenes FROM dbo.WritingPlans p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE p.WritingPlanID=@WritingPlanID AND p.UserID=@UserID;
IF @project IS NULL THROW 51000,'Plan access denied',1;
IF @Action='context'
BEGIN
SELECT COUNT(DISTINCT c.ChapterID) Chapters,COUNT(s.SceneID) Scenes,COALESCE(SUM(CASE WHEN sw.IsBlocked=1 THEN 1 ELSE 0 END),0) Blocked,
COALESCE(SUM(CASE WHEN scheduled.SceneID IS NOT NULL THEN 1 ELSE 0 END),0) ExistingTasks
FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=s.SceneID
LEFT JOIN(SELECT DISTINCT SceneID FROM dbo.WritingScheduleItems WHERE WritingPlanID=@WritingPlanID) scheduled ON scheduled.SceneID=s.SceneID
WHERE b.ProjectID=@project AND b.IsArchived=0 AND (@book IS NULL OR b.BookID=@book);RETURN;
END;
IF @Action='candidates'
BEGIN
SELECT TOP(1000) b.BookID,c.ChapterID,s.SceneID,COALESCE(s.SceneTitle,c.ChapterTitle) Title,b.BookTitle,rs.StatusName RevisionStatus,sw.EstimatedWordCount Words
FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=s.SceneID LEFT JOIN dbo.RevisionStatuses rs ON rs.RevisionStatusID=COALESCE(s.RevisionStatusID,c.RevisionStatusID)
WHERE b.ProjectID=@project AND b.IsArchived=0 AND (@book IS NULL OR b.BookID=@book) AND (@blocked=1 OR COALESCE(sw.IsBlocked,0)=0)
AND NOT EXISTS(SELECT 1 FROM dbo.WritingScheduleItems existing WHERE existing.WritingPlanID=@WritingPlanID AND existing.SceneID=s.SceneID)
ORDER BY COALESCE(sw.Priority,0) DESC,b.SortOrder,c.SortOrder,s.SortOrder,c.ChapterID,s.SceneID;
RETURN;
END;
IF @Action='list'
BEGIN
SELECT a.*,COALESCE(g.Name,s.SceneTitle,c.ChapterTitle) Title,b.BookTitle FROM dbo.WriterPlannedActivities a JOIN dbo.Books b ON b.BookID=a.BookID AND b.IsArchived=0 LEFT JOIN dbo.WriterWorkingGroups g ON g.GroupID=a.GroupID AND g.BookID=b.BookID AND g.UserID=@UserID LEFT JOIN dbo.Chapters c ON c.ChapterID=a.ChapterID AND c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.SceneID=a.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0 WHERE a.WritingPlanID=@WritingPlanID AND ((a.GroupID IS NOT NULL AND g.GroupID IS NOT NULL) OR (c.ChapterID IS NOT NULL AND (a.SceneID IS NULL OR s.SceneID IS NOT NULL))) ORDER BY a.ScheduledDate,a.ActivityID;RETURN;
END;
IF @Action IN ('complete','skip') BEGIN UPDATE dbo.WriterPlannedActivities SET Status=CASE WHEN @Action='skip' THEN 'Skipped' ELSE 'Done' END WHERE WritingPlanID=@WritingPlanID AND ActivityID=@ActivityID AND Status='Planned';RETURN;END;
IF @Action<>'save' OR ISJSON(@Items)<>1 THROW 51000,'Invalid planned activities',1;
DECLARE @rows TABLE(BookID int,ChapterID int,SceneID int,GroupID int,Kind varchar(20),Minutes int,ScheduledDate date);
INSERT @rows SELECT BookID,ChapterID,SceneID,GroupID,Kind,Minutes,ScheduledDate FROM OPENJSON(@Items) WITH(BookID int,ChapterID int,SceneID int,GroupID int,Kind varchar(20),Minutes int,ScheduledDate date);
IF NOT EXISTS(SELECT 1 FROM @rows) OR (SELECT COUNT(*) FROM @rows)>20000 THROW 51000,'Choose activities',1;
IF EXISTS(SELECT 1 FROM @rows r LEFT JOIN dbo.Books b ON b.BookID=r.BookID LEFT JOIN dbo.Chapters c ON c.ChapterID=r.ChapterID LEFT JOIN dbo.Scenes s ON s.SceneID=r.SceneID LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID=r.SceneID LEFT JOIN dbo.WriterWorkingGroups g ON g.GroupID=r.GroupID AND g.BookID=b.BookID AND g.UserID=@UserID
WHERE b.ProjectID<>@project OR b.BookID IS NULL OR b.IsArchived=1 OR (@book IS NOT NULL AND r.BookID<>@book) OR (r.GroupID IS NULL AND (c.ChapterID IS NULL OR c.BookID<>b.BookID OR c.IsArchived=1))
OR (r.GroupID IS NOT NULL AND (g.GroupID IS NULL OR r.ChapterID IS NOT NULL OR r.SceneID IS NOT NULL
OR NOT EXISTS (SELECT 1 FROM dbo.WriterWorkingGroupChapters m JOIN dbo.Chapters mc ON mc.ChapterID=m.ChapterID
WHERE m.GroupID=r.GroupID AND mc.BookID=r.BookID AND mc.IsArchived=0))) OR (r.SceneID IS NOT NULL AND (s.SceneID IS NULL OR s.ChapterID<>c.ChapterID OR s.IsArchived=1)) OR (@blocked=0 AND COALESCE(sw.IsBlocked,0)=1) OR r.Kind IS NULL OR r.Kind NOT IN('Draft','Edit','Plan','Review','AudioReview') OR r.Minutes IS NULL OR r.Minutes NOT BETWEEN 1 AND 1440 OR r.ScheduledDate IS NULL OR r.ScheduledDate NOT BETWEEN @start AND @end) THROW 51000,'Activities no longer match this plan',1;
BEGIN TRANSACTION;
DECLARE @locked int;SELECT @locked=WritingPlanID FROM dbo.WritingPlans WITH(UPDLOCK,HOLDLOCK) WHERE WritingPlanID=@WritingPlanID;
IF EXISTS(SELECT 1 FROM dbo.WriterPlannedActivities WHERE WritingPlanID=@WritingPlanID AND Status IN ('Done','Skipped')) THROW 51000,'Completed activities are preserved; create a new plan for another pass',1;
IF EXISTS (SELECT 1 FROM dbo.WritingPlans WHERE WritingPlanID = @WritingPlanID AND ContingencyPercent IS NOT NULL)
AND EXISTS (
SELECT 1 FROM @rows requested
JOIN dbo.WritingPlans other WITH (UPDLOCK, HOLDLOCK) ON other.UserID=@UserID AND other.IsActive=1
AND other.WritingPlanID<>@WritingPlanID
JOIN dbo.WriterPlannedActivities existing ON existing.WritingPlanID=other.WritingPlanID
AND existing.BookID=requested.BookID AND existing.Status='Planned' AND existing.Kind=requested.Kind
WHERE (requested.ChapterID=existing.ChapterID AND
(requested.SceneID IS NULL OR existing.SceneID IS NULL OR requested.SceneID=existing.SceneID))
OR requested.GroupID=existing.GroupID
OR EXISTS (
SELECT 1 FROM dbo.WriterWorkingGroupChapters m
WHERE m.GroupID=requested.GroupID AND
(m.ChapterID=existing.ChapterID OR EXISTS (
SELECT 1 FROM dbo.WriterWorkingGroupChapters n
WHERE n.GroupID=existing.GroupID AND n.ChapterID=m.ChapterID)))
OR EXISTS (
SELECT 1 FROM dbo.WriterWorkingGroupChapters m
WHERE m.GroupID=existing.GroupID AND m.ChapterID=requested.ChapterID)
) THROW 51020, 'This work is already allocated in another active writing plan.', 1;
DELETE dbo.WriterPlannedActivities WHERE WritingPlanID=@WritingPlanID;
INSERT dbo.WriterPlannedActivities(WritingPlanID,BookID,ChapterID,SceneID,GroupID,Kind,Minutes,ScheduledDate) SELECT @WritingPlanID,BookID,ChapterID,SceneID,GroupID,Kind,Minutes,ScheduledDate FROM @rows;
COMMIT;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterPlanningUpcoming @UserID int,@BookID int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book access denied',1;
SELECT TOP(10) a.*,COALESCE(g.Name,s.SceneTitle,c.ChapterTitle) Title,b.BookTitle FROM dbo.WriterPlannedActivities a JOIN dbo.WritingPlans p ON p.WritingPlanID=a.WritingPlanID AND p.UserID=@UserID AND p.IsActive=1 JOIN dbo.Books b ON b.BookID=a.BookID AND b.IsArchived=0 LEFT JOIN dbo.WriterWorkingGroups g ON g.GroupID=a.GroupID AND g.BookID=b.BookID AND g.UserID=@UserID LEFT JOIN dbo.Chapters c ON c.ChapterID=a.ChapterID AND c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.SceneID=a.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0 WHERE a.BookID=@BookID AND a.Status='Planned' AND ((a.GroupID IS NOT NULL AND g.GroupID IS NOT NULL) OR (c.ChapterID IS NOT NULL AND (a.SceneID IS NULL OR s.SceneID IS NOT NULL))) ORDER BY a.ScheduledDate,a.ActivityID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleRecalculate
@UserID int, @WritingPlanID int, @ExpectedModifiedUtc datetime2, @StartDate date,
@ExpectedPending nvarchar(max), @Allocations nvarchar(max), @ContingencyPercent int
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @TargetDate date;
SELECT @TargetDate = p.DeadlineDate
FROM dbo.WritingPlans p WITH (UPDLOCK, HOLDLOCK)
JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
WHERE p.WritingPlanID = @WritingPlanID AND p.UserID = @UserID
AND p.ContingencyPercent IS NOT NULL AND p.ModifiedDateUtc = @ExpectedModifiedUtc;
IF @TargetDate IS NULL OR @ContingencyPercent NOT BETWEEN 1 AND 99 THROW 51000, 'Writing plan changed; preview again', 1;
DECLARE @Pending TABLE (ActivityID int PRIMARY KEY, BookID int, ChapterID int, SceneID int, GroupID int,
Kind varchar(20), Minutes int);
INSERT @Pending
SELECT ActivityID, BookID, ChapterID, SceneID, GroupID, Kind, Minutes
FROM dbo.WriterPlannedActivities WITH (UPDLOCK, HOLDLOCK)
WHERE WritingPlanID = @WritingPlanID AND Status = 'Planned';
IF NOT EXISTS (SELECT 1 FROM @Pending)
OR EXISTS (SELECT ActivityID FROM @Pending EXCEPT SELECT CONVERT(int, value) FROM OPENJSON(@ExpectedPending))
OR EXISTS (SELECT CONVERT(int, value) FROM OPENJSON(@ExpectedPending) EXCEPT SELECT ActivityID FROM @Pending)
THROW 51000, 'Remaining work changed; preview again', 1;
DECLARE @New TABLE (BookID int, ChapterID int, SceneID int, GroupID int, Kind varchar(20), Minutes int, ScheduledDate date);
INSERT @New
SELECT BookID, ChapterID, SceneID, GroupID, Kind, Minutes, ScheduledDate
FROM OPENJSON(@Allocations) WITH (BookID int, ChapterID int, SceneID int, GroupID int, Kind varchar(20), Minutes int, ScheduledDate date);
IF EXISTS (SELECT 1 FROM @New WHERE ScheduledDate IS NULL OR ScheduledDate NOT BETWEEN @StartDate AND @TargetDate
OR Minutes IS NULL OR Minutes NOT BETWEEN 1 AND 1440)
OR EXISTS (
SELECT BookID, ChapterID, SceneID, GroupID, Kind, SUM(Minutes) FROM @New GROUP BY BookID, ChapterID, SceneID, GroupID, Kind
EXCEPT SELECT BookID, ChapterID, SceneID, GroupID, Kind, SUM(Minutes) FROM @Pending GROUP BY BookID, ChapterID, SceneID, GroupID, Kind)
OR EXISTS (
SELECT BookID, ChapterID, SceneID, GroupID, Kind, SUM(Minutes) FROM @Pending GROUP BY BookID, ChapterID, SceneID, GroupID, Kind
EXCEPT SELECT BookID, ChapterID, SceneID, GroupID, Kind, SUM(Minutes) FROM @New GROUP BY BookID, ChapterID, SceneID, GroupID, Kind)
THROW 51000, 'Allocations must preserve remaining budgets and the target date', 1;
DELETE a FROM dbo.WriterPlannedActivities a JOIN @Pending p ON p.ActivityID = a.ActivityID;
INSERT dbo.WriterPlannedActivities (WritingPlanID, BookID, ChapterID, SceneID, GroupID, Kind, Minutes, ScheduledDate)
SELECT @WritingPlanID, BookID, ChapterID, SceneID, GroupID, Kind, Minutes, ScheduledDate FROM @New;
UPDATE dbo.WritingPlans SET ContingencyPercent = @ContingencyPercent, ModifiedDateUtc = SYSUTCDATETIME()
WHERE WritingPlanID = @WritingPlanID;
COMMIT TRANSACTION;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterScheduleDailyFocus
@UserID int, @BookID int, @UtcDate date
AS
BEGIN
SET NOCOUNT ON;
SELECT r.ScheduledDate, SUM(r.Minutes) AS Minutes,
FLOOR(SUM(CASE WHEN r.Kind = 'Draft' AND p.DraftingWordsPerHour IS NOT NULL
THEN CONVERT(decimal(22, 4), r.Minutes) * p.DraftingWordsPerHour / 60 ELSE 0 END)) AS SuggestedWords
FROM dbo.WriterPlannedActivities r
JOIN dbo.WritingPlans p ON p.WritingPlanID = r.WritingPlanID AND p.UserID = @UserID AND p.IsActive = 1
JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
WHERE r.BookID = @BookID AND r.Status = 'Planned'
AND r.ScheduledDate BETWEEN DATEADD(day, -1, @UtcDate) AND DATEADD(day, 1, @UtcDate)
GROUP BY r.ScheduledDate
ORDER BY r.ScheduledDate;
END;
GO

View File

@ -949,6 +949,8 @@ public sealed class WriterDashboardViewModel
public int? ProjectID { get; set; }
public IReadOnlyList<SelectListItem> ProjectOptions { get; set; } = [];
public IReadOnlyList<WriterScheduleDailyFocus> ScheduleDailyFocus { get; set; } = [];
public WriterWorkingGroup? CurrentWorkingGroup { get; set; }
public WritingScheduleDashboardViewModel WritingSchedule { get; set; } = new();
public IReadOnlyList<WriterDashboardScene> WriteNext { get; set; } = [];
public IReadOnlyList<WriterDashboardScene> ContinueWriting { get; set; } = [];
@ -1008,6 +1010,10 @@ public sealed class WritingDayAvailabilityViewModel
public sealed class WritingPlanSettingsEditViewModel
{
public DateTime? OriginalTargetDate { get; set; }
public int? ContingencyPercent { get; set; }
public int? DraftingWordsPerHour { get; set; }
public DateTime ModifiedDateUtc { get; set; }
public int ProjectID { get; set; }
public int? BookID { get; set; }
public int WritingPlanID { get; set; }
@ -1134,6 +1140,22 @@ public sealed class WritingScheduleSetupViewModel
[Required]
public string RebalanceMode { get; set; } = "Ask";
[Range(1, 99)]
public int ContingencyPercent { get; set; } = 20;
[Range(1, int.MaxValue)]
public int DraftingWordsPerHour { get; set; } = 750;
public int? ObservedDraftingWordsPerHour { get; set; }
public int? WorkingGroupID { get; set; }
public IReadOnlyList<WriterWorkingGroup> WorkingGroups { get; set; } = [];
public List<WriterPlanActivity> Candidates { get; set; } = [];
public Services.Writer.WriterCapacityPreview? Capacity { get; set; }
public Guid CreationToken { get; set; } = Guid.NewGuid();
public string? ReviewFingerprint { get; set; }
public IReadOnlyList<DateTime> OverlapDates { get; set; } = [];
public IReadOnlyList<SelectListItem> ProjectOptions { get; set; } = [];
public IReadOnlyList<SelectListItem> BookOptions { get; set; } = [];
public IReadOnlyList<SelectListItem> GoalTypeOptions { get; set; } = [];
@ -1151,13 +1173,6 @@ public sealed class WritingScheduleSetupViewModel
];
}
public sealed class WritingScheduleSetupResult
{
public int WritingPlanID { get; init; }
public int GeneratedItemCount { get; init; }
public string? ValidationMessage { get; init; }
}
public sealed class CharacterArcViewModel
{
public Project Project { get; set; } = new();

View File

@ -0,0 +1,18 @@
@model string
@{
ViewData["Title"] = "Start page";
}
<h1>Start page</h1>
<form asp-action="Startup" method="post" class="story-bible-card">
<label for="page" class="form-label">Open after sign-in on this browser</label>
<select id="page" name="page" class="form-select">
@foreach (var choice in ApplicationStartup.Destinations)
{
<option value="@choice.Key" selected="@(Model == choice.Key)">@choice.Value.Label</option>
}
</select>
<div class="button-row mt-3" data-pwa-context="Record">
<button class="btn btn-primary" type="submit">Save start page</button>
<a asp-controller="Projects" asp-action="Index">Cancel</a>
</div>
</form>

View File

@ -10,7 +10,7 @@
}
<section class="pd-shell" aria-label="Application commands" data-app-navigation data-ribbon-shell data-workspace-controller="@controller" data-workspace-action="@action" data-collapsed="@appearance.RibbonCollapsed.ToString().ToLowerInvariant()">
<div class="pd-titlebar">
<a class="pd-brand" asp-controller="Projects" asp-action="Index">PlotDirector<span class="pd-brand-mark" aria-hidden="true">.</span></a>
<a class="pd-brand" asp-controller="Home" asp-action="Index">PlotDirector<span class="pd-brand-mark" aria-hidden="true">.</span></a>
<partial name="_ApplicationToolbar" model="Model" />
@if (appearance.ShowProjectContextMenu || (appearance.ShowBookContextMenu && project is not null))
{
@ -86,6 +86,7 @@
<li hidden data-pwa-install-item><button type="button" class="dropdown-item" data-pwa-install>PlotDirector Desktop</button></li>
<li><span class="visually-hidden" role="status" data-pwa-status></span></li>
<li><a class="dropdown-item" asp-controller="ManageAccount" asp-action="Index">Manage Account</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Startup">Start page</a></li>
<li><a class="dropdown-item" asp-controller="Onboarding" asp-action="Index">Setup preferences</a></li>
@if (!(ViewData["ShellClass"] as string ?? "").Contains("marketing-shell", StringComparison.OrdinalIgnoreCase))
{

View File

@ -60,11 +60,7 @@
<input type="hidden" asp-for="SessionLengthMinutes" />
<div class="col-md-6">
<label asp-for="RebalanceMode" class="form-label">Rebalance Mode</label>
<select asp-for="RebalanceMode" asp-items="Model.RebalanceModeOptions" class="form-select"></select>
<span asp-validation-for="RebalanceMode" class="text-danger"></span>
</div>
<input type="hidden" asp-for="RebalanceMode" />
<div class="col-12">
<label class="form-label">Writing Availability</label>

View File

@ -8,6 +8,31 @@
<div class="writer3 writer3-home" data-writer-destination="Home" data-writer-queues-url="@Url.Action("Workspaces",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writer-legacy-url="@Url.Action("Overview",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writer-write-url="@Url.Action("Write",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writing-workspace-launcher data-compact-writer="true" data-project-id="@Model.ProjectID" data-book-id="@Model.BookID">
<partial name="_Writer3Header" model="Model" />
@if(!Model.BookID.HasValue){<p class="writer3-scope-notice">Select a project and book in the application bar, or <a asp-controller="Projects" asp-action="Index">open your projects</a> to begin. You can explore writing problems before you have a manuscript.</p>}
@if (Model.BookID.HasValue)
{
<section class="writer3-panel" aria-label="Current work">
<h2>Current work</h2>
@if (Model.CurrentWorkingGroup is { } group)
{
<p>Current group · <a asp-controller="WriterGroups" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-groupId="@group.GroupID">@group.Name</a></p>
}
@if (Model.Objective is { } objective)
{
<p>@objective.Activity · @(objective.SceneTitle ?? objective.ChapterTitle ?? "Across the book")</p>
}
<p data-writer-today hidden></p>
<div hidden>
@foreach (var day in Model.ScheduleDailyFocus)
{
<span data-writer-allocation-date="@day.ScheduledDate.ToString("yyyy-MM-dd")" data-writer-allocation-minutes="@day.Minutes" data-writer-suggested-words="@day.SuggestedWords.ToString(System.Globalization.CultureInfo.InvariantCulture)"></span>
}
</div>
<div class="button-row">
<a asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Continue writing</a>
<a asp-action="SchedulePreview" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Review or recalculate writing time</a>
</div>
</section>
}
<section class="writer3-home-choices" aria-label="Choose where to begin">
<a class="writer3-choice" asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">
<svg class="writer3-choice-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("writer").IconPath" /></svg>
@ -20,14 +45,22 @@
<h2>Explore Your Story</h2><p>Develop ideas, solve problems<br class="writer3-desktop-break" /> and discover what happens next.</p><small>No completed plan or linked Word document needed.</small>
<span class="writer3-cta">Go to Explore <span aria-hidden="true">→</span></span>
</a>
<a class="writer3-choice" asp-action="Dashboard" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">
<svg class="writer3-choice-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("metrics").IconPath" /></svg>
<h2>Writing Dashboard</h2><p>See plans, progress, activity<br class="writer3-desktop-break" /> and your writing journey.</p><small>Your recorded work and the work ahead.</small>
<span class="writer3-cta">Open Dashboard <span aria-hidden="true">→</span></span>
@if (Model.BookID.HasValue)
{
<a class="writer3-choice" asp-controller="Writing" asp-action="Context" asp-route-projectId="@Model.ProjectID" asp-route-panel="intent" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.NarrativeFocus?.ChapterID">
<h2>Plan your story</h2><p>Review narrative intent in Context.</p>
</a>
}
<a class="writer3-choice" asp-action="Plan" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">
<h2>Organise work</h2><p>Order activities and plan writing time when it helps.</p>
</a>
<a class="writer3-choice" asp-action="Reflect" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">
<h2>Writing journey</h2><p>See your recorded work.</p>
</a>
</section>
</div>
@section Scripts {
<script src="~/js/writer-schedule-date.js" asp-append-version="true"></script>
<script src="~/js/writer3-navigation.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>

View File

@ -113,7 +113,7 @@ else
}
<partial name="_PlannedActivities" model="Model.DerivedActivities" />
<a asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@Model.SelectedPlan.WritingPlanID">Review activities from chapters and scenes</a>
<a asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@Model.SelectedPlan.WritingPlanID">Review or recalculate writing activities</a>
@if(Model.Items.Count>0){
<section class="story-bible-section">
<div class="story-bible-section-heading">

View File

@ -1,18 +1,18 @@
@model WritingScheduleSetupViewModel
@{
ViewData["DesktopLayout"] = "wide";
ViewData["Title"] = "Schedule Setup";
ViewData["Title"] = "Create Writing Schedule";
}
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
<a asp-controller="Writer" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Writer</a>
<span>Schedule Setup</span>
<span>Create Writing Schedule</span>
</nav>
<div data-pwa-task class="page-heading compact">
<div>
<p class="eyebrow">Writing schedule</p>
<h1>Schedule Setup <help-icon key="workspace.writingPlans" /></h1>
<h1>Create Writing Schedule <help-icon key="workspace.writingPlans" /></h1>
<p class="lead-text">Plan for the selected book, or choose All Books for a project-wide plan.</p><a asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Skip scheduling · return to Writer</a>
</div>
</div>
@ -29,7 +29,7 @@
</div>
<div class="col-md-6">
<label asp-for="GoalType" class="form-label">Goal Type</label>
<label asp-for="GoalType" class="form-label">Type of work</label>
<select asp-for="GoalType" asp-items="Model.GoalTypeOptions" class="form-select"></select>
<span asp-validation-for="GoalType" class="text-danger"></span>
</div>
@ -50,24 +50,48 @@
<span asp-validation-for="BookID" class="text-danger"></span>
</div>
@if (Model.WorkingGroups.Count > 0 || Model.WorkingGroupID.HasValue)
{
<div class="col-md-6">
<label asp-for="WorkingGroupID" class="form-label">Work to schedule</label>
<select asp-for="WorkingGroupID" class="form-select">
<option value="">Choose individual chapters or scenes</option>
@foreach (var group in Model.WorkingGroups.Where(group => group.ChapterIDs.Count > 0))
{
<option value="@group.GroupID">@group.Name (@group.ChapterIDs.Count chapters)</option>
}
</select>
</div>
}
<div class="col-md-6">
<label asp-for="StartDate" class="form-label">Start Date</label>
<input asp-for="StartDate" class="form-control" type="date" />
<input asp-for="StartDate" class="form-control" type="date" data-author-start-date data-default-local="@(Context.Request.Method == "GET" ? "true" : "false")" />
<span asp-validation-for="StartDate" class="text-danger"></span>
</div>
<div class="col-md-6">
<label asp-for="DeadlineDate" class="form-label">Deadline Date</label>
<input asp-for="DeadlineDate" class="form-control" type="date" />
<label asp-for="DeadlineDate" class="form-label">Target date</label>
<input asp-for="DeadlineDate" class="form-control" type="date" data-author-target-date data-default-local="@(Context.Request.Method == "GET" ? "true" : "false")" />
<span asp-validation-for="DeadlineDate" class="text-danger"></span>
</div>
<input type="hidden" asp-for="SessionLengthMinutes" />
<div class="col-md-6">
<label asp-for="RebalanceMode" class="form-label">Rebalance Mode</label>
<select asp-for="RebalanceMode" asp-items="Model.RebalanceModeOptions" class="form-select"></select>
<span asp-validation-for="RebalanceMode" class="text-danger"></span>
<label asp-for="ContingencyPercent" class="form-label">Reserve for contingency (%)</label>
<input asp-for="ContingencyPercent" class="form-control" min="1" max="99" />
<span asp-validation-for="ContingencyPercent" class="text-danger"></span>
</div>
<div class="col-md-6">
<label asp-for="DraftingWordsPerHour" class="form-label">Drafting words per hour</label>
<input asp-for="DraftingWordsPerHour" class="form-control" min="1" />
<span asp-validation-for="DraftingWordsPerHour" class="text-danger"></span>
@if (Model.ObservedDraftingWordsPerHour is > 0)
{
<p>Observed pace from matched drafting sessions · @Model.ObservedDraftingWordsPerHour words per hour.</p>
<button class="btn btn-sm btn-outline-secondary" name="step" value="use-observed-rate" type="submit">Use observed rate and review work</button>
}
</div>
<div class="col-12">
@ -111,13 +135,103 @@
</div>
</div>
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3">
<button class="btn btn-primary" data-pwa-icon="save" type="submit">Review activities</button>
<a class="btn btn-outline-secondary" asp-action="SchedulePreview" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Schedule Preview</a>
@if (Model.Candidates.Count > 0)
{
<h2 class="mt-4">Choose work and review effort</h2>
@if (Model.WorkingGroupID.HasValue)
{
<p>This schedule reserves time for the group. Choose any chapter in the group when you sit down to write.</p>
}
<p>Adjust each budget in minutes. Drafting estimates use the estimated words remaining and your drafting rate. Use your own budget for research, revision, editing, or work without a word estimate.</p>
<div class="table-responsive">
<table class="table align-middle">
<thead><tr><th>Include</th><th>Chapter / scene</th><th>Activity</th><th>Minutes</th></tr></thead>
<tbody>
@for (var i = 0; i < Model.Candidates.Count; i++)
{
var row = Model.Candidates[i];
<tr>
<td>
<input asp-for="Candidates[i].Selected" aria-label="Include @row.Title" />
<input asp-for="Candidates[i].GroupID" type="hidden" />
<input asp-for="Candidates[i].ChapterID" type="hidden" />
<input asp-for="Candidates[i].SceneID" type="hidden" />
</td>
<td>@row.BookTitle · @row.Title</td>
<td>
<select asp-for="Candidates[i].Kind" class="form-select" aria-label="Activity for @row.Title">
<option value="Draft">Draft</option>
<option value="Plan">Research / plan</option>
<option value="Edit">Revise / edit</option>
<option value="Review">Read / review</option>
</select>
</td>
<td><input asp-for="Candidates[i].Minutes" class="form-control" min="5" max="1440" aria-label="Minutes for @row.Title" /></td>
</tr>
}
</tbody>
</table>
</div>
}
else if (Context.Request.Method == "POST" && ViewData.ModelState.IsValid)
{
<p class="mt-3">No eligible work was found. Choose a different book, add a chapter, or include blocked scenes.</p>
}
@if (Model.Capacity is { } capacity)
{
<section class="mt-4" aria-label="Schedule preview">
<h2>Schedule preview</h2>
<dl>
<dt>Available</dt><dd>@capacity.Available min</dd>
<dt>Reserved for contingency</dt><dd>@capacity.Reserved min</dd>
<dt>Usable</dt><dd>@capacity.Usable min</dd>
<dt>Required</dt><dd>@capacity.Required min</dd>
<dt>Shortfall</dt><dd>@capacity.Shortfall min</dd>
<dt>Forecast</dt><dd>@(capacity.Forecast?.ToString("d MMM yyyy") ?? "Unavailable")</dd>
</dl>
@if (Model.OverlapDates.Count > 0)
{
<p role="status">Other active plans also use @Model.OverlapDates.Count of these dates. Check your combined time before saving.</p>
}
@if (capacity.Shortfall > 0)
{
<p role="status">The selected work exceeds usable time. Change the work, availability, contingency, or target date and preview again.</p>
}
else if (capacity.Allocations.Count == 0)
{
<p role="status">Select at least one activity to preview a schedule.</p>
}
else
{
<ul>
@foreach (var day in capacity.Allocations.GroupBy(item => item.ScheduledDate))
{
<li>@day.Key.ToString("d MMM yyyy") · @day.Sum(item => item.Minutes) min · @string.Join(", ", day.Select(item => item.Title).Distinct())</li>
}
</ul>
}
</section>
}
<input type="hidden" asp-for="ReviewFingerprint" />
<input type="hidden" asp-for="CreationToken" />
<div class="button-row mt-3" data-pwa-context="Record" data-pwa-priority="0">
@if (Model.Capacity?.Allocations.Count > 0)
{
<button class="btn btn-primary" data-pwa-icon="save" type="submit" name="step" value="save">Save writing schedule</button>
}
@if (Model.Candidates.Count > 0)
{
<button class="btn @(Model.Capacity?.Allocations.Count > 0 ? "btn-outline-primary" : "btn-primary")" type="submit" name="step" value="preview">Preview schedule</button>
}
<button class="btn @(Model.Candidates.Count > 0 ? "btn-outline-secondary" : "btn-primary")" type="submit" name="step" value="review">Review activities</button>
<a class="btn btn-outline-secondary" asp-action="SchedulePreview" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Cancel</a>
</div>
</form>
</section>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script src="~/js/writer-schedule-date.js" asp-append-version="true"></script>
}

View File

@ -98,10 +98,11 @@
</form>
}
<a class="btn btn-sm btn-outline-primary" asp-controller="WriterPlanning" asp-action="Index" asp-route-writingPlanId="@plan.WritingPlanID">Review chapter activities</a>
<details><summary>Legacy scene scheduling</summary>
<form asp-action="RegenerateWritingPlanSchedule" method="post">
<input type="hidden" name="writingPlanId" value="@plan.WritingPlanID" /><input type="hidden" name="projectId" value="@Model.ProjectID" /><input type="hidden" name="bookId" value="@Model.BookID" />
<button class="btn btn-sm btn-outline-primary" type="submit">Regenerate workflow scene tasks</button>
</form>
</form></details>
<button class="btn btn-sm btn-outline-danger" type="button" data-bs-toggle="modal" data-bs-target="#deleteWritingPlanModal-@plan.WritingPlanID">Delete Plan</button>
</div>
</td>

View File

@ -1,6 +1,6 @@
@model PlotLine.Models.WriterActivity
<article class="writer21-task" data-activity-id="@Model.ID">
<h4>@Model.Title</h4><p>@Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){<time>· @Model.TargetDate.Value.ToString("d MMM yyyy")</time>}</p>
<article class="writer21-task" data-activity-id="@Model.ID" data-activity-version="@Model.Version">
<h4><span data-board-handle>@Model.Title</span></h4><p>@Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){<time>· @Model.TargetDate.Value.ToString("d MMM yyyy")</time>}</p>
@if(!string.IsNullOrWhiteSpace(Model.Notes)){<p>@Model.Notes</p>}
<small>Updated @Model.UpdatedUtc.ToString("d MMM yyyy HH:mm") UTC</small>
<div class="button-row"><form asp-controller="WriterActivities" asp-action="Start" method="post" data-activity-start><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@Model.ID"/><input type="hidden" name="version" value="@Model.Version"/><button class="btn btn-primary">Start working</button></form>

View File

@ -4,7 +4,25 @@
<div class="writer21-tabs" role="tablist" aria-label="Activity views">@foreach(var view in new[]{"list","board","schedule"}){<button type="button" role="tab" aria-selected="@(Model.View==view?"true":"false")" data-planner-tab="@view">@System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase(view)</button>}</div>
<p data-planner-message role="status"></p><details><summary>Add planned activity</summary><partial name="~/Views/Writer/_ActivityEditor.cshtml" model="new PlotLine.Models.WriterActivity{ID=Guid.NewGuid(),BookID=Model.BookID}" /></details>
@if(active.Length==0){<p>No planned activities yet. Add one when it helps you organise your work.</p>}
@if(Model.View=="board"){<div class="writer21-board">@foreach(var status in PlotLine.Models.WriterActivity.Statuses){<section><h3>@status</h3>@foreach(var item in active.Where(x=>x.Status==status)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}</section>}</div>}
@if (Model.View == "board")
{
<form asp-controller="WriterActivities" asp-action="MoveOnBoard" method="post" data-board-move hidden>
<input type="hidden" name="bookId" value="@Model.BookID" />
</form>
<div class="writer21-board">
@foreach (var status in PlotLine.Models.WriterActivity.Statuses)
{
var cards = active.Where(item => item.Status == status).ToArray();
<section data-board-status="@status">
<h3>@status <small class="text-body-secondary">(@cards.Length)</small></h3>
@foreach (var item in cards)
{
<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />
}
</section>
}
</div>
}
else if(Model.View=="schedule"){
<h3>Dated activities</h3>@foreach(var item in active.Where(x=>x.TargetDate.HasValue).OrderBy(x=>x.TargetDate)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}
<h3>Undated activities</h3>@foreach(var item in active.Where(x=>!x.TargetDate.HasValue)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}

View File

@ -1,2 +1,2 @@
@model IReadOnlyList<PlotLine.Models.WriterPlanActivity>
@if(Model.Count>0){<section class="story-bible-section"><h2>Reviewed writing activities</h2><p>@Model.Count allocations · @Model.Sum(x=>x.Minutes) planned minutes · these budgets are not measured work.</p><div class="table-responsive"><table class="table"><thead><tr><th>Date</th><th>Work</th><th>Activity</th><th>Minutes</th><th>Status</th></tr></thead><tbody>@foreach(var item in Model){<tr><td>@item.ScheduledDate.ToString("d MMM yyyy")</td><td>@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">@item.Title</a>}else{<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@item.ChapterID">@item.Title</a>}</td><td>@item.Kind</td><td>@item.Minutes</td><td>@item.Status @if(item.Status=="Planned"){<form asp-controller="WriterPlanning" asp-action="Complete" method="post"><input type="hidden" name="writingPlanId" value="@ViewData["WritingPlanID"]" /><input type="hidden" name="activityId" value="@item.ActivityID" /><button class="btn btn-sm btn-outline-primary">Mark complete</button></form>}</td></tr>}</tbody></table></div></section>}
@if(Model.Count>0){<section class="story-bible-section"><h2>Reviewed writing activities</h2><p>@Model.Count allocations · @Model.Sum(x=>x.Minutes) planned minutes · these budgets are not measured work.</p><div class="table-responsive"><table class="table"><thead><tr><th>Date</th><th>Work</th><th>Activity</th><th>Minutes</th><th>Status</th></tr></thead><tbody>@foreach(var item in Model){<tr><td>@item.ScheduledDate.ToString("d MMM yyyy")</td><td>@if(item.GroupID.HasValue){<a asp-controller="WriterGroups" asp-action="Index" asp-route-bookId="@item.BookID" asp-route-groupId="@item.GroupID">@item.Title</a>}else if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">@item.Title</a>}else{<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@item.ChapterID">@item.Title</a>}</td><td>@item.Kind</td><td>@item.Minutes</td><td>@item.Status @if(item.Status=="Planned"){<form asp-controller="WriterPlanning" asp-action="Complete" method="post"><input type="hidden" name="writingPlanId" value="@ViewData["WritingPlanID"]" /><input type="hidden" name="activityId" value="@item.ActivityID" /><button class="btn btn-sm btn-outline-primary">Mark complete</button><button class="btn btn-sm btn-outline-secondary" asp-controller="WriterPlanning" asp-action="Skip">Skip allocation</button></form>}</td></tr>}</tbody></table></div></section>}

View File

@ -2,9 +2,10 @@
<div class="writer3-workspace writer2-single" aria-label="Writing priorities">
<section class="writer3-panel writer3-main">
<h2>Planned activities</h2><p>What you intend to accomplish. Starting work is separate from recording a session.</p>
<p><a asp-controller="WriterGroups" asp-action="Index" asp-route-bookId="@Model.BookID">Working groups</a></p>
<div data-activity-planner data-book="@Model.BookID" data-url="@Url.Action("Panel","WriterActivities",new{bookId=Model.BookID})"><p>Loading your activities…</p></div>
<section data-planner-schedule-existing hidden>
@if(Model.PlannedActivities.Count>0){<h3>Scheduled writing activities</h3><ol class="writer2-activities">@foreach(var item in Model.PlannedActivities.Take(12)){<li><time>@item.ScheduledDate.ToString("ddd d MMM")</time><strong>@item.Kind · @item.Title</strong><span>@item.Status · @item.Minutes planned minutes</span>@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Work on this scene</a>}else{<a asp-action="Chapter" asp-route-id="@item.ChapterID">Work on this chapter</a>}</li>}</ol>}
@if(Model.PlannedActivities.Count>0){<h3>Scheduled writing activities</h3><ol class="writer2-activities">@foreach(var item in Model.PlannedActivities.Take(12)){<li><time>@item.ScheduledDate.ToString("ddd d MMM")</time><strong>@item.Kind · @item.Title</strong><span>@item.Status · @item.Minutes planned minutes</span>@if(item.GroupID.HasValue){<a asp-controller="WriterGroups" asp-action="Index" asp-route-bookId="@item.BookID" asp-route-groupId="@item.GroupID">Choose a chapter from this group</a>}else if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Work on this scene</a>}else{<a asp-action="Chapter" asp-route-id="@item.ChapterID">Work on this chapter</a>}</li>}</ol>}
else{<h3>Writing time ahead</h3><partial name="_WriterUpcoming" model="Model" />}
<details class="writer3-inset"><summary>Schedule and completed work</summary><p>@Model.WritingSchedule.CompletedTasks completed · @Model.WritingSchedule.SkippedTasks skipped · @Model.WritingSchedule.RemainingTasks outstanding scheduled tasks. These are recorded task states, not measured manuscript progress.</p>
<div class="button-row"><a asp-action="SchedulePreview" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">View and adjust your schedule</a><a asp-action="WritingPlans" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Existing plans and activity completion</a><a asp-action="ScheduleSetup" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">@(Model.WritingSchedule.HasActivePlans?"Create another writing plan":"Create a writing schedule")</a></div></details>

View File

@ -2,6 +2,21 @@
@{var focus = Model.Objective; var editing = Context.Request.Query["setup"] == "true"; var kind = focus?.Activity is "Revising" or "Editing" or "Proofreading" ? "Editing" : focus?.Activity == "Researching" ? "Planning" : "Writing";}
<div class="writer3-workspace" aria-label="Writing workspace">
<section class="writer3-panel writer3-main" tabindex="0" id="working-focus" aria-label="Saved Writer objective" data-writer-focus data-focus-url="@Url.Action("Focus","Writer",new{bookId=Model.BookID})" data-saved-activity="@focus?.Activity" data-saved-session-kind="@PlotLine.Services.Writer.WriterFocusActivities.SessionKind(focus?.Activity)" data-saved-chapter="@focus?.ChapterID" data-book-id="@Model.BookID" data-plan-url="@Url.Action("ScheduleSetup", "Writer", new { bookId = Model.BookID, projectId = Model.ProjectID })">
<h2>Write</h2>
<div class="button-row">
<a class="btn btn-primary" asp-controller="Writing" asp-action="Context" asp-route-projectId="@Model.ProjectID" asp-route-panel="intent" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.NarrativeFocus?.ChapterID">Open Context and Intent</a>
<a class="btn btn-outline-primary" asp-controller="WriterIntentImport" asp-action="Index" asp-route-bookId="@Model.BookID">Paste chapter intentions</a>
@if (focus?.ChapterID is int chapterId)
{
<a class="btn btn-outline-primary" asp-action="Chapter" asp-route-id="@chapterId">Resume @focus.ChapterTitle</a>
}
else
{
<a class="btn btn-outline-primary" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Choose a chapter</a>
}
</div>
<details class="mt-3" open="@editing">
<summary>Optional objective and session controls</summary>
<p class="eyebrow">Saved Writer objective</p>
<p class="writer3-caption" data-objective-location data-chapter="@focus?.ChapterID" data-scene="@focus?.SceneID">Objective target: @(focus?.SceneTitle ?? focus?.ChapterTitle ?? "Across the book"). This target changes only when you edit the objective.</p>
<button type="button" class="btn btn-sm btn-outline-secondary" data-go-objective data-chapter="@focus?.ChapterID" data-scene="@focus?.SceneID" hidden="@(focus?.ChapterID==null)">Go to objective</button>
@ -26,6 +41,7 @@
<p class="writer3-caption" data-focus-session-difference hidden></p>
<div class="writer3-session-block"><h3>Work sessions &amp; Audio Review</h3><p class="writer3-caption">Recording keeps its explicitly selected objective or session target. Audio Review is recorded for a chapter.</p><partial name="_WriterWorkToolbar" model="new PlotLine.Models.WriterWorkToolbar(Model.BookID!.Value, focus?.ChapterID, focus?.ChapterTitle, Model.ObjectiveChoices, kind, true)" /></div>}
else{<p class="muted">Work-session evidence is private to the book owner. Your chapter and scene tools remain available.</p>}
</details>
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Writing tools">
<h2>Keep your story close</h2><div class="button-row"><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Context" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.NarrativeFocus?.ChapterID" asp-route-sceneId="@Model.NarrativeFocus?.SceneID">Context</a></div><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>

View File

@ -0,0 +1,52 @@
@model PlotLine.Controllers.WriterGroupsController.GroupPage
@{
ViewData["Title"] = "Working groups";
ViewData["ProjectSection"] = "Writer";
}
<header data-pwa-task>
<h1>Working groups</h1>
<p>Group existing chapters for a stretch of work. Choose any chapter in the group when you write.</p>
</header>
@if (TempData["WriterWorkspaceMessage"] is string message)
{
<p role="status">@message</p>
}
@foreach (var group in Model.Groups)
{
<section class="story-bible-card mb-3">
<h2>@group.Name @if (group.IsCurrent) { <small class="text-body-secondary">Current focus</small> }</h2>
<ul>
@foreach (var chapter in Model.Chapters.Where(chapter => group.ChapterIDs.Contains(chapter.ChapterID)))
{
<li><a asp-controller="Writer" asp-action="Chapter" asp-route-id="@chapter.ChapterID">@chapter.ChapterTitle</a></li>
}
</ul>
<a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-groupId="@group.GroupID">Edit @group.Name</a>
@if (group.ChapterIDs.Count > 0)
{
<a asp-controller="Writer" asp-action="ScheduleSetup" asp-route-bookId="@Model.BookID" asp-route-workingGroupId="@group.GroupID">Schedule time for @group.Name</a>
}
</section>
}
<form asp-action="Index" method="post" class="story-bible-card">
<h2>@(Model.GroupID == 0 ? "Create a group" : "Edit group")</h2>
<div asp-validation-summary="All" class="text-danger"></div>
<input asp-for="BookID" type="hidden" />
<input asp-for="GroupID" type="hidden" />
<label asp-for="Name" class="form-label">Group name</label>
<input asp-for="Name" class="form-control" required />
<label class="mt-2"><input asp-for="IsCurrent" /> Make this the current group for this book</label>
<fieldset class="mt-2">
<legend>Chapters</legend>
@foreach (var chapter in Model.Chapters)
{
<label class="d-block">
<input type="checkbox" name="ChapterIDs" value="@chapter.ChapterID" checked="@Model.ChapterIDs.Contains(chapter.ChapterID)" /> @chapter.ChapterTitle
</label>
}
</fieldset>
<div class="button-row mt-3" data-pwa-context="Record">
<button class="btn btn-primary" type="submit">Save working group</button>
<a asp-action="Index" asp-route-bookId="@Model.BookID">Cancel</a>
</div>
</form>

View File

@ -0,0 +1,55 @@
@model PlotLine.Controllers.WriterIntentImportController.ImportPage
@{
ViewData["Title"] = "Paste chapter intentions";
ViewData["ProjectSection"] = "Writer";
}
<header data-pwa-task>
<h1>Paste chapter intentions</h1>
<p>Use a Markdown heading or a line beginning with “Chapter” before each block of notes, summaries, or bullets.</p>
</header>
<form asp-action="Index" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<input asp-for="BookID" type="hidden" />
@if (Model.Sections.Count == 0)
{
<label asp-for="Text" class="form-label">Chapter intentions</label>
<textarea asp-for="Text" class="form-control" rows="10" maxlength="64000" required></textarea>
}
else
{
<input asp-for="Text" type="hidden" />
@for (var i = 0; i < Model.Sections.Count; i++)
{
var block = Model.Sections[i];
<fieldset class="story-bible-card mb-3">
<legend>@block.Heading</legend>
<p style="white-space: pre-wrap">@block.Body</p>
<label asp-for="Mappings[i].ChapterID">Chapter</label>
<select asp-for="Mappings[i].ChapterID" class="form-select" required>
<option value="">Choose a chapter</option>
@foreach (var chapter in Model.Chapters)
{
<option value="@chapter.ChapterID">@chapter.ChapterTitle</option>
}
</select>
<label asp-for="Mappings[i].Mode">Save as</label>
<select asp-for="Mappings[i].Mode" class="form-select">
<option value="notes">Append to chapter Intent notes</option>
<option value="checklist">Add unchecked Intent items</option>
</select>
</fieldset>
}
}
<div class="button-row mt-3" data-pwa-context="Record">
@if (Model.Sections.Count == 0)
{
<button class="btn btn-primary" type="submit" name="step" value="preview">Preview pasted intentions</button>
}
else
{
<button class="btn btn-primary" type="submit" name="step" value="save">Save chapter intentions</button>
<a asp-action="Index" asp-route-bookId="@Model.BookID">Start a new paste</a>
}
<a asp-controller="Writer" asp-action="Index" asp-route-bookId="@Model.BookID">Cancel</a>
</div>
</form>

View File

@ -0,0 +1,66 @@
@model PlotLine.Models.WriterScheduleRecalculation
@{
ViewData["Title"] = "Recalculate remaining writing time";
ViewData["ProjectSection"] = "Writer";
}
<header data-pwa-task>
<h1>Recalculate remaining writing time</h1>
<p>@Model.Plan?.PlanName · Target @Model.Plan?.DeadlineDate.ToString("d MMM yyyy")</p>
@if (Model.Plan?.OriginalTargetDate is { } original && original != Model.Plan.DeadlineDate)
{
<p>Original target @original.ToString("d MMM yyyy")</p>
}
</header>
<p>Choose when to resume. Completed work, remaining budgets, and the target date are preserved.</p>
<form asp-action="Recalculate" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<input type="hidden" asp-for="WritingPlanID" />
<input type="hidden" asp-for="ReviewFingerprint" />
<input type="hidden" name="authorUtcOffset" data-author-utc-offset />
@if (Model.PendingCount == 0)
{
<p>There is no remaining reviewed work to schedule.</p>
}
else
{
<label asp-for="StartDate" class="form-label">Resume on</label>
<input asp-for="StartDate" type="date" data-author-start-date required />
<label asp-for="ContingencyPercent" class="form-label">Reserve for contingency (%)</label>
<input asp-for="ContingencyPercent" class="form-control" min="1" max="99" required />
@if (Model.Capacity is { } capacity)
{
<dl class="mt-3">
<dt>Available</dt><dd>@capacity.Available min</dd>
<dt>Reserved for contingency</dt><dd>@capacity.Reserved min</dd>
<dt>Used by completed allocations</dt><dd>@capacity.AlreadyAllocated min</dd>
<dt>Usable</dt><dd>@capacity.Usable min</dd>
<dt>Required</dt><dd>@capacity.Required min</dd>
<dt>Shortfall</dt><dd>@capacity.Shortfall min</dd>
<dt>Forecast</dt><dd>@(capacity.Forecast?.ToString("d MMM yyyy") ?? "Unavailable")</dd>
</dl>
@if (Model.OverlapDates.Count > 0)
{
<p role="status">Other active plans also use @Model.OverlapDates.Count of these dates. Check your combined time before saving.</p>
}
@if (capacity.Shortfall > 0)
{
<p role="status">Remaining work exceeds usable time. Edit availability or explicitly change the target date, then preview again.</p>
}
}
}
<div class="button-row mt-3" data-pwa-context="Record">
@if (Model.PendingCount > 0)
{
<button class="btn btn-primary" type="submit" name="step" value="preview">Preview remaining work</button>
}
@if (Model.Capacity?.Allocations.Count > 0)
{
<button class="btn btn-primary" type="submit" name="step" value="save">Save revised allocations</button>
}
<a asp-controller="Writer" asp-action="EditWritingPlan" asp-route-writingPlanId="@Model.WritingPlanID">Edit availability or target date</a>
<a asp-controller="Writer" asp-action="SchedulePreview" asp-route-writingPlanId="@Model.WritingPlanID">Cancel</a>
</div>
</form>
@section Scripts {
<script src="~/js/writer-schedule-date.js" asp-append-version="true"></script>
}

View File

@ -35,3 +35,24 @@
.writer-investigation-actions>summary::-webkit-details-marker{display:none}
.writer-investigation-actions[open]>button{position:absolute;right:0;z-index:2;min-width:210px;display:flex;align-items:center;gap:.4rem;background:var(--pd-surface);border:1px solid var(--pd-border);box-shadow:var(--pd-shadow)}
@media(pointer:coarse){.writer-investigation-actions>summary{min-width:44px;min-height:44px}}
.writer21-board [data-board-status] {
min-height: 8rem;
padding: .5rem;
border: 1px dashed var(--bs-border-color);
border-radius: .5rem;
}
.writer21-board .writer21-drop-target {
border-color: var(--bs-primary);
background: var(--bs-primary-bg-subtle);
}
.writer21-board .writer21-task {
padding: .6rem;
margin-block: .4rem;
}
.writer21-board [data-board-handle][draggable="true"] {
cursor: grab;
}

View File

@ -37,6 +37,7 @@
if (!['single','columns','rows'].includes(state.layout)) state.layout='single';
state.ratio = Number.isFinite(state.ratio) ? Math.max(.2,Math.min(.8,state.ratio)) : .5;
state.panes=state.panes.map((pane,i)=>({tab:registry.has(pane?.tab)?pane.tab:defaults().panes[i].tab,views:pane?.views && typeof pane.views==='object'?pane.views:{}}));
if (new URL(location.href).searchParams.get('panel') === 'intent') state.panes[0].tab = 'intent';
let selectedDocument = restoredState ? (typeof state.selectedDocument==='string'?state.selectedDocument:'') : root.dataset.wordInstance && root.dataset.wordSession ? `${root.dataset.wordInstance}/${root.dataset.wordSession}` : '';
function presentSelectedDocument() {
const [instance,session]=selectedDocument.split('/');root.dataset.wordInstance=instance||'';root.dataset.wordSession=session||'';

View File

@ -1,7 +1,96 @@
(()=>{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);const schedule=document.querySelector('[data-planner-schedule-existing]');if(schedule)schedule.hidden=view!=='schedule';dirty=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);
for (const handle of root.querySelectorAll("[data-board-status] [data-board-handle]")) handle.draggable = true;const schedule=document.querySelector('[data-planner-schedule-existing]');if(schedule)schedule.hidden=view!=='schedule';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;const payload=new FormData(form);busy=true;root.setAttribute('aria-busy','true');const button=event.submitter,locked=[...root.querySelectorAll('button,input,select,textarea')].map(node=>[node,node.disabled]);for(const [node] of locked)node.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:payload});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;root.removeAttribute('aria-busy');for(const [node,disabled] of locked)if(node.isConnected)node.disabled=disabled;button.disabled=committed&&form.isConnected;}});
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;
const move = form.querySelector('[name="direction"]');
const card = form.closest('[data-board-status] [data-activity-id]');
if (move && card) {
const column = card.closest('[data-board-status]');
const cards = [...column.querySelectorAll('[data-activity-id]')];
const index = cards.indexOf(card);
const direction = Number(move.value);
if (index + direction >= 0 && index + direction < cards.length &&
(!dirty || confirm('Leave unsaved activity edits?'))) {
await moveOnBoard(card, column, cards[index + (direction < 0 ? -1 : 2)]);
const refreshed = root.querySelector(`[data-activity-id="${card.dataset.activityId}"]`);
refreshed?.querySelector(`input[name="direction"][value="${direction}"]`)?.form.querySelector('button')?.focus();
}
return;
}
const payload=new FormData(form);busy=true;root.setAttribute('aria-busy','true');const button=event.submitter,locked=[...root.querySelectorAll('button,input,select,textarea')].map(node=>[node,node.disabled]);for(const [node] of locked)node.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:payload});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;root.removeAttribute('aria-busy');for(const [node,disabled] of locked)if(node.isConnected)node.disabled=disabled;button.disabled=committed&&form.isConnected;}});
let draggedCard;
let dropColumn;
function clearDropTarget() {
dropColumn?.classList.remove('writer21-drop-target');
dropColumn = null;
}
root.addEventListener('dragstart', event => {
const handle = event.target.closest('[data-board-status] [data-board-handle]');
if (!handle || busy || dirty) {
if (handle) event.preventDefault();
return;
}
draggedCard = handle.closest('[data-activity-id]');
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', draggedCard.dataset.activityId);
});
root.addEventListener('dragover', event => {
const column = event.target.closest('[data-board-status]');
if (!draggedCard || !column || busy) return;
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
clearDropTarget();
dropColumn = column;
column.classList.add('writer21-drop-target');
});
root.addEventListener('dragend', () => {
draggedCard = null;
clearDropTarget();
});
root.addEventListener('drop', async event => {
const column = event.target.closest('[data-board-status]');
const card = draggedCard;
if (!card || !column || busy || dirty) return;
event.preventDefault();
clearDropTarget();
const cards = [...column.querySelectorAll('[data-activity-id]')].filter(item => item !== card);
const before = cards.find(item => {
const bounds = item.getBoundingClientRect();
return event.clientY < bounds.top + bounds.height / 2;
});
await moveOnBoard(card, column, before);
});
async function moveOnBoard(card, column, before) {
const form = root.querySelector('[data-board-move]');
const payload = new FormData(form);
payload.set('id', card.dataset.activityId);
payload.set('version', card.dataset.activityVersion);
payload.set('status', column.dataset.boardStatus);
if (before) payload.set('beforeId', before.dataset.activityId);
const message = root.querySelector('[data-planner-message]');
busy = true;
root.setAttribute('aria-busy', 'true');
let committed = false;
try {
const response = await fetch(form.action, { method: 'POST', body: payload });
if (!response.ok) {
const data = await response.json().catch(() => null);
throw Error(data?.message || 'Move could not be confirmed. Reload the planner before retrying.');
}
committed = true;
await load();
window.PlotDirector?.toast?.success('Activity moved');
} catch (error) {
message.textContent = committed ? 'Activity moved. Reload to see the updated board.' : error.message;
} finally {
busy = false;
root.removeAttribute('aria-busy');
}
}
window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allow){e.preventDefault();e.returnValue='';}});load().catch(e=>{root.textContent=e.message;});
})();

View File

@ -0,0 +1,29 @@
(() => {
const start = document.querySelector('[data-author-start-date]');
const now = new Date();
const date = [now.getFullYear(), now.getMonth() + 1, now.getDate()]
.map(part => String(part).padStart(2, '0')).join('-');
const today = document.querySelector('[data-writer-today]');
const allocation = document.querySelector(`[data-writer-allocation-date="${date}"]`);
if (today && allocation) {
today.textContent = `${allocation.dataset.writerAllocationMinutes} minutes planned for today.`;
const suggestedWords = Number(allocation.dataset.writerSuggestedWords);
if (suggestedWords > 0) today.textContent += ` About ${suggestedWords.toLocaleString()} draft words at your target pace.`;
today.hidden = false;
}
if (!start) return;
const offset = start.form.querySelector('[data-author-utc-offset]');
if (offset) {
offset.value = -now.getTimezoneOffset();
start.min = date;
}
if (!start.value || start.dataset.defaultLocal === 'true') start.value = date;
const deadline = start.form.querySelector('[data-author-target-date]');
if (deadline?.dataset.defaultLocal === 'true') {
now.setMonth(now.getMonth() + 1);
deadline.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()]
.map(part => String(part).padStart(2, '0')).join('-');
}
})();