diff --git a/PlotLine.Tests/ApplicationDomainBoundaryTests.cs b/PlotLine.Tests/ApplicationDomainBoundaryTests.cs index f13d017e..c0e0b68e 100644 --- a/PlotLine.Tests/ApplicationDomainBoundaryTests.cs +++ b/PlotLine.Tests/ApplicationDomainBoundaryTests.cs @@ -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 diff --git a/PlotLine.Tests/Browser/writer-planning-development.cjs b/PlotLine.Tests/Browser/writer-planning-development.cjs new file mode 100644 index 00000000..54442bf1 --- /dev/null +++ b/PlotLine.Tests/Browser/writer-planning-development.cjs @@ -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; +}); diff --git a/PlotLine.Tests/ContextIntentTextTests.cs b/PlotLine.Tests/ContextIntentTextTests.cs index 9140b98e..f257c12b 100644 --- a/PlotLine.Tests/ContextIntentTextTests.cs +++ b/PlotLine.Tests/ContextIntentTextTests.cs @@ -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"]), diff --git a/PlotLine.Tests/WriterIntelligenceTests.cs b/PlotLine.Tests/WriterIntelligenceTests.cs index 51378d62..e5bdb1cd 100644 --- a/PlotLine.Tests/WriterIntelligenceTests.cs +++ b/PlotLine.Tests/WriterIntelligenceTests.cs @@ -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"); diff --git a/PlotLine/Controllers/AccountController.cs b/PlotLine/Controllers/AccountController.cs index 0b358276..c9c1fafb 100644 --- a/PlotLine/Controllers/AccountController.cs +++ b/PlotLine/Controllers/AccountController.cs @@ -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"); } } diff --git a/PlotLine/Controllers/HomeController.cs b/PlotLine/Controllers/HomeController.cs index db28d349..0c905c5a 100644 --- a/PlotLine/Controllers/HomeController.cs +++ b/PlotLine/Controllers/HomeController.cs @@ -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 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() { diff --git a/PlotLine/Controllers/WriterActivitiesController.cs b/PlotLine/Controllers/WriterActivitiesController.cs index 11e00449..416edad7 100644 --- a/PlotLine/Controllers/WriterActivitiesController.cs +++ b/PlotLine/Controllers/WriterActivitiesController.cs @@ -16,6 +16,16 @@ public sealed class WriterActivitiesController(WriterActivityRepository activiti [HttpPost,ValidateAntiForgeryToken]public Task 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 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 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."}); diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index bf97ea4c..7a020b40 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -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 ScheduleSetup(int? projectId, int? bookId = null, string? focusActivity = null) + public async Task 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 ScheduleSetup(WritingScheduleSetupViewModel model) + [RequestFormLimits(ValueCountLimit = 20000)] + public async Task 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] diff --git a/PlotLine/Controllers/WriterGroupsController.cs b/PlotLine/Controllers/WriterGroupsController.cs new file mode 100644 index 00000000..a79eeeb6 --- /dev/null +++ b/PlotLine/Controllers/WriterGroupsController.cs @@ -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 Groups { get; set; } = []; + public IReadOnlyList Chapters { get; set; } = []; + } + + [HttpGet] + public async Task 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 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(); + } +} diff --git a/PlotLine/Controllers/WriterIntentImportController.cs b/PlotLine/Controllers/WriterIntentImportController.cs new file mode 100644 index 00000000..a7d6c4d2 --- /dev/null +++ b/PlotLine/Controllers/WriterIntentImportController.cs @@ -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 Mappings { get; set; } = []; + public IReadOnlyList Chapters { get; set; } = []; + public IReadOnlyList Sections { get; set; } = []; + } + + public sealed record Mapping(int ChapterID, string? Mode); + + [HttpGet] + public async Task Index(int bookId) + { + if (!await access.CanAccessEntityAsync("Book", bookId)) return NotFound(); + return View(new ImportPage { BookID = bookId }); + } + + [HttpPost, ValidateAntiForgeryToken] + public async Task 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); + } +} diff --git a/PlotLine/Controllers/WriterPlanningController.cs b/PlotLine/Controllers/WriterPlanningController.cs index 5ffd371f..ed2d84bc 100644 --- a/PlotLine/Controllers/WriterPlanningController.cs +++ b/PlotLine/Controllers/WriterPlanningController.cs @@ -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 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 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 Recalculate(int writingPlanId) + => ReviewRecalculation(new() { WritingPlanID = writingPlanId }, null); + + [HttpPost("Recalculate"), ValidateAntiForgeryToken] + public Task Recalculate(WriterScheduleRecalculation model, string? step, int? authorUtcOffset) + => ReviewRecalculation(model, step, authorUtcOffset); + + private async Task 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 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 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 Load(int id) { var plan=await schedule.GetWritingPlanSettingsAsync(id); diff --git a/PlotLine/Data/WriterActivityRepository.cs b/PlotLine/Data/WriterActivityRepository.cs index 70d6e1ae..9223d060 100644 --- a/PlotLine/Data/WriterActivityRepository.cs +++ b/PlotLine/Data/WriterActivityRepository.cs @@ -7,4 +7,11 @@ public sealed class WriterActivityRepository(ISqlConnectionFactory factory) public async Task> Read(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterActivities_Manage",new{Action="read",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} public async Task> Entities(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync("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); + } } diff --git a/PlotLine/Data/WriterPlanningRepository.cs b/PlotLine/Data/WriterPlanningRepository.cs index 7305e644..9951bcd9 100644 --- a/PlotLine/Data/WriterPlanningRepository.cs +++ b/PlotLine/Data/WriterPlanningRepository.cs @@ -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> WorkingGroups(int userId, int bookId) + { + using var connection = factory.CreateConnection(); + var rows = await connection.QueryAsync("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> ReviewCandidates(WritingPlanViewModel plan) + { + using var connection = factory.CreateConnection(); + return (await connection.QueryAsync("dbo.WriterScheduleReviewCandidates", + new { plan.UserID, plan.ProjectID, plan.BookID, plan.IncludeBlockedScenes }, + commandType: CommandType.StoredProcedure)).AsList(); + } + + public async Task SaveNewSchedule(WritingPlanViewModel plan, WritingScheduleSetupViewModel setup, + IReadOnlyList allocations) + { + using var connection = factory.CreateConnection(); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var existing = await connection.QuerySingleAsync("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("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 pending, IReadOnlyList 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 ObservedDraftingRate(int userId, int bookId) + { + using var connection = factory.CreateConnection(); + return await connection.QuerySingleAsync("dbo.WriterScheduleObservedDrafting", + new { UserID = userId, BookID = bookId }, commandType: CommandType.StoredProcedure); + } + + public async Task> DailyFocus(int userId, int bookId) + { + using var connection = factory.CreateConnection(); + return (await connection.QueryAsync("dbo.WriterScheduleDailyFocus", + new { UserID = userId, BookID = bookId, UtcDate = DateTime.UtcNow.Date }, + commandType: CommandType.StoredProcedure)).AsList(); + } + + public async Task> CapacityOverlap(int userId, int? planId, + IReadOnlyList 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("dbo.WriterScheduleCapacityOverlap", + new { UserID = userId, WritingPlanID = planId, Dates = JsonSerializer.Serialize(dates) }, + commandType: CommandType.StoredProcedure)).AsList(); + } + public async Task> Read(int user,int plan,string action="list") {using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterPlanning",new{Action=action,UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure)).ToArray();} public async Task Context(int user,int plan) {using var db=factory.CreateConnection();return await db.QuerySingleAsync("dbo.WriterPlanning",new{Action="context",UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure);} public async Task Save(int user,int plan,IReadOnlyList 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> Upcoming(int user,int book) {using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterPlanningUpcoming",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} } diff --git a/PlotLine/Models/CoreModels.cs b/PlotLine/Models/CoreModels.cs index 2cc6d6ce..67ebc6bc 100644 --- a/PlotLine/Models/CoreModels.cs +++ b/PlotLine/Models/CoreModels.cs @@ -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; } diff --git a/PlotLine/Models/WriterPlanning.cs b/PlotLine/Models/WriterPlanning.cs index c61c9054..7f6b084a 100644 --- a/PlotLine/Models/WriterPlanning.cs +++ b/PlotLine/Models/WriterPlanning.cs @@ -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 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 ChapterIDs); + + +public sealed record WriterScheduleDailyFocus(DateTime ScheduledDate, int Minutes, decimal SuggestedWords); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 1cc85309..289553bd 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -164,6 +164,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/ApplicationNavigation.cs b/PlotLine/Services/ApplicationNavigation.cs index a5459f1c..2bfce839 100644 --- a/PlotLine/Services/ApplicationNavigation.cs +++ b/PlotLine/Services/ApplicationNavigation.cs @@ -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)) diff --git a/PlotLine/Services/ApplicationStartup.cs b/PlotLine/Services/ApplicationStartup.cs new file mode 100644 index 00000000..8fb6fd5c --- /dev/null +++ b/PlotLine/Services/ApplicationStartup.cs @@ -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 Destinations = new Dictionary + { + [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 WriterDestinations = new Dictionary + { + ["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(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(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(HttpContext context, int userId, string key) + { + if (!context.Request.Cookies.TryGetValue(CookieName(userId, key), out var value)) return default; + try { return JsonSerializer.Deserialize(Protector(userId, key).Unprotect(value)); } + catch (Exception ex) when (ex is CryptographicException or JsonException) { return default; } + } + + private void Write(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}"; +} diff --git a/PlotLine/Services/Context/ContextIntentChecklist.cs b/PlotLine/Services/Context/ContextIntentChecklist.cs index 1b57ee68..727b98da 100644 --- a/PlotLine/Services/Context/ContextIntentChecklist.cs +++ b/PlotLine/Services/Context/ContextIntentChecklist.cs @@ -147,7 +147,49 @@ public sealed class ContextIntentChecklist(ISqlConnectionFactory connections, IC catch (JsonException) { return false; } } - public async Task 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 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 Load(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save = null) + => LoadCore(bookId, chapterId, sceneId, save, notify: true); + + private async Task 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, diff --git a/PlotLine/Services/Context/ContextIntentText.cs b/PlotLine/Services/Context/ContextIntentText.cs index 0d9dee93..d2bd2d6e 100644 --- a/PlotLine/Services/Context/ContextIntentText.cs +++ b/PlotLine/Services/Context/ContextIntentText.cs @@ -41,6 +41,42 @@ public static partial class ContextIntentText return result; } + public sealed record ChapterPasteSection(string Heading, string Body); + + [GeneratedRegex(@"^\s*(?:#{1,6}\s+(?.+)|(?Chapter\s+.+?))\s*$", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex ChapterHeading(); + + public static IReadOnlyList ParseChapters(string input) + { + if (input.Length > 64_000) throw new ArgumentException("Paste 64,000 characters or fewer."); + var sections = new List(); + 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 Deduplicate(IEnumerable entities) diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 0105f4d7..106ce5a3 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -619,7 +619,7 @@ public interface IWritingScheduleService Task> RegenerateScheduleAsync(int writingPlanId); Task GetScheduleSetupAsync(int? projectId); Task PopulateScheduleSetupOptionsAsync(WritingScheduleSetupViewModel model); - Task CreateScheduleFromSetupAsync(WritingScheduleSetupViewModel model); + Task PrepareScheduleFromSetupAsync(WritingScheduleSetupViewModel model); Task GetTodayDashboardAsync(int? projectId = null, int? bookId = null); Task MarkScheduleItemCompleteAsync(int writingScheduleItemId); Task 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 CreateScheduleFromSetupAsync(WritingScheduleSetupViewModel model) + public async Task 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 GetTodayDashboardAsync(int? projectId = null, int? bookId = null) diff --git a/PlotLine/Services/Writer/WriterPlanning.cs b/PlotLine/Services/Writer/WriterPlanning.cs index efee5bb8..0dd5e9be 100644 --- a/PlotLine/Services/Writer/WriterPlanning.cs +++ b/PlotLine/Services/Writer/WriterPlanning.cs @@ -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 Allocations) +{ + public int AlreadyAllocated { get; init; } + public int Usable => Available - Reserved - AlreadyAllocated; +} + public static class WriterPlanning { - public static IReadOnlyList Allocate(WritingPlanSettingsEditViewModel plan,IReadOnlyList 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.Date3650)throw new ArgumentException("Choose a planning window of at most ten years."); - var availability=plan.WritingDayAvailability.Where(x=>x.IsAvailable).ToDictionary(x=>Enum.Parse(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();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 selected, int minimumBudget = 5, + IReadOnlyList? 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 Allocate(WritingPlanSettingsEditViewModel plan, + IReadOnlyList 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 Capacity(DateTime start, DateTime target, + IReadOnlyList days, int contingency, IReadOnlyList 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(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(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(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 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 Fit(IReadOnlyList dates, IReadOnlyList work) + { + var usable = dates.Where(date => date.Usable > 0).ToArray(); + var result = new List(); + 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; + } } diff --git a/PlotLine/Services/WriterNavigation.cs b/PlotLine/Services/WriterNavigation.cs index 3bbaddab..46129586 100644 --- a/PlotLine/Services/WriterNavigation.cs +++ b/PlotLine/Services/WriterNavigation.cs @@ -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")) diff --git a/PlotLine/Sql/352_WriterScheduleReview.sql b/PlotLine/Sql/352_WriterScheduleReview.sql new file mode 100644 index 00000000..cdf9d1ed --- /dev/null +++ b/PlotLine/Sql/352_WriterScheduleReview.sql @@ -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 diff --git a/PlotLine/Sql/353_WriterWorkingGroups.sql b/PlotLine/Sql/353_WriterWorkingGroups.sql new file mode 100644 index 00000000..ffe79662 --- /dev/null +++ b/PlotLine/Sql/353_WriterWorkingGroups.sql @@ -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 diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index b73067e0..0594ce76 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -949,6 +949,8 @@ public sealed class WriterDashboardViewModel public int? ProjectID { get; set; } public IReadOnlyList ProjectOptions { get; set; } = []; + public IReadOnlyList ScheduleDailyFocus { get; set; } = []; + public WriterWorkingGroup? CurrentWorkingGroup { get; set; } public WritingScheduleDashboardViewModel WritingSchedule { get; set; } = new(); public IReadOnlyList WriteNext { get; set; } = []; public IReadOnlyList 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 WorkingGroups { get; set; } = []; + + public List Candidates { get; set; } = []; + public Services.Writer.WriterCapacityPreview? Capacity { get; set; } + public Guid CreationToken { get; set; } = Guid.NewGuid(); + public string? ReviewFingerprint { get; set; } + public IReadOnlyList OverlapDates { get; set; } = []; + public IReadOnlyList ProjectOptions { get; set; } = []; public IReadOnlyList BookOptions { get; set; } = []; public IReadOnlyList 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(); diff --git a/PlotLine/Views/Home/Startup.cshtml b/PlotLine/Views/Home/Startup.cshtml new file mode 100644 index 00000000..227db979 --- /dev/null +++ b/PlotLine/Views/Home/Startup.cshtml @@ -0,0 +1,18 @@ +@model string +@{ + ViewData["Title"] = "Start page"; +} +

Start page

+
+ + +
+ + Cancel +
+
diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index a4332c31..e3064e31 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -10,7 +10,7 @@ }
- PlotDirector + PlotDirector @if (appearance.ShowProjectContextMenu || (appearance.ShowBookContextMenu && project is not null)) { @@ -86,6 +86,7 @@
  • Manage Account
  • +
  • Start page
  • Setup preferences
  • @if (!(ViewData["ShellClass"] as string ?? "").Contains("marketing-shell", StringComparison.OrdinalIgnoreCase)) { diff --git a/PlotLine/Views/Writer/EditWritingPlan.cshtml b/PlotLine/Views/Writer/EditWritingPlan.cshtml index f54c3bd4..3df05b50 100644 --- a/PlotLine/Views/Writer/EditWritingPlan.cshtml +++ b/PlotLine/Views/Writer/EditWritingPlan.cshtml @@ -60,11 +60,7 @@ -
    - - - -
    +
    diff --git a/PlotLine/Views/Writer/Index.cshtml b/PlotLine/Views/Writer/Index.cshtml index 966b1ed8..2ac26be4 100644 --- a/PlotLine/Views/Writer/Index.cshtml +++ b/PlotLine/Views/Writer/Index.cshtml @@ -8,6 +8,31 @@
    @if(!Model.BookID.HasValue){

    Select a project and book in the application bar, or open your projects to begin. You can explore writing problems before you have a manuscript.

    } + @if (Model.BookID.HasValue) + { +
    +

    Current work

    + @if (Model.CurrentWorkingGroup is { } group) + { +

    Current group · @group.Name

    + } + @if (Model.Objective is { } objective) + { +

    @objective.Activity · @(objective.SceneTitle ?? objective.ChapterTitle ?? "Across the book")

    + } + + + +
    + }
    @@ -20,14 +45,22 @@

    Explore Your Story

    Develop ideas, solve problems
    and discover what happens next.

    No completed plan or linked Word document needed. Go to Explore
    - - -

    Writing Dashboard

    See plans, progress, activity
    and your writing journey.

    Your recorded work and the work ahead. - Open Dashboard + @if (Model.BookID.HasValue) + { +
    +

    Plan your story

    Review narrative intent in Context.

    +
    + } + +

    Organise work

    Order activities and plan writing time when it helps.

    +
    + +

    Writing journey

    See your recorded work.

    @section Scripts { + diff --git a/PlotLine/Views/Writer/SchedulePreview.cshtml b/PlotLine/Views/Writer/SchedulePreview.cshtml index ec30f965..aff57ab2 100644 --- a/PlotLine/Views/Writer/SchedulePreview.cshtml +++ b/PlotLine/Views/Writer/SchedulePreview.cshtml @@ -113,7 +113,7 @@ else } - Review activities from chapters and scenes + Review or recalculate writing activities @if(Model.Items.Count>0){
    diff --git a/PlotLine/Views/Writer/ScheduleSetup.cshtml b/PlotLine/Views/Writer/ScheduleSetup.cshtml index 7b47091c..033bfd7f 100644 --- a/PlotLine/Views/Writer/ScheduleSetup.cshtml +++ b/PlotLine/Views/Writer/ScheduleSetup.cshtml @@ -1,18 +1,18 @@ @model WritingScheduleSetupViewModel @{ ViewData["DesktopLayout"] = "wide"; - ViewData["Title"] = "Schedule Setup"; + ViewData["Title"] = "Create Writing Schedule"; }

    Writing schedule

    -

    Schedule Setup

    +

    Create Writing Schedule

    Plan for the selected book, or choose All Books for a project-wide plan.

    Skip scheduling · return to Writer
    @@ -29,7 +29,7 @@
    - +
    @@ -50,24 +50,48 @@
    + @if (Model.WorkingGroups.Count > 0 || Model.WorkingGroupID.HasValue) + { +
    + + +
    + } +
    - +
    - - + +
    - - - + + + +
    +
    + + + + @if (Model.ObservedDraftingWordsPerHour is > 0) + { +

    Observed pace from matched drafting sessions · @Model.ObservedDraftingWordsPerHour words per hour.

    + + }
    @@ -111,13 +135,103 @@
    -
    - - Schedule Preview + @if (Model.Candidates.Count > 0) + { +

    Choose work and review effort

    + @if (Model.WorkingGroupID.HasValue) + { +

    This schedule reserves time for the group. Choose any chapter in the group when you sit down to write.

    + } +

    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.

    +
    + + + + @for (var i = 0; i < Model.Candidates.Count; i++) + { + var row = Model.Candidates[i]; + + + + + + + } + +
    IncludeChapter / sceneActivityMinutes
    + + + + + @row.BookTitle · @row.Title + +
    +
    + } + else if (Context.Request.Method == "POST" && ViewData.ModelState.IsValid) + { +

    No eligible work was found. Choose a different book, add a chapter, or include blocked scenes.

    + } + + @if (Model.Capacity is { } capacity) + { +
    +

    Schedule preview

    +
    +
    Available
    @capacity.Available min
    +
    Reserved for contingency
    @capacity.Reserved min
    +
    Usable
    @capacity.Usable min
    +
    Required
    @capacity.Required min
    +
    Shortfall
    @capacity.Shortfall min
    +
    Forecast
    @(capacity.Forecast?.ToString("d MMM yyyy") ?? "Unavailable")
    +
    + @if (Model.OverlapDates.Count > 0) + { +

    Other active plans also use @Model.OverlapDates.Count of these dates. Check your combined time before saving.

    + } + @if (capacity.Shortfall > 0) + { +

    The selected work exceeds usable time. Change the work, availability, contingency, or target date and preview again.

    + } + else if (capacity.Allocations.Count == 0) + { +

    Select at least one activity to preview a schedule.

    + } + else + { +
      + @foreach (var day in capacity.Allocations.GroupBy(item => item.ScheduledDate)) + { +
    • @day.Key.ToString("d MMM yyyy") · @day.Sum(item => item.Minutes) min · @string.Join(", ", day.Select(item => item.Title).Distinct())
    • + } +
    + } +
    + } + + + +
    + @if (Model.Capacity?.Allocations.Count > 0) + { + + } + @if (Model.Candidates.Count > 0) + { + + } + + Cancel
    @section Scripts { + } diff --git a/PlotLine/Views/Writer/WritingPlans.cshtml b/PlotLine/Views/Writer/WritingPlans.cshtml index 4d9d0ed3..089856cf 100644 --- a/PlotLine/Views/Writer/WritingPlans.cshtml +++ b/PlotLine/Views/Writer/WritingPlans.cshtml @@ -98,10 +98,11 @@ } Review chapter activities +
    Legacy scene scheduling
    -
    +
    diff --git a/PlotLine/Views/Writer/_ActivityCard.cshtml b/PlotLine/Views/Writer/_ActivityCard.cshtml index 4046c794..abd6e6ee 100644 --- a/PlotLine/Views/Writer/_ActivityCard.cshtml +++ b/PlotLine/Views/Writer/_ActivityCard.cshtml @@ -1,6 +1,6 @@ @model PlotLine.Models.WriterActivity -
    -

    @Model.Title

    @Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){}

    +
    +

    @Model.Title

    @Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){}

    @if(!string.IsNullOrWhiteSpace(Model.Notes)){

    @Model.Notes

    } Updated @Model.UpdatedUtc.ToString("d MMM yyyy HH:mm") UTC
    diff --git a/PlotLine/Views/Writer/_ActivityPlanner.cshtml b/PlotLine/Views/Writer/_ActivityPlanner.cshtml index 387c2959..a443e565 100644 --- a/PlotLine/Views/Writer/_ActivityPlanner.cshtml +++ b/PlotLine/Views/Writer/_ActivityPlanner.cshtml @@ -4,7 +4,25 @@
    @foreach(var view in new[]{"list","board","schedule"}){}

    Add planned activity
    @if(active.Length==0){

    No planned activities yet. Add one when it helps you organise your work.

    } - @if(Model.View=="board"){
    @foreach(var status in PlotLine.Models.WriterActivity.Statuses){

    @status

    @foreach(var item in active.Where(x=>x.Status==status)){}
    }
    } + @if (Model.View == "board") + { + +
    + @foreach (var status in PlotLine.Models.WriterActivity.Statuses) + { + var cards = active.Where(item => item.Status == status).ToArray(); +
    +

    @status (@cards.Length)

    + @foreach (var item in cards) + { + + } +
    + } +
    + } else if(Model.View=="schedule"){

    Dated activities

    @foreach(var item in active.Where(x=>x.TargetDate.HasValue).OrderBy(x=>x.TargetDate)){}

    Undated activities

    @foreach(var item in active.Where(x=>!x.TargetDate.HasValue)){} diff --git a/PlotLine/Views/Writer/_PlannedActivities.cshtml b/PlotLine/Views/Writer/_PlannedActivities.cshtml index d4a2c898..442eb4dd 100644 --- a/PlotLine/Views/Writer/_PlannedActivities.cshtml +++ b/PlotLine/Views/Writer/_PlannedActivities.cshtml @@ -1,2 +1,2 @@ @model IReadOnlyList -@if(Model.Count>0){

    Reviewed writing activities

    @Model.Count allocations · @Model.Sum(x=>x.Minutes) planned minutes · these budgets are not measured work.

    @foreach(var item in Model){}
    DateWorkActivityMinutesStatus
    @item.ScheduledDate.ToString("d MMM yyyy")@if(item.SceneID.HasValue){@item.Title}else{@item.Title}@item.Kind@item.Minutes@item.Status @if(item.Status=="Planned"){
    }
    } +@if(Model.Count>0){

    Reviewed writing activities

    @Model.Count allocations · @Model.Sum(x=>x.Minutes) planned minutes · these budgets are not measured work.

    @foreach(var item in Model){}
    DateWorkActivityMinutesStatus
    @item.ScheduledDate.ToString("d MMM yyyy")@if(item.GroupID.HasValue){@item.Title}else if(item.SceneID.HasValue){@item.Title}else{@item.Title}@item.Kind@item.Minutes@item.Status @if(item.Status=="Planned"){
    }
    } diff --git a/PlotLine/Views/Writer/_WriterPlan.cshtml b/PlotLine/Views/Writer/_WriterPlan.cshtml index fab1f725..4a1ca9a5 100644 --- a/PlotLine/Views/Writer/_WriterPlan.cshtml +++ b/PlotLine/Views/Writer/_WriterPlan.cshtml @@ -2,9 +2,10 @@

    Planned activities

    What you intend to accomplish. Starting work is separate from recording a session.

    +

    Working groups

    Loading your activities…