Deliver book-scoped Writer dashboard, calendar, workspaces and contextual ribbon
This commit is contained in:
parent
a369e7dcd2
commit
364842f0a3
@ -6,7 +6,7 @@ Authorisation: attached overnight implementation instructions, following the app
|
||||
|
||||
The first increment retains counts and identifiers, not a second manuscript or historical prose archive. The existing paragraph manuscript and chapter acceptance engine remain authoritative. `ParagraphManuscriptRepository` holds the canonical row lock and commits the established stored-procedure save and activity append together. A failed append rolls back that acceptance; Word's document is unchanged and the caller may retry. No unchanged chapter validation is counted as writing output.
|
||||
|
||||
Events have server receipt UTC, optional native observation UTC, source/provenance, request/event identity, schema/metric version, manuscript/book/project, optional transport session/chapter and old/new paragraph/scene associations. Snapshot references are hashes/revisions; old prose cannot be reconstructed from this ledger. Initial or explicit current baseline contributes no new writing output. Existing manuscripts receive a baseline on their first recorded change, or an owner can explicitly record the current accepted baseline. No historical backfill is fabricated.
|
||||
Events have server receipt UTC, optional native observation UTC, source/provenance, request/event identity, schema/metric version, manuscript/book/project, optional transport session/chapter and old/new paragraph/scene associations. Snapshot references are hashes/revisions; old prose cannot be reconstructed from this ledger. Initial or explicit current baseline contributes no new writing output. Existing manuscripts receive a metadata-only current baseline at startup/daily discovery under source System, respecting per-book pause settings. A concurrent first change is also protected by transactional baseline insertion, and owners can explicitly record a baseline. Discovery pages 100 books at a time without changing canonical prose/revisions. No historical backfill is fabricated.
|
||||
|
||||
Word changes use whitespace-v1 tokens and paragraph-local LCS; recognised moved paragraphs retain identity without new words, unmatched splits/merges are compared together. Very large replacement comparisons use an explicitly labelled partial minimum token-balance estimate to bound processing. Additions minus removals always equals the comparable word-count difference; these are sampled accepted differences, not keystrokes. Formatting not present in capture cannot be measured. No sessions or continuous focus duration are inferred.
|
||||
|
||||
@ -23,6 +23,8 @@ Word changes use whitespace-v1 tokens and paragraph-local LCS; recognised moved
|
||||
|
||||
The agent's existing DPAPI-protected installation state now holds up to 128 source observations with immutable event identities, server/account scope and original UTC. No prose is queued. Known unsaved chapter-change signals use this queue; delivery waits for normal authenticated connection recovery, runs independently of manuscript synchronisation and acknowledges exact request identity. Entries survive a restart, transient failures and sign-out/account switching without being reassigned to another account. Failed deliveries back off and remain pending; queue/storage failures expose incomplete observation coverage rather than changing sync behaviour.
|
||||
|
||||
Pending outbox entries use protected state schema 2, which older agents refuse rather than silently dropping unknown fields. After the queue drains, settings return to compatible schema 1. Do not force re-pair or replace protected settings to work around an older-agent downgrade while observations remain pending.
|
||||
|
||||
The old coalescing DeferredWorkQueue is deliberately not connected as a prose sender: it cannot preserve exact activity observations and contains no text. Final saved offline changes still reconcile via the established synchronisation path; the new queue does not claim to capture edits that were never observed, survive every Word crash, or reconstruct offline sessions. Observations outside the server's 30-day/five-minute-future window are retained locally pending resolution, not falsely timestamped at receipt. A blocked or full queue needs attention; it does not stop normal manuscript synchronisation.
|
||||
|
||||
Native source/portable qualification is distinct from Windows installer/COM acceptance. No Windows execution, real monitor placement or signed installer is claimed by this sprint.
|
||||
|
||||
@ -1,120 +1,48 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const base = 'http://127.0.0.1:5238';
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
for (const pwa of [false,true]) {
|
||||
const context = await browser.newContext({viewport:{width:1600,height:1000}});
|
||||
if (pwa) await context.addInitScript(() => Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
const page = await context.newPage();
|
||||
const errors=[];page.on('pageerror',error=>{errors.push(error.message);console.error(page.url(),error.stack);}); context.on('page',popup=>popup.on('pageerror',error=>errors.push(error.message)));
|
||||
// Use the real SDK, production Hub/presence services, full Razor layout and scripts.
|
||||
// Only the first network negotiation is failed; subsequent traffic reaches the loopback Hub.
|
||||
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8') + `
|
||||
;window.__writerConnections=[];const originalHubBuild=signalR.HubConnectionBuilder.prototype.build;signalR.HubConnectionBuilder.prototype.build=function(){const connection=originalHubBuild.call(this);window.__writerConnections.push(connection);return connection;};`}));
|
||||
let negotiations=0;
|
||||
await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue());
|
||||
await page.goto(base+'/fixture?page=writer&layout=full');
|
||||
await page.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace);
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Unavailable');
|
||||
assert.equal(negotiations,1,'Initial failed connection is not retried in a tight loop');
|
||||
const start=page.getByRole('button',{name:'Start / Reapply Workspace',exact:true});
|
||||
await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;});
|
||||
await start.click();
|
||||
await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled);
|
||||
assert.ok(negotiations>=2,'A user command must retry after the initial connection failure');
|
||||
assert.equal(await page.locator('[data-writing-workspace-word]').textContent(),'Not connected');
|
||||
await page.evaluate(()=>window.open=window.__originalWindowOpen);
|
||||
const windows=[];
|
||||
for(const role of ['context','intent']){
|
||||
const opened=context.waitForEvent('page');
|
||||
await page.locator(`[data-open-writing-${role}]`).click();
|
||||
const popup=await opened;await popup.waitForLoadState();
|
||||
assert.equal(await popup.locator('[data-writing-mode]').count(),1,'Production writing-window view renders successfully');
|
||||
windows.push(popup);
|
||||
}
|
||||
const identities=await Promise.all(context.pages().map(tab=>tab.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId())));
|
||||
assert.equal(new Set(identities).size,3,'Launcher, Context and Intent must have distinct presence identities even when sessionStorage is cloned from an opener');
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Open' && document.querySelector('[data-writing-workspace-intent]').textContent==='Open');
|
||||
for(const popup of windows){
|
||||
const before=await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId());
|
||||
await popup.reload();await popup.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace);
|
||||
assert.equal(await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId()),before,'Reload preserves the identity owned by this window');
|
||||
}
|
||||
await page.locator('[data-focus-writing-context]').click();
|
||||
await page.locator('[data-focus-writing-intent]').click();
|
||||
assert.equal(context.pages().length,3,'Focus commands reuse the existing writing windows');
|
||||
const oldContext=windows[0];
|
||||
const oldContextUrl=oldContext.url();
|
||||
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:13}})));
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-book]').textContent==='Book 13');
|
||||
await page.evaluate(async()=>{
|
||||
await window.PlotDirectorWritingWorkspace.watchWorkspace({projectID:7,bookID:13});
|
||||
document.addEventListener('plotdirector:writing-workspace-status',event=>{
|
||||
if((event.detail?.bookID||event.detail?.BookID)===12)window.__labelDuringOtherBookUpdate=document.querySelector('[data-writing-workspace-book]').textContent;
|
||||
});
|
||||
});
|
||||
await oldContext.evaluate(()=>window.__writerConnections.at(-1).invoke('WritingWindowHeartbeat',{
|
||||
browserWindowID:window.PlotDirectorWritingWorkspace.getBrowserWindowId(),projectID:7,bookID:12,writingRole:'Context',currentRoute:location.pathname
|
||||
}));
|
||||
await page.waitForFunction(()=>window.__labelDuringOtherBookUpdate!==undefined);
|
||||
assert.equal(await page.evaluate(()=>window.__labelDuringOtherBookUpdate),'Book 13','Another book heartbeat cannot change the selected workspace');
|
||||
await page.locator('[data-open-writing-context]').click();
|
||||
await page.waitForFunction(()=>!document.querySelector('[data-open-writing-context]').disabled);
|
||||
assert.equal(context.pages().length,4,'Changing books opens a separately scoped Context window');
|
||||
assert.equal(oldContext.url(),oldContextUrl,'The first book context is preserved');
|
||||
const secondContext=context.pages().find(tab=>tab!==page&&!windows.includes(tab));
|
||||
await secondContext.waitForLoadState();
|
||||
assert.equal(new URL(secondContext.url()).searchParams.get('bookId'),'13');
|
||||
await secondContext.close();
|
||||
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12}})));
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-book]').textContent==='Book 12');
|
||||
const beforeRestart=negotiations;
|
||||
await page.evaluate(()=>window.__writerConnections.at(-1).stop());
|
||||
await start.click();
|
||||
await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled);
|
||||
assert.ok(negotiations>beforeRestart,'A terminal disconnect permits a fresh connection');
|
||||
assert.equal(context.pages().length,3,'Reapply reuses existing Context/Intent windows');
|
||||
for(const popup of windows)await popup.close();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Not open');
|
||||
await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;});
|
||||
await page.getByRole('button',{name:'Open Context',exact:true}).click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-message]').textContent.includes('blocked'));
|
||||
assert.equal(await page.getByRole('button',{name:'Open Context',exact:true}).isEnabled(),true);
|
||||
await page.evaluate(()=>window.open=window.__originalWindowOpen);
|
||||
await page.route('**/Locations?*',async route=>route.fulfill({response:await page.request.get(base+'/fixture?desktop=Locations')}));
|
||||
for(let pass=0;pass<3;pass++){
|
||||
await page.getByRole('tab',{name:'World',exact:true}).click();
|
||||
await page.getByRole('link',{name:'Locations',exact:true}).first().click();
|
||||
await page.waitForURL('**/Locations?*');
|
||||
assert(await page.locator('.location-page').isVisible());
|
||||
await page.getByRole('tab',{name:'Project',exact:true}).click();
|
||||
await page.getByRole('link',{name:'Writer',exact:true}).first().click();
|
||||
await page.waitForURL(url=>url.pathname==='/Writer');
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent!=='Checking...');
|
||||
assert(await page.getByRole('button',{name:'Start / Reapply Workspace',exact:true}).isEnabled());
|
||||
}
|
||||
await page.evaluate(()=>{window.__screenDetails=window.getScreenDetails;Object.defineProperty(window,'getScreenDetails',{value:undefined,configurable:true});});
|
||||
await page.getByRole('button',{name:'Detect displays',exact:true}).click();
|
||||
await page.waitForFunction(()=>!document.querySelector('[data-detect-writing-displays]').disabled);
|
||||
assert.match(await page.locator('[data-writing-workspace-message]').textContent(),/unavailable/);
|
||||
const focus= pwa ? page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Focus',exact:true}) : page.locator('.writer-dashboard-heading').getByRole('button',{name:'Focus',exact:true});
|
||||
await focus.click();
|
||||
await page.waitForURL(url=>url.pathname==='/Writer'&&url.searchParams.get('projectId')==='7');
|
||||
for(const [name,route] of [['Writing Plans','WritingPlans'],['Schedule Setup','ScheduleSetup'],['Schedule Preview','SchedulePreview']]){
|
||||
const host=pwa?page.locator('[data-pwa-context-controls]'):page.locator('.writer-dashboard-heading');
|
||||
const link=host.getByRole('link',{name,exact:true,includeHidden:true});
|
||||
const menu=link.locator('xpath=ancestor::details[@data-compact="true"]').last();
|
||||
if(await menu.count()&&!(await menu.evaluate(node=>node.open)))await menu.locator(':scope > summary').click();
|
||||
const response=page.waitForResponse(response=>response.request().isNavigationRequest()&&new URL(response.url()).pathname==='/Writer/'+route);
|
||||
await link.click();assert.equal((await response).status(),200,name+' real controller/view route');
|
||||
await page.goto(base+'/Writer');
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
await context.close();
|
||||
// Exercise the retained reference-window/presence workflow through the Writer 2 layout.
|
||||
const {chromium}=require('playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs');
|
||||
const base='http://127.0.0.1:5238';
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
for(const pwa of [false,true]){
|
||||
const context=await browser.newContext({viewport:{width:1600,height:1000}});
|
||||
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
let negotiations=0;
|
||||
await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue());
|
||||
await page.goto(base+'/fixture?page=writer&layout=full');
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Unavailable');
|
||||
assert.equal(negotiations,1,'No tight retry loop after initial network failure');
|
||||
await page.locator('#display-setup > summary').click();
|
||||
assert.equal(await page.locator('[data-start-writing-workspace]').isVisible(),false,'A disconnected book has no linked-Word controls');
|
||||
await page.evaluate(()=>{window.__open=window.open;window.open=()=>null;});
|
||||
await page.locator('[data-open-writing-context]').click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-message]').textContent.includes('blocked'));
|
||||
assert(negotiations>=2,'Manual reference-window command retries connection');
|
||||
await page.evaluate(()=>window.open=window.__open);
|
||||
const windows=[];
|
||||
for(const role of ['context','intent']){
|
||||
const opened=context.waitForEvent('page');await page.locator(`[data-open-writing-${role}]`).click();const popup=await opened;await popup.waitForLoadState();
|
||||
await popup.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace);windows.push(popup);
|
||||
}
|
||||
console.log('PASS full-layout Writer browser/PWA negotiation recovery, terminal reconnect, actual Context/Intent windows, blocked pop-ups and repeated section navigation');
|
||||
} finally {await browser.close();}
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Open'&&document.querySelector('[data-writing-workspace-intent]').textContent==='Open');
|
||||
const identities=await Promise.all(context.pages().map(tab=>tab.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId())));
|
||||
assert.equal(new Set(identities).size,3,'Each window owns a distinct presence identity');
|
||||
await page.locator('[data-focus-writing-context]').click();await page.locator('[data-focus-writing-intent]').click();assert.equal(context.pages().length,3,'Focus reuses existing windows');
|
||||
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:13}})));
|
||||
assert.equal(await page.locator('[data-writing-workspace-book]').textContent(),'Book 12','Word activity in another book cannot retarget the selected dashboard');
|
||||
await page.evaluate(()=>Object.defineProperty(window,'getScreenDetails',{value:undefined,configurable:true}));
|
||||
await page.locator('[data-detect-writing-displays]').click();await page.waitForFunction(()=>!document.querySelector('[data-detect-writing-displays]').disabled);
|
||||
assert.match(await page.locator('[data-writing-workspace-message]').textContent(),/unavailable/);
|
||||
await page.evaluate(()=>Object.defineProperty(window,'getScreenDetails',{value:async()=>{throw new DOMException('denied','NotAllowedError');},configurable:true}));
|
||||
await page.locator('[data-detect-writing-displays]').click();await page.waitForFunction(()=>!document.querySelector('[data-detect-writing-displays]').disabled);
|
||||
assert.match(await page.locator('[data-writing-workspace-message]').textContent(),/denied/);
|
||||
for(const popup of windows)await popup.close();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Not open');
|
||||
const response=page.waitForResponse(r=>r.request().isNavigationRequest()&&new URL(r.url()).pathname==='/Writer/WritingPlans');
|
||||
await page.locator('#ribbon-panel-writer').getByRole('link',{name:'Writing Plan',exact:true}).click();assert.equal((await response).status(),200,'Existing plans remain reachable through the ribbon');
|
||||
assert.deepEqual(errors,[]);await context.close();
|
||||
}
|
||||
console.log('PASS Writer reference windows: initial failure/retry, window identity/reuse, pinned book, denied/unavailable display permissions, plan navigation, browser/PWA.');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
|
||||
31
PlotLine.Tests/Browser/writer2-dashboard.cjs
Normal file
31
PlotLine.Tests/Browser/writer2-dashboard.cjs
Normal file
@ -0,0 +1,31 @@
|
||||
const {chromium}=require('playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs');
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
for(const pwa of [false,true]){
|
||||
const context=await browser.newContext();if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
for(const populated of [false,true])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark'])for(const width of [390,1024,1440]){
|
||||
await page.setViewportSize({width,height:1000});await page.addInitScript(theme=>localStorage.setItem('plotdirector.applicationTheme',theme),theme);
|
||||
await page.goto(`http://127.0.0.1:5238/writer2-fixture?populated=${populated}`);
|
||||
assert.equal(await page.locator('h1').textContent(),'A Distant Shore');
|
||||
assert.equal(await page.locator('.pd-ribbon-navigation').filter({hasText:/^Writer$/}).count(),1);
|
||||
assert.equal(await page.locator('#ribbon-panel-writer').isVisible(),true);
|
||||
assert.equal(await page.locator('.writer-tabs a').count(),5);
|
||||
assert.equal(await page.locator('.writer-heading select').count(),0,'Book/project selection belongs to common shell');
|
||||
const choices=await page.locator('[data-app-book-choice]').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('href')));assert(choices.length>0);assert(choices.every(href=>new URL(href,'http://127.0.0.1:5238').pathname==='/Writer'),'Common book selection stays in Writer');
|
||||
assert.equal(await page.locator('[data-start-writing-workspace]').isVisible(),false,'No linked document exposes no workspace reapply action');
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${theme} ${width} overflow`);
|
||||
assert.equal(await page.locator('[data-writer-queue="WriteNext"]').isVisible(),true);
|
||||
assert.equal(await page.locator('[data-writer-queue="Revision"]').isVisible(),false);
|
||||
if(populated){assert.equal(await page.locator('.writer-day').count(),28);assert.equal(await page.locator('.writer-day-observed').count(),2);assert.equal(await page.locator('.writer-indicators strong').nth(0).textContent(),'120');assert((await page.locator('.writer-day-observed').first().getAttribute('href')).includes('day='));}
|
||||
else{assert((await page.locator('.writer-empty').textContent()).includes('Earlier writing'));assert.equal(await page.locator('.writer-indicators strong').first().textContent(),'—');}
|
||||
await page.getByRole('link',{name:'Connection & Display Setup'}).click();await page.waitForFunction(()=>document.getElementById('display-setup').open);assert.equal(await page.locator('#display-setup').getAttribute('open'),'');
|
||||
if(theme==='warm-light'&&width===1440&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-sprint/writer2-desktop.png',fullPage:true});
|
||||
if(theme==='warm-light'&&width===390&&populated&&!pwa)await page.screenshot({path:'/home/nick/writer2-sprint/writer2-small.png',fullPage:true});
|
||||
}
|
||||
assert.deepEqual(errors,[]);await context.close();
|
||||
}
|
||||
console.log('PASS Writer 2 overview: real Razor, 48 theme/viewport/history/PWA combinations, single navigation, book scope, honest empty states, chart links and contextual controls.');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -45,6 +45,8 @@ internal static class NativeCompanionHttpTests
|
||||
using(var bitmap=new SkiaSharp.SKBitmap(20,30)){using var image=SkiaSharp.SKImage.FromBitmap(bitmap);using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90);File.WriteAllBytes(coverFile,png.ToArray());}
|
||||
var coverReads=0;
|
||||
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
builder.Services.AddSingleton<ISqlConnectionFactory>(Proxy<ISqlConnectionFactory>((name,args)=>throw new Exception("Activity HTTP admission must not reach a database")));
|
||||
builder.Services.AddScoped<WritingActivityRepository>();
|
||||
builder.Services.AddSingleton<IStoryIntelligenceClient>(provider);
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>{if(n=="GetCoverPathsAsync")coverReads++;return Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book",CoverThumbnailPath="/uploads/books/3/cover.webp"});}));
|
||||
builder.Services.AddSingleton(Proxy<IUploadStorageService>((n,a)=>n=="TryResolvePublicPath"&&Equals(a![1],"uploads/books/3")?coverFile:throw new Exception("Unexpected cover path lookup")));
|
||||
@ -76,6 +78,7 @@ internal static class NativeCompanionHttpTests
|
||||
using var browserHandler=new HttpClientHandler{AllowAutoRedirect=false};using var browser=new HttpClient(browserHandler){BaseAddress=new Uri(address)};
|
||||
using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)};
|
||||
Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous");
|
||||
Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.Unauthorized,"Activity observation requires a native grant before any database access");
|
||||
var anonymousHub=(await agent.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null)).StatusCode;Check(anonymousHub is HttpStatusCode.Unauthorized or HttpStatusCode.Redirect,"Anonymous native hub subscription refused");
|
||||
var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
var oversized=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge=new string('A',64),padding=new string('x',5000)});Check(!oversized.IsSuccessStatusCode,"Oversized pairing bodies are refused before pairing state creation");
|
||||
@ -89,6 +92,7 @@ internal static class NativeCompanionHttpTests
|
||||
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code},{"retainImport","true"},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds");
|
||||
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
|
||||
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
|
||||
Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.BadRequest,"Native activity rejects malformed identities before database access");
|
||||
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
|
||||
var listed=(await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single();Check(listed.ProjectTitle=="Fixture"&&listed.BookTitle=="Test book","Native book selection includes author-facing project and book names");
|
||||
Check((await agent.GetAsync("/api/native-companion/books/999/cover")).StatusCode==HttpStatusCode.Forbidden&&coverReads==0,"Foreign book cover denied before private file lookup");
|
||||
|
||||
@ -168,6 +168,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
|
||||
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
|
||||
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
|
||||
("Writer dashboard book scope",()=>WriterDashboardTests.Run().GetAwaiter().GetResult()),
|
||||
("Writing activity measurement", WritingActivityTests.Run),
|
||||
("Manuscript Reader", () => ManuscriptReaderTests.Run().GetAwaiter().GetResult()),
|
||||
("Paragraph manuscript identity, evidence and exact-session synchronisation", () => { ParagraphManuscriptTests.Run();ParagraphWorkflowTests.Run().GetAwaiter().GetResult(); }),
|
||||
|
||||
@ -88,7 +88,7 @@ internal static class ToolbarBrowserHost
|
||||
}
|
||||
|
||||
private static WriterDashboardViewModel WriterFixture() => new() {
|
||||
ProjectID = 7, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)],
|
||||
ProjectID = 7, BookID=12, Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"}, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)],
|
||||
WriteNext = [new() { ProjectID = 7, BookID = 12, BookTitle = "A Distant Shore", ChapterID = 21, ChapterNumber = 1, SceneID = 101, SceneNumber = 1, SceneTitle = "The crossing", RevisionStatusName = "Outlined", Summary = "A synthetic writing task." }]
|
||||
};
|
||||
|
||||
@ -169,6 +169,16 @@ internal static class ToolbarBrowserHost
|
||||
builder.Services.AddSingleton<IStoryCalendarService>(new StoryCalendarService(new FakeTimelineRepository(CalendarNavigationTests.Data())));
|
||||
var app = builder.Build();
|
||||
app.UseWritingSolverReviewBoundary();
|
||||
app.MapGet("/writer2-fixture",async (HttpContext context)=>{
|
||||
var model=WriterFixture();
|
||||
if(context.Request.Query["populated"]=="true")
|
||||
{
|
||||
var now=DateTime.UtcNow;
|
||||
model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,ActiveDays=2,RecordedEvents=3,AcceptedEvents=3,HasAcceptedEvidence=true,CoverageSinceUtc=now.AddDays(-2)},Days=[new(){Day=now.Date.AddDays(-1),Added=80,Removed=20,Changes=1},new(){Day=now.Date,Added=40,Removed=10,Changes=1}],Events=[new(){BookID=12,ReceivedUtc=now,Kind="Change",Source="WordCompanion",Added=40,Removed=10}]};
|
||||
}
|
||||
model.Workspace=context.Request.Query["workspace"].ToString() is "Revision"?"Revision":"WriteNext";
|
||||
await RenderFullAsync(context,"Writer","Index",model);
|
||||
});
|
||||
app.Urls.Add(Environment.GetEnvironmentVariable("PD_BROWSER_FIXTURE_URL") ?? "http://127.0.0.1:5238");
|
||||
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) });
|
||||
app.Use(async (context, next) =>
|
||||
|
||||
33
PlotLine.Tests/WriterDashboardTests.cs
Normal file
33
PlotLine.Tests/WriterDashboardTests.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
internal static class WriterDashboardTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Writer dashboard "+message);}
|
||||
int? scheduledBook=null;var allowed=true;
|
||||
var workspace=Proxy<IWriterWorkspaceService>((method,args)=>method=="GetDashboardAsync"?Task.FromResult(new WriterDashboardViewModel{ProjectID=1,WriteNext=[new(){BookID=2,SceneID=20},new(){BookID=3,SceneID=30}]}):throw new Exception(method));
|
||||
var schedule=Proxy<IWritingScheduleService>((method,args)=>{if(method!="GetTodayDashboardAsync")throw new Exception(method);scheduledBook=(int?)args![1];return Task.FromResult(new WritingScheduleDashboardViewModel{TodayTasks=[new(){BookID=2,SceneID=20},new(){BookID=3,SceneID=30}]});});
|
||||
var books=Proxy<IBookRepository>((method,args)=>method switch{"ListByProjectAsync"=>Task.FromResult<IReadOnlyList<Book>>([new(){BookID=2,ProjectID=1},new(){BookID=3,ProjectID=1}]),"GetAsync"=>Task.FromResult<Book?>(new(){BookID=(int)args![0]!,ProjectID=1}),_=>throw new Exception(method)});
|
||||
var access=Proxy<IProjectAccessService>((method,args)=>Task.FromResult(allowed));
|
||||
var controller=new WriterController(workspace,schedule,books,access);
|
||||
var result=(ViewResult)await controller.Index(1,3,"Revision");var model=(WriterDashboardViewModel)result.Model!;
|
||||
Check(model.BookID==3&&model.WriteNext.Single().SceneID==30&&model.WritingSchedule.TodayTasks.Single().SceneID==30,"book selection filters queues and tasks consistently");
|
||||
Check(scheduledBook==3&&model.Workspace=="Revision","book scope reaches schedule service before selection and active workspace persists");
|
||||
Check(await controller.Index(1,999) is NotFoundResult,"unknown book cannot fall back to another book");
|
||||
allowed=false;Check(await controller.Index(null,3) is NotFoundResult,"book-only deep link checks access before metadata");
|
||||
Check(controller.LegacyWrite(1,3) is RedirectToActionResult redirect&&(int?)redirect.RouteValues!["bookId"]==3,"legacy Write redirect preserves book scope");
|
||||
var ribbon=ApplicationRibbon.Categories.Single(c=>c.Key=="writer");Check(ribbon.Groups.SelectMany(g=>g.Commands).Any(c=>c.Action=="Workspaces")&&ribbon.Groups.SelectMany(g=>g.Commands).Any(c=>c.Controller=="WritingActivity"),"Writer contextual commands target implemented workspaces and evidence");
|
||||
}
|
||||
private static T Proxy<T>(Func<string,object?[]?,object?> action)where T:class {var value=DispatchProxy.Create<T,WriterProxy>();((WriterProxy)(object)value).Action=action;return value;}
|
||||
public class WriterProxy:DispatchProxy
|
||||
{
|
||||
public Func<string,object?[]?,object?> Action {get;set;}=null!;
|
||||
protected override object? Invoke(MethodInfo? targetMethod,object?[]? args)=>Action(targetMethod!.Name,args);
|
||||
}
|
||||
}
|
||||
@ -39,6 +39,11 @@ internal static class WritingActivityDatabaseTests
|
||||
await repository.Save(fixture.UserID,State("one new three four\r"),1,nextID);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==2,"exact retry is not counted twice");
|
||||
var observation=new WritingObservation{BookID=fixture.BookID,ManuscriptID=manuscript,ObservedUtc=DateTime.UtcNow,PayloadHash=new string('A',64)};
|
||||
await activity.Observe(fixture.UserID,observation);await activity.Observe(fixture.UserID,observation);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==3,"queued observation retry is idempotent");
|
||||
Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Single(e=>e.Kind=="Observation").SnapshotHash==null,"source observation never claims an accepted snapshot reference");
|
||||
Check((await activity.Read(fixture.UserID,fixture.BookID)).Totals.Net==1,"bounded dashboard aggregation reconciles accepted net without observation inflation");
|
||||
await db.ExecuteAsync("UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=NEWID() WHERE BookID=@BookID",new{fixture.BookID});
|
||||
try{await activity.Observe(fixture.UserID,observation);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==3,"lost acknowledgement remains idempotent after document identity changes");}
|
||||
finally{await db.ExecuteAsync("UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=@manuscript WHERE BookID=@BookID",new{fixture.BookID,manuscript});}
|
||||
observation.PayloadHash=new string('B',64);var rejected=false;try{await activity.Observe(fixture.UserID,observation);}catch(SqlException){rejected=true;}Check(rejected,"same observation identity with conflicting payload rejected");
|
||||
var wrongDocument=new WritingObservation{BookID=fixture.BookID,ManuscriptID=Guid.NewGuid(),ObservedUtc=DateTime.UtcNow,PayloadHash=new string('C',64)};
|
||||
rejected=false;try{await activity.Observe(fixture.UserID,wrongDocument);}catch(SqlException){rejected=true;}Check(rejected,"document switching cannot attach activity to another manuscript");
|
||||
@ -51,6 +56,13 @@ internal static class WritingActivityDatabaseTests
|
||||
try{rejected=false;try{await repository.Save(fixture.UserID,State("must roll back\r"),current.Revision,Guid.NewGuid());}catch(SqlException){rejected=true;}Check(rejected&&(await repository.Get(fixture.UserID,fixture.BookID))!.SnapshotHash==current.SnapshotHash,"partial activity failure rolls back canonical acceptance");}finally{await db.ExecuteAsync("DROP TRIGGER dbo.Writer2_TestReject");}
|
||||
await activity.Configure(fixture.UserID,fixture.BookID,false,30);var count=(await activity.Read(fixture.UserID,fixture.BookID)).Events.Count;await repository.Save(fixture.UserID,State("capture paused\r"),current.Revision,Guid.NewGuid());Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==count,"privacy pause does not block manuscript sync or record activity");
|
||||
await activity.Erase(fixture.UserID,fixture.BookID);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==0,"owner erasure leaves manuscript intact and capture paused");
|
||||
Check(!(await activity.BaselineTargets(fixture.BookID-1)).Any(t=>t.BookID==fixture.BookID),"automatic baseline discovery respects privacy pause");
|
||||
await activity.Configure(fixture.UserID,fixture.BookID,true,365);
|
||||
Check((await activity.BaselineTargets(fixture.BookID-1)).Any(t=>t.BookID==fixture.BookID&&t.UserID==fixture.UserID),"automatic baseline discovery selects existing accepted owner manuscripts");
|
||||
var baselineSource=(await repository.Get(fixture.UserID,fixture.BookID))!;
|
||||
await activity.Baseline(fixture.UserID,fixture.BookID,"System");await activity.Baseline(fixture.UserID,fixture.BookID,"System");
|
||||
var recorded=(await activity.Read(fixture.UserID,fixture.BookID)).Events.Single();var afterBaseline=(await repository.Get(fixture.UserID,fixture.BookID))!;
|
||||
Check(recorded.Kind=="Baseline"&&recorded.Source=="System"&&recorded.Added==0&&baselineSource.Revision==afterBaseline.Revision&&baselineSource.SnapshotHash==afterBaseline.SnapshotHash,"automatic baseline is idempotent metadata-only and never invents prior writing");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@ -2,20 +2,59 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
using PlotLine.Data;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class WriterController(
|
||||
IWriterWorkspaceService writerWorkspace,
|
||||
IWritingScheduleService writingSchedule) : Controller
|
||||
IWritingScheduleService writingSchedule,
|
||||
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null) : Controller
|
||||
{
|
||||
public async Task<IActionResult> Index(int? projectId)
|
||||
public async Task<IActionResult> Index(int? projectId,int? bookId=null,string? workspace=null,bool journey=false)
|
||||
{
|
||||
if(bookId.HasValue&&!projectId.HasValue&&bookRepository!=null)
|
||||
{
|
||||
if(access!=null&&!await access.CanAccessEntityAsync("Book",bookId.Value))return NotFound();
|
||||
var selected=await bookRepository.GetAsync(bookId.Value);if(selected==null||selected.IsArchived)return NotFound();projectId=selected.ProjectID;
|
||||
}
|
||||
var model = await writerWorkspace.GetDashboardAsync(projectId);
|
||||
model.WritingSchedule = await writingSchedule.GetTodayDashboardAsync(projectId);
|
||||
return View(model);
|
||||
if(!projectId.HasValue && int.TryParse(model.ProjectOptions.FirstOrDefault()?.Value,out var firstProject))
|
||||
{ projectId=firstProject;model=await writerWorkspace.GetDashboardAsync(projectId); }
|
||||
if(bookRepository!=null && projectId.HasValue)
|
||||
{
|
||||
var available=(await bookRepository.ListByProjectAsync(projectId.Value)).Where(b=>!b.IsArchived).ToArray();
|
||||
model.Book=bookId.HasValue?available.SingleOrDefault(b=>b.BookID==bookId):available.FirstOrDefault();
|
||||
if(bookId.HasValue&&model.Book==null)return NotFound();
|
||||
model.BookID=model.Book?.BookID;
|
||||
}
|
||||
else model.BookID=bookId;
|
||||
if(model.BookID.HasValue)
|
||||
{
|
||||
if(access!=null&&!await access.CanAccessEntityAsync("Book",model.BookID.Value))return NotFound();
|
||||
model.WriteNext=model.WriteNext.Where(x=>x.BookID==model.BookID).ToArray();
|
||||
model.ContinueWriting=model.ContinueWriting.Where(x=>x.BookID==model.BookID).ToArray();
|
||||
model.RevisionQueue=model.RevisionQueue.Where(x=>x.BookID==model.BookID).ToArray();
|
||||
model.PolishingQueue=model.PolishingQueue.Where(x=>x.BookID==model.BookID).ToArray();
|
||||
if(activity!=null&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user))
|
||||
{ try{model.Activity=await activity.Read(user,model.BookID.Value);}catch(SqlException e)when(e.Number==51000){ model.ActivityIsPrivate=true; } }
|
||||
if(activity!=null&&int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var reader))model.StoryHealthReminders=await activity.Reminders(reader,model.BookID.Value);
|
||||
}
|
||||
model.Workspace=workspace is "InProgress" or "Revision" or "FinalPass" or "StoryHealth"?workspace:"WriteNext";
|
||||
model.Journey=journey;
|
||||
model.WritingSchedule = await writingSchedule.GetTodayDashboardAsync(projectId,model.BookID);
|
||||
if(model.BookID.HasValue)
|
||||
{ model.WritingSchedule.TodayTasks=model.WritingSchedule.TodayTasks.Where(x=>x.BookID==model.BookID).ToArray();model.WritingSchedule.UpcomingTasks=model.WritingSchedule.UpcomingTasks.Where(x=>x.BookID==model.BookID).ToArray(); }
|
||||
return View("Index",model);
|
||||
}
|
||||
public Task<IActionResult> Workspaces(int? projectId,int? bookId,string? workspace=null)=>Index(projectId,bookId,workspace);
|
||||
public Task<IActionResult> Journey(int? projectId,int? bookId)=>Index(projectId,bookId,journey:true);
|
||||
public IActionResult DisplaySetup(int? projectId,int? bookId)=>Redirect(Url.Action(nameof(Index),new{projectId,bookId})+"#display-setup");
|
||||
[HttpGet("Write"),HttpGet("Write/Index")]
|
||||
public IActionResult LegacyWrite(int? projectId,int? bookId)=>RedirectToAction(nameof(Index),new{projectId,bookId});
|
||||
|
||||
public async Task<IActionResult> Chapter(int id)
|
||||
{
|
||||
|
||||
@ -13,9 +13,9 @@ public sealed class WritingActivityController(WritingActivityRepository activity
|
||||
{
|
||||
private int Actor => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet("Writer/Activity")]
|
||||
public async Task<IActionResult> Index(int bookId,long? before=null)
|
||||
public async Task<IActionResult> Index(int bookId,long? before=null,DateTime? day=null)
|
||||
{
|
||||
try { var page=await activity.Read(Actor,bookId,before);page.Book=await books.GetAsync(bookId);return View(page); }
|
||||
try { var page=await activity.Read(Actor,bookId,before,day);page.Day=day;page.Book=await books.GetAsync(bookId);return View(page); }
|
||||
catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
[HttpPost("Writer/Activity/Baseline"),ValidateAntiForgeryToken]
|
||||
|
||||
@ -7,22 +7,28 @@ using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class WritingActivityRepository(ISqlConnectionFactory factory)
|
||||
{
|
||||
public async Task<WritingActivityPage> Read(int user,int book,long? before=null)
|
||||
public async Task<WritingActivityPage> Read(int user,int book,long? before=null,DateTime? day=null)
|
||||
{
|
||||
using var db=factory.CreateConnection();
|
||||
var settings=await db.QuerySingleAsync<WritingActivitySettings>("dbo.WritingActivity",new{Action="settings",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);
|
||||
var events=(await db.QueryAsync<WritingActivityEvent>("dbo.WritingActivity",new{Action="list",UserID=user,BookID=book,AfterSequence=before},commandType:CommandType.StoredProcedure)).ToArray();
|
||||
return new(){BookID=book,Settings=settings,Events=events,CanManage=true};
|
||||
var events=(await db.QueryAsync<WritingActivityEvent>("dbo.WritingActivity_List",new{UserID=user,BookID=book,Before=before,Day=day?.Date},commandType:CommandType.StoredProcedure)).ToArray();
|
||||
using var summary=await db.QueryMultipleAsync("dbo.WritingActivity_Summary",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure);
|
||||
var totals=await summary.ReadSingleAsync<WritingActivityTotals>();var days=(await summary.ReadAsync<WritingActivityDay>()).ToArray();
|
||||
return new(){BookID=book,Settings=settings,Events=events,CanManage=true,Totals=totals,Days=days};
|
||||
}
|
||||
public async Task Baseline(int user,int book)
|
||||
public async Task<IReadOnlyList<StoryBibleAttentionItem>> Reminders(int user,int book)
|
||||
{using var db=factory.CreateConnection();return (await db.QueryAsync<StoryBibleAttentionItem>("dbo.WriterBook_Reminders",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
|
||||
public async Task Baseline(int user,int book,string source="PlotDirector")
|
||||
{
|
||||
using var db=factory.CreateConnection();db.Open();using var transaction=db.BeginTransaction();
|
||||
var json=await db.QuerySingleOrDefaultAsync<string>("dbo.WritingActivity",new{Action="lock",UserID=user,BookID=book},transaction,commandType:CommandType.StoredProcedure);
|
||||
if(json==null)throw new InvalidOperationException("No accepted manuscript is available. Link and synchronise the existing Word manuscript first.");
|
||||
var state=JsonSerializer.Deserialize<ParagraphManuscript>(json)!;var change=PlotLine.Services.WritingActivity.WritingChangeCalculator.Compare(null,state);
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="append",UserID=user,BookID=book,RequestID=Guid.NewGuid(),Source="PlotDirector",PayloadHash=state.SnapshotHash,ManuscriptID=state.ManuscriptId,Revision=state.Revision,Kind="Baseline",WordsAfter=change.AfterWords,Coverage=change.Coverage},transaction,commandType:CommandType.StoredProcedure);
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="append",UserID=user,BookID=book,RequestID=Guid.NewGuid(),Source=source,PayloadHash=state.SnapshotHash,ManuscriptID=state.ManuscriptId,Revision=state.Revision,Kind="Baseline",WordsAfter=change.AfterWords,Coverage=change.Coverage},transaction,commandType:CommandType.StoredProcedure);
|
||||
transaction.Commit();
|
||||
}
|
||||
public async Task<IReadOnlyList<WritingBaselineTarget>> BaselineTargets(int afterBook)
|
||||
{using var db=factory.CreateConnection();return (await db.QueryAsync<WritingBaselineTarget>("dbo.WritingActivity_BaselineTargets",new{AfterBookID=afterBook},commandType:CommandType.StoredProcedure)).ToArray();}
|
||||
public async Task Configure(int user,int book,bool enabled,int retentionDays)
|
||||
{ using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WritingActivity",new{Action="configure",UserID=user,BookID=book,Enabled=enabled,RetentionDays=retentionDays},commandType:CommandType.StoredProcedure); }
|
||||
public async Task Erase(int user,int book)
|
||||
@ -33,3 +39,5 @@ public sealed class WritingActivityRepository(ISqlConnectionFactory factory)
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="observe",UserID=user,value.BookID,value.RequestID,Source="WordCompanion",PayloadHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)))),value.ManuscriptID,value.ChapterID,value.ObservedUtc},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record WritingBaselineTarget(int BookID,int UserID);
|
||||
|
||||
@ -2414,6 +2414,8 @@ public sealed class WritingSchedulePreviewItem
|
||||
|
||||
public sealed class WritingScheduleDashboardItem
|
||||
{
|
||||
public int BookID { get; set; }
|
||||
public int ChapterID { get; set; }
|
||||
public int WritingScheduleItemID { get; set; }
|
||||
public int WritingPlanID { get; set; }
|
||||
public string PlanName { get; set; } = string.Empty;
|
||||
|
||||
@ -6,6 +6,11 @@ public sealed class WritingActivityEvent
|
||||
public Guid EventID { get; set; }
|
||||
public int BookID { get; set; }
|
||||
public Guid ManuscriptID { get; set; }
|
||||
public int UserID { get; set; }
|
||||
public Guid? SessionID { get; set; }
|
||||
public string? SnapshotHash { get; set; }
|
||||
public int SchemaVersion { get; set; } = 1;
|
||||
public string MetricVersion { get; set; } = "";
|
||||
public string Kind { get; set; } = "";
|
||||
public string Source { get; set; } = "";
|
||||
public string Provenance { get; set; } = "Observed";
|
||||
@ -29,6 +34,10 @@ public sealed class WritingActivityPage
|
||||
{
|
||||
public int BookID { get; set; }
|
||||
public Book? Book { get; set; }
|
||||
public int? ProjectID => Book?.ProjectID;
|
||||
public WritingActivityTotals Totals { get; set; } = new();
|
||||
public IReadOnlyList<WritingActivityDay> Days { get; set; } = [];
|
||||
public DateTime? Day { get; set; }
|
||||
public bool CanManage { get; set; }
|
||||
public WritingActivitySettings Settings { get; set; } = new();
|
||||
public IReadOnlyList<WritingActivityEvent> Events { get; set; } = [];
|
||||
@ -41,3 +50,22 @@ public sealed record WritingChange(int BeforeWords, int AfterWords, int Added, i
|
||||
{
|
||||
public int Net => Added - Removed;
|
||||
}
|
||||
public sealed class WritingActivityTotals
|
||||
{
|
||||
public long Added { get; set; }
|
||||
public long Removed { get; set; }
|
||||
public long Net => Added-Removed;
|
||||
public int ActiveDays { get; set; }
|
||||
public int RecordedEvents { get; set; }
|
||||
public int AcceptedEvents { get; set; }
|
||||
public bool HasAcceptedEvidence { get; set; }
|
||||
public DateTime? CoverageSinceUtc { get; set; }
|
||||
public int PartialComparisons { get; set; }
|
||||
}
|
||||
public sealed class WritingActivityDay
|
||||
{
|
||||
public DateTime Day { get; set; }
|
||||
public long Added { get; set; }
|
||||
public long Removed { get; set; }
|
||||
public int Changes { get; set; }
|
||||
}
|
||||
|
||||
@ -15,6 +15,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo
|
||||
var controller = request.RouteValues["controller"]?.ToString() ?? string.Empty;
|
||||
var result = new ApplicationNavigationViewModel { ActiveSection = section ?? controller switch
|
||||
{
|
||||
"WritingActivity" => "Writer",
|
||||
"Projects" or "Books" or "Chapters" or "Scenes" or "ManuscriptReader" => "Overview",
|
||||
"StoryCalendar" => "Calendar", "StoryPoint" => "At This Point",
|
||||
"RelationshipMap" => "Relationships", "StoryAssets" => "Assets",
|
||||
|
||||
@ -5,9 +5,10 @@ public sealed record RibbonCommand(string Label, string IconKey, string Controll
|
||||
string Scope = "project", bool OwnerOnly = false, string? ToolbarKey = null, bool Post = false)
|
||||
{
|
||||
public bool Available(ApplicationNavigationViewModel model) => (Scope == "global" || model.Project is not null)
|
||||
&& (Scope != "book" && Scope != "chapter" || model.Book is not null) && (!OwnerOnly || model.Project?.IsOwner == true);
|
||||
&& (Scope != "book" && Scope != "chapter" && Scope != "writerBook" || model.Book is not null) && (!OwnerOnly || model.Project?.IsOwner == true);
|
||||
public object Values(ApplicationNavigationViewModel model) => Scope switch
|
||||
{
|
||||
"writerBook" => new { projectId=model.Project?.ProjectID,bookId=model.Book?.BookID },
|
||||
"global" => new { }, "id" => new { id = model.Project?.ProjectID },
|
||||
"book" => new { id = model.Book?.BookID }, "chapter" => new { bookId = model.Book?.BookID },
|
||||
_ => new { projectId = model.Project?.ProjectID }
|
||||
@ -31,6 +32,10 @@ public static class ApplicationRibbon
|
||||
new("book", "Book",
|
||||
new("Selected book", new("Book overview", "bible", "Books", "Details", "book"), new("Edit book", "writer", "Books", "Edit", "book"), new("Add chapter", "threads", "Chapters", "Create", "chapter")),
|
||||
new("Manuscript review", S("review")), new("Library", S("overview"), new("Add book", "bible", "Books", "Create"))),
|
||||
new("writer", "Writer",
|
||||
new("Writing", new("Overview","writer","Writer","Index","writerBook"),new("Writing Journey","calendar","Writer","Journey","writerBook"),new("Writing Plan","calendar","Writer","WritingPlans")),
|
||||
new("Work",new("Workspaces","threads","Writer","Workspaces","writerBook"),new("Reports","metrics","WritingActivity","Index","writerBook",OwnerOnly:true)),
|
||||
new("Workspace setup",new RibbonCommand("Display Setup","maps","Writer","DisplaySetup","writerBook"))),
|
||||
new("story", "Story", new("Story structure", S("timeline"), S("plotlines"), S("threads"), S("calendar"), S("point")), new("Analysis & planning", S("review"), S("scenarios"), S("continuity"))),
|
||||
new("characters", "Characters", new("Cast", S("characters"), S("names")), new("Connections", S("relationships"))),
|
||||
new("world", "World", new("Setting", S("locations"), S("maps"), S("floorplans")), new("Story world", S("assets"))),
|
||||
|
||||
@ -615,7 +615,7 @@ public interface IWritingScheduleService
|
||||
Task<WritingScheduleSetupViewModel> GetScheduleSetupAsync(int? projectId);
|
||||
Task PopulateScheduleSetupOptionsAsync(WritingScheduleSetupViewModel model);
|
||||
Task<WritingScheduleSetupResult> CreateScheduleFromSetupAsync(WritingScheduleSetupViewModel model);
|
||||
Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null);
|
||||
Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null, int? bookId = null);
|
||||
Task<bool> MarkScheduleItemCompleteAsync(int writingScheduleItemId);
|
||||
Task<bool> SkipScheduleItemAsync(int writingScheduleItemId);
|
||||
Task<IReadOnlyList<WritingPlanSummary>> GetPlansRequiringRebalanceAsync(int? projectId = null);
|
||||
@ -6657,7 +6657,7 @@ public sealed class WritingScheduleService(
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null)
|
||||
public async Task<WritingScheduleDashboardViewModel> GetTodayDashboardAsync(int? projectId = null, int? bookId = null)
|
||||
{
|
||||
if (!currentUser.UserId.HasValue)
|
||||
{
|
||||
@ -6669,6 +6669,7 @@ public sealed class WritingScheduleService(
|
||||
var plansRequiringRebalance = await writingSchedule.GetPlansRequiringRebalanceAsync(currentUser.UserId.Value, DateTime.Today, projectId);
|
||||
var items = await writingSchedule.GetActiveScheduleDashboardItemsAsync(currentUser.UserId.Value, projectId);
|
||||
var today = DateTime.Today;
|
||||
if(bookId.HasValue) items=items.Where(x=>x.BookID==bookId.Value).ToArray();
|
||||
var plannedItems = items
|
||||
.Where(x => string.Equals(x.ScheduleStatus, "Planned", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
|
||||
@ -8,6 +8,23 @@ public sealed class WritingActivityRetention(IServiceScopeFactory scopes,ILogger
|
||||
{
|
||||
while(!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var baselineScope=scopes.CreateScope();var repository=baselineScope.ServiceProvider.GetRequiredService<WritingActivityRepository>();var afterBook=0;
|
||||
while(!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var targets=await repository.BaselineTargets(afterBook);if(targets.Count==0)break;
|
||||
foreach(var target in targets)
|
||||
{
|
||||
stoppingToken.ThrowIfCancellationRequested();
|
||||
try{await repository.Baseline(target.UserID,target.BookID,"System");}
|
||||
catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger.LogWarning("Accepted manuscript baseline could not be recorded for book {BookID} ({FailureKind}); other books continue.",target.BookID,e.GetType().Name);}
|
||||
afterBook=target.BookID;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
|
||||
catch(Exception e){logger.LogWarning("Writing baseline discovery could not run ({FailureKind}); retrying on next daily pass.",e.GetType().Name);}
|
||||
try { using var scope=scopes.CreateScope();using var db=scope.ServiceProvider.GetRequiredService<ISqlConnectionFactory>().CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.WritingActivity_Prune",commandType:CommandType.StoredProcedure,cancellationToken:stoppingToken)); }
|
||||
catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
|
||||
catch(Exception e){logger.LogWarning("Writing activity retention could not run ({FailureKind}); retrying on next daily pass.",e.GetType().Name);}
|
||||
|
||||
149
PlotLine/Sql/260_WriterActivitySummary.sql
Normal file
149
PlotLine/Sql/260_WriterActivitySummary.sql
Normal file
@ -0,0 +1,149 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity_Summary @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 b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole='Owner') THROW 51000,'Owner authority required',1;
|
||||
SELECT COALESCE(SUM(CASE WHEN Kind='Change' THEN CONVERT(bigint,Added) ELSE 0 END),0) Added,
|
||||
COALESCE(SUM(CASE WHEN Kind='Change' THEN CONVERT(bigint,Removed) ELSE 0 END),0) Removed,
|
||||
COUNT(DISTINCT CASE WHEN Kind='Change' THEN CONVERT(date,ReceivedUtc) END) ActiveDays,
|
||||
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.WritingActivityEvents allEvents WHERE allEvents.BookID=@BookID AND allEvents.Kind<>'Observation') THEN 1 ELSE 0 END AS bit) HasAcceptedEvidence,
|
||||
COUNT(*) RecordedEvents,COUNT(CASE WHEN Kind<>'Observation' THEN 1 END) AcceptedEvents,MIN(CASE WHEN Kind<>'Observation' THEN ReceivedUtc END) CoverageSinceUtc,
|
||||
SUM(CASE WHEN Coverage LIKE 'Partial:%' THEN 1 ELSE 0 END) PartialComparisons
|
||||
FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND ReceivedUtc>=DATEADD(day,-30,SYSUTCDATETIME());
|
||||
SELECT CONVERT(date,ReceivedUtc) Day,SUM(CONVERT(bigint,Added)) Added,SUM(CONVERT(bigint,Removed)) Removed,COUNT(*) Changes
|
||||
FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND Kind='Change' AND ReceivedUtc>=DATEADD(day,-30,SYSUTCDATETIME()) GROUP BY CONVERT(date,ReceivedUtc) ORDER BY Day;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WriterBook_Reminders @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(60) N'Chapter Goal' Category,N'Info' SeverityName,CONCAT(N'Chapter ',c.ChapterNumber,N' needs intent') Title,N'Goal summary is empty.' Detail,CAST(NULL AS int) SceneID,c.ChapterID EntityID,N'Chapter' EntityType
|
||||
FROM dbo.Chapters c LEFT JOIN dbo.ChapterGoals cg ON cg.ChapterID=c.ChapterID WHERE c.BookID=@BookID AND c.IsArchived=0 AND NULLIF(LTRIM(RTRIM(cg.GoalSummary)),N'') IS NULL
|
||||
UNION ALL
|
||||
SELECT N'Writer Note',N'Warning',COALESCE(sn.NoteTitle,s.SceneTitle),sn.NoteText,s.SceneID,sn.SceneNoteID,N'SceneNote'
|
||||
FROM dbo.SceneNotes sn JOIN dbo.SceneNoteTypes nt ON nt.SceneNoteTypeID=sn.SceneNoteTypeID JOIN dbo.Scenes s ON s.SceneID=sn.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID
|
||||
WHERE c.BookID=@BookID AND c.IsArchived=0 AND s.IsArchived=0 AND sn.IsResolved=0 AND nt.TypeName IN(N'TODO',N'Continuity Note',N'Revision Note');
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity_List @UserID int,@BookID int,@Day date=NULL,@Before bigint=NULL
|
||||
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 b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole='Owner') THROW 51000,'Owner authority required',1;
|
||||
SELECT TOP(500) e.UserID,e.SessionID,e.SnapshotHash,e.SchemaVersion,e.MetricVersion,e.Sequence,e.EventID,e.BookID,e.ManuscriptID,e.Kind,e.Source,e.Provenance,e.ReceivedUtc,e.ObservedUtc,e.Revision,e.WordsAfter,e.Added,e.Removed,e.Coverage,e.ChapterID,c.ChapterTitle
|
||||
FROM dbo.WritingActivityEvents e LEFT JOIN dbo.Chapters c ON c.ChapterID=e.ChapterID AND c.BookID=e.BookID
|
||||
WHERE e.BookID=@BookID AND (@Before IS NULL OR e.Sequence<@Before) AND (@Day IS NULL OR (e.ReceivedUtc>=@Day AND e.ReceivedUtc<DATEADD(day,1,@Day))) ORDER BY e.Sequence DESC;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingScheduleDashboard_ListActive
|
||||
@UserID int,
|
||||
@ProjectID int = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
SELECT wsi.WritingScheduleItemID, wsi.WritingPlanID, wp.PlanName, wsi.SceneID, wsi.ScheduledDate, wsi.TaskType,
|
||||
b.BookID, c.ChapterID, b.BookTitle, b.Subtitle AS BookSubtitle, c.ChapterNumber, c.ChapterTitle, c.SortOrder AS ChapterSortOrder,
|
||||
s.SceneNumber, s.SceneTitle, s.SortOrder AS SceneSortOrder, sw.Priority, wsi.EstimatedMinutes,
|
||||
wsi.TargetWords, wsi.ScheduleStatus, COALESCE(sw.IsBlocked, 0) AS IsBlocked
|
||||
FROM dbo.WritingPlans wp
|
||||
INNER JOIN dbo.WritingScheduleItems wsi ON wsi.WritingPlanID = wp.WritingPlanID
|
||||
INNER JOIN dbo.Scenes s ON s.SceneID = wsi.SceneID
|
||||
INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID
|
||||
INNER JOIN dbo.Books b ON b.BookID = c.BookID
|
||||
LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID = s.SceneID
|
||||
WHERE wp.UserID = @UserID
|
||||
AND wp.IsActive = 1
|
||||
AND (@ProjectID IS NULL OR wp.ProjectID = @ProjectID)
|
||||
ORDER BY wsi.ScheduledDate, wsi.WritingScheduleItemID;
|
||||
END;
|
||||
GO
|
||||
|
||||
-- Observations have no accepted snapshot reference. Their envelope digest belongs only in retry receipts.
|
||||
ALTER TABLE dbo.WritingActivityEvents ALTER COLUMN SnapshotHash char(64) NULL;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity
|
||||
@Action varchar(16),@UserID int,@BookID int,@RequestID uniqueidentifier=NULL,@Source varchar(32)='WordCompanion',@PayloadHash char(64)=NULL,
|
||||
@ManuscriptID uniqueidentifier=NULL,@Revision bigint=0,@Kind varchar(20)='Change',@WordsAfter int=0,@BeforeWords int=0,@Added int=0,@Removed int=0,
|
||||
@MetricVersion varchar(64)='whitespace-v1/bounded-paragraph-diff',@SessionID uniqueidentifier=NULL,@BeforeHash char(64)=NULL,@BeforeRevision bigint=NULL,@Coverage nvarchar(200)=N'Accepted snapshots; writing time unknown',@ChapterID int=NULL,@Scopes nvarchar(max)=NULL,@ObservedUtc datetime2=NULL,
|
||||
@Enabled bit=1,@RetentionDays int=365,@AfterSequence bigint=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
DECLARE @ProjectID int=(SELECT ProjectID FROM dbo.Books WHERE BookID=@BookID AND IsArchived=0);
|
||||
IF @ProjectID IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1) THROW 51000,'Book access denied',1;
|
||||
-- Activity is author-private until a dedicated contributor visibility policy exists.
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole='Owner') THROW 51000,'Owner authority required',1;
|
||||
IF @Action='list'
|
||||
BEGIN
|
||||
SELECT TOP(500) e.Sequence,e.EventID,e.BookID,e.ManuscriptID,e.Kind,e.Source,e.Provenance,e.ReceivedUtc,e.ObservedUtc,e.Revision,e.WordsAfter,e.Added,e.Removed,e.Coverage,e.ChapterID,c.ChapterTitle
|
||||
FROM dbo.WritingActivityEvents e LEFT JOIN dbo.Chapters c ON c.ChapterID=e.ChapterID AND c.BookID=e.BookID
|
||||
WHERE e.BookID=@BookID AND (@AfterSequence IS NULL OR e.Sequence<@AfterSequence) ORDER BY e.Sequence DESC;
|
||||
RETURN;
|
||||
END;
|
||||
IF @Action='settings' BEGIN SELECT COALESCE(s.Enabled,1) Enabled,COALESCE(s.RetentionDays,365) RetentionDays FROM(SELECT 1 n) x LEFT JOIN dbo.WritingActivitySettings s ON s.BookID=@BookID;RETURN;END;
|
||||
IF @Action='configure'
|
||||
BEGIN
|
||||
IF @RetentionDays NOT BETWEEN 30 AND 3650 THROW 51000,'Retention must be 30 to 3650 days',1;
|
||||
BEGIN TRANSACTION;
|
||||
UPDATE dbo.WritingActivitySettings WITH(UPDLOCK,SERIALIZABLE) SET Enabled=@Enabled,RetentionDays=@RetentionDays WHERE BookID=@BookID;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.WritingActivitySettings VALUES(@BookID,@Enabled,@RetentionDays);
|
||||
DELETE dbo.WritingActivityEvents WHERE BookID=@BookID AND ReceivedUtc<DATEADD(day,-@RetentionDays,SYSUTCDATETIME());
|
||||
COMMIT;RETURN;
|
||||
END;
|
||||
IF @Action='erase' BEGIN BEGIN TRANSACTION;DELETE dbo.WritingActivityEvents WHERE BookID=@BookID;UPDATE dbo.WritingActivitySettings SET Enabled=0 WHERE BookID=@BookID;IF @@ROWCOUNT=0 INSERT dbo.WritingActivitySettings VALUES(@BookID,0,365);COMMIT;RETURN;END;
|
||||
IF @Action='lock'
|
||||
BEGIN
|
||||
-- Must share caller's transaction with the established canonical save and activity append.
|
||||
IF @@TRANCOUNT=0 THROW 51000,'Activity lock requires a transaction',1;
|
||||
SELECT Payload FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
RETURN;
|
||||
END;
|
||||
IF @Action NOT IN('append','observe') THROW 51000,'Unknown activity operation',1;
|
||||
IF @RequestID IS NULL OR @RequestID='00000000-0000-0000-0000-000000000000' OR @PayloadHash IS NULL OR LEN(@PayloadHash)<>64 OR @Source NOT IN('WordCompanion','PlotDirector','Editor','System') THROW 51000,'Invalid activity identity',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @CurrentManuscript uniqueidentifier;
|
||||
SELECT @CurrentManuscript=ManuscriptID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
DECLARE @PriorHash char(64);
|
||||
SELECT @PriorHash=PayloadHash FROM dbo.WritingActivityReceipts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID AND RequestID=@RequestID AND Source=@Source;
|
||||
IF @PriorHash IS NOT NULL BEGIN IF @PriorHash<>@PayloadHash THROW 51000,'Activity identity conflict',1;COMMIT;RETURN;END;
|
||||
IF @CurrentManuscript IS NULL OR @CurrentManuscript<>@ManuscriptID THROW 51000,'Manuscript identity changed',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID) THROW 51000,'Manuscript identity changed',1;
|
||||
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@BookID AND ChapterID=@ChapterID) THROW 51000,'Chapter scope mismatch',1;
|
||||
IF @Action='observe'
|
||||
BEGIN
|
||||
IF @ObservedUtc IS NULL OR @ObservedUtc>DATEADD(minute,5,SYSUTCDATETIME()) OR @ObservedUtc<DATEADD(day,-30,SYSUTCDATETIME()) THROW 51000,'Observation outside supported clock/retention window',1;
|
||||
SET @Added=0;SET @Removed=0;SET @WordsAfter=0;SET @Kind='Observation';SET @Coverage=N'Native change observation; not an accepted text change or measured writing time';
|
||||
END;
|
||||
IF @Kind='Baseline' AND EXISTS(SELECT 1 FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID AND Kind<>'Observation') BEGIN COMMIT;RETURN;END;
|
||||
IF @Action='append' AND @Kind<>'Baseline' AND @Added-@Removed<>@WordsAfter-@BeforeWords THROW 51000,'Word changes do not reconcile',1;
|
||||
INSERT dbo.WritingActivityReceipts(BookID,RequestID,Source,PayloadHash) VALUES(@BookID,@RequestID,@Source,@PayloadHash);
|
||||
IF COALESCE((SELECT Enabled FROM dbo.WritingActivitySettings WHERE BookID=@BookID),1)=1
|
||||
BEGIN
|
||||
IF @Action='append' AND @Kind<>'Baseline' AND NOT EXISTS(SELECT 1 FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID AND Kind<>'Observation')
|
||||
INSERT dbo.WritingActivityEvents(BookID,ProjectID,ManuscriptID,UserID,RequestID,Kind,Source,Revision,WordsAfter,Added,Removed,Coverage,SnapshotHash)
|
||||
VALUES(@BookID,@ProjectID,@ManuscriptID,@UserID,NEWID(),'Baseline','PlotDirector',COALESCE(@BeforeRevision,0),@BeforeWords,0,0,N'Current accepted baseline; earlier activity unavailable',COALESCE(@BeforeHash,@PayloadHash));
|
||||
INSERT dbo.WritingActivityEvents(BookID,ProjectID,ManuscriptID,UserID,RequestID,Kind,Source,ObservedUtc,Revision,WordsAfter,Added,Removed,Coverage,ChapterID,SnapshotHash,Scopes,SessionID,MetricVersion)
|
||||
VALUES(@BookID,@ProjectID,@ManuscriptID,@UserID,@RequestID,@Kind,@Source,@ObservedUtc,@Revision,@WordsAfter,@Added,@Removed,@Coverage,@ChapterID,CASE WHEN @Action='observe' THEN NULL ELSE @PayloadHash END,@Scopes,@SessionID,CASE WHEN @Action='observe' THEN 'none' ELSE @MetricVersion END);
|
||||
END;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity_BaselineTargets @AfterBookID int=0
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT TOP(100) b.BookID,owner.UserID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.BookParagraphManuscripts m ON m.BookID=b.BookID
|
||||
CROSS APPLY(SELECT TOP(1) a.UserID FROM dbo.ProjectUserAccess a WHERE a.ProjectID=b.ProjectID AND a.AccessRole='Owner' AND a.IsActive=1 ORDER BY a.UserID) owner
|
||||
LEFT JOIN dbo.WritingActivitySettings s ON s.BookID=b.BookID
|
||||
WHERE b.BookID>@AfterBookID AND b.IsArchived=0 AND p.IsArchived=0 AND COALESCE(s.Enabled,1)=1
|
||||
AND NOT EXISTS(SELECT 1 FROM dbo.WritingActivityEvents e WHERE e.BookID=b.BookID AND e.ManuscriptID=m.ManuscriptID AND e.Kind<>'Observation') ORDER BY b.BookID;
|
||||
END;
|
||||
GO
|
||||
@ -925,6 +925,13 @@ public sealed class ChapterWorkflowViewModel
|
||||
|
||||
public sealed class WriterDashboardViewModel
|
||||
{
|
||||
public int? BookID { get; set; }
|
||||
public Book? Book { get; set; }
|
||||
public PlotLine.Models.WritingActivityPage? Activity { get; set; }
|
||||
public string Workspace { get; set; } = "WriteNext";
|
||||
public bool Journey { get; set; }
|
||||
public bool ActivityIsPrivate { get; set; }
|
||||
|
||||
public int? ProjectID { get; set; }
|
||||
public IReadOnlyList<SelectListItem> ProjectOptions { get; set; } = [];
|
||||
public WritingScheduleDashboardViewModel WritingSchedule { get; set; } = new();
|
||||
|
||||
@ -42,7 +42,6 @@
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="Projects" asp-action="Index">@(project is null ? "Projects" : "Switch project…")</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Writer" asp-action="Index">Writer Workspace</a></li>
|
||||
<li><form asp-controller="Onboarding" asp-action="StartImport" method="post"><button class="dropdown-item">Import a manuscript</button></form></li>
|
||||
@if(project is null){<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup">Back up books</a></li>}
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a></li>
|
||||
@ -65,7 +64,7 @@
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
@foreach (var choice in Model.Books)
|
||||
{
|
||||
<li><a class="dropdown-item @(choice.BookID == book?.BookID ? "active" : null)" aria-current="@(choice.BookID == book?.BookID ? "page" : null)" data-app-book-choice="@choice.BookID" data-app-book-title="@choice.BookDisplayTitle" asp-controller="Books" asp-action="Details" asp-route-id="@choice.BookID">Book @choice.BookNumber: @choice.BookDisplayTitle</a></li>
|
||||
<li><a class="dropdown-item @(choice.BookID == book?.BookID ? "active" : null)" aria-current="@(choice.BookID == book?.BookID ? "page" : null)" data-app-book-choice="@choice.BookID" data-app-book-title="@choice.BookDisplayTitle" href="@(Model.ActiveSection == "Writer" ? Url.Action("Index", "Writer", new { projectId = project.ProjectID, bookId = choice.BookID }) : Url.Action("Details", "Books", new { id = choice.BookID }))">Book @choice.BookNumber: @choice.BookDisplayTitle</a></li>
|
||||
}
|
||||
@if (Model.Books.Count == 0)
|
||||
{
|
||||
|
||||
@ -37,7 +37,6 @@
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="Projects" asp-action="Index">@(project is null ? "Projects" : "Switch project…")</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Writer" asp-action="Index">Writer Workspace</a></li>
|
||||
<li><form asp-controller="Onboarding" asp-action="StartImport" method="post"><button class="dropdown-item">Import a manuscript</button></form></li>
|
||||
@if(project is null){<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup">Back up books</a></li>}
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a></li>
|
||||
@ -60,7 +59,7 @@
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
@foreach (var choice in Model.Books)
|
||||
{
|
||||
<li><a class="dropdown-item @(choice.BookID == book?.BookID ? "active" : null)" aria-current="@(choice.BookID == book?.BookID ? "page" : null)" data-app-book-choice="@choice.BookID" data-app-book-title="@choice.BookDisplayTitle" asp-controller="Books" asp-action="Details" asp-route-id="@choice.BookID">Book @choice.BookNumber: @choice.BookDisplayTitle</a></li>
|
||||
<li><a class="dropdown-item @(choice.BookID == book?.BookID ? "active" : null)" aria-current="@(choice.BookID == book?.BookID ? "page" : null)" data-app-book-choice="@choice.BookID" data-app-book-title="@choice.BookDisplayTitle" href="@(Model.ActiveSection == "Writer" ? Url.Action("Index", "Writer", new { projectId = project.ProjectID, bookId = choice.BookID }) : Url.Action("Details", "Books", new { id = choice.BookID }))">Book @choice.BookNumber: @choice.BookDisplayTitle</a></li>
|
||||
}
|
||||
@if (Model.Books.Count == 0)
|
||||
{
|
||||
@ -117,9 +116,10 @@
|
||||
<div class="pd-ribbon-tabs" role="tablist" aria-label="Command categories">
|
||||
@foreach (var category in ApplicationRibbon.Categories)
|
||||
{
|
||||
@if (category.Key == "story")
|
||||
@if (category.Key == "writer")
|
||||
{
|
||||
<a class="pd-ribbon-navigation" aria-current="@(Model.ActiveSection == "Writer" ? "page" : null)" asp-controller="Writer" asp-action="Index" asp-route-projectId="@project?.ProjectID" asp-route-bookId="@book?.BookID">Writer</a>
|
||||
<a class="pd-ribbon-navigation" aria-current="@(Model.ActiveSection == "Writer" ? "page" : null)" asp-controller="Writer" asp-action="Index" asp-route-projectId="@project?.ProjectID" asp-route-bookId="@book?.BookID" id="ribbon-tab-writer">Writer</a>
|
||||
continue;
|
||||
}
|
||||
<button type="button" role="tab" id="ribbon-tab-@category.Key" aria-controls="ribbon-panel-@category.Key" aria-selected="@(category.Key == selectedCategory ? "true" : "false")" tabindex="@(category.Key == selectedCategory ? "0" : "-1")" data-ribbon-tab="@category.Key">@category.Label</button>
|
||||
}
|
||||
@ -140,7 +140,7 @@
|
||||
var available = shortcut?.IsAvailable(Model) ?? command.Available(Model);
|
||||
var url = available ? Url.Action(command.Action, command.Controller, shortcut?.RouteValues(Model) ?? command.Values(Model)) : null;
|
||||
var active = available && (shortcut?.IsActive(controller, action, Model.ActiveSection) ?? (controller == command.Controller && action == command.Action));
|
||||
var bookScoped = command.Scope is "book" or "chapter";
|
||||
var bookScoped = command.Scope is "book" or "chapter" or "writerBook";
|
||||
var presentationIcon = RibbonPresentation.IconFor(RibbonPresentation.Operation(command.Controller, command.Action)) ?? command.IconKey;
|
||||
var icon = ApplicationRibbon.Icon(presentationIcon);
|
||||
@if(command.Post){
|
||||
@ -152,7 +152,7 @@
|
||||
}else{
|
||||
<a class="pd-ribbon-command" href="@url" aria-disabled="@(!available ? "true" : null)" aria-current="@(active ? "page" : null)"
|
||||
data-review-url="@(command.ToolbarKey == "review" ? Url.Action(command.Action, command.Controller, new { bookId = 0 }) : null)"
|
||||
data-ribbon-book-url="@(bookScoped ? Url.Action(command.Action, command.Controller, new { id = (int?)null, bookId = (int?)null }) : null)" data-book-param="@(command.Scope == "chapter" ? "bookId" : "id")"
|
||||
data-ribbon-book-url="@(bookScoped ? Url.Action(command.Action, command.Controller, new { id = (int?)null, bookId = (int?)null }) : null)" data-book-param="@(command.Scope is "chapter" or "writerBook" ? "bookId" : "id")"
|
||||
data-command-operation="@RibbonPresentation.Operation(command.Controller, command.Action)" data-ribbon-icon="@presentationIcon" title="@(available ? command.Label : bookScoped || shortcut?.RequiresBook == true ? "Select a book to use this command" : "Select a project to use this command")">
|
||||
<svg viewBox="0 0 24 24" class="pd-icon" data-tone="@icon.Tone" aria-hidden="true" focusable="false"><path d="@icon.IconPath" /></svg><span>@command.Label @if (command.Controller == "FeatureRequests" && Model.FeatureRequestAttentionCount > 0) { <span class="badge text-bg-warning">@Model.FeatureRequestAttentionCount</span> }</span>
|
||||
</a>
|
||||
|
||||
@ -1,338 +1,88 @@
|
||||
@model WriterDashboardViewModel
|
||||
@{
|
||||
ViewData["Title"] = "Writer Workspace";
|
||||
ViewData["Title"] = Model.Journey ? "Writing Journey" : "Writer";
|
||||
ViewData["ShellClass"] = "pd-writer";
|
||||
var message = TempData["WriterWorkspaceMessage"] as string;
|
||||
var error = TempData["WriterWorkspaceError"] as string;
|
||||
var workspaceSeed = Model.WriteNext
|
||||
.Concat(Model.ContinueWriting)
|
||||
.Concat(Model.RevisionQueue)
|
||||
.Concat(Model.PolishingQueue)
|
||||
.FirstOrDefault();
|
||||
var workspaceProjectId = workspaceSeed?.ProjectID ?? Model.ProjectID;
|
||||
var workspaceBookId = workspaceSeed?.BookID;
|
||||
var workspaceBookTitle = workspaceSeed?.BookDisplayTitle ?? "Waiting for Word";
|
||||
ViewData["ProjectSection"] = "Writer";
|
||||
var seed=Model.WriteNext.Concat(Model.ContinueWriting).Concat(Model.RevisionQueue).Concat(Model.PolishingQueue).FirstOrDefault();
|
||||
var bookId=Model.BookID??seed?.BookID;
|
||||
var bookTitle=Model.Book?.BookDisplayTitle??seed?.BookDisplayTitle??"Choose a book";
|
||||
var next=Model.ContinueWriting.FirstOrDefault()??Model.WriteNext.FirstOrDefault()??Model.RevisionQueue.FirstOrDefault()??Model.PolishingQueue.FirstOrDefault();
|
||||
var opportunity=Model.WritingSchedule.TodayTasks.FirstOrDefault()??Model.WritingSchedule.UpcomingTasks.FirstOrDefault();
|
||||
var totals=Model.Activity?.Totals.HasAcceptedEvidence==true?Model.Activity.Totals:null;
|
||||
var queues=new[]{("WriteNext","Write Next",Model.WriteNext),("InProgress","In Progress",Model.ContinueWriting),("Revision","Revision",Model.RevisionQueue),("FinalPass","Final Pass",Model.PolishingQueue)};
|
||||
var days=Model.Activity?.Days??Array.Empty<PlotLine.Models.WritingActivityDay>();
|
||||
var maximum=Math.Max(1L,days.Select(x=>x.Added+x.Removed).DefaultIfEmpty(1).Max());
|
||||
}
|
||||
|
||||
<div data-pwa-header class="page-heading writer-dashboard-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Today view</p>
|
||||
<h1>Writer Workspace <help-icon key="workspace.overview" /></h1>
|
||||
<p class="lead-text">A practical control room for drafting, revision, polish, and story readiness.</p>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<a class="btn btn-outline-primary" asp-action="WritingPlans">Writing Plans</a>
|
||||
<a class="btn btn-outline-primary" asp-action="ScheduleSetup" asp-route-projectId="@Model.ProjectID">Schedule Setup</a>
|
||||
<a class="btn btn-outline-secondary" asp-action="SchedulePreview">Schedule Preview</a>
|
||||
<form asp-action="Index" method="get" class="story-bible-search">
|
||||
<select data-pwa-label="Project" class="form-select" name="projectId" asp-items="Model.ProjectOptions">
|
||||
<option value="">All projects</option>
|
||||
</select>
|
||||
<button class="btn btn-primary" type="submit">Focus</button>
|
||||
</form>
|
||||
<link rel="stylesheet" href="~/css/writer-dashboard.css" asp-append-version="true" />
|
||||
<div class="writer-studio" data-writing-workspace-launcher data-compact-writer="true" data-project-id="@Model.ProjectID" data-book-id="@bookId">
|
||||
<header class="writer-heading" data-pwa-task>
|
||||
<div><p class="eyebrow">@(Model.Journey?"Writing Journey":"Your writing desk")</p><h1>@bookTitle</h1><p class="muted">@(Model.Journey?"Accepted activity and the work ahead.":"Continue your manuscript, review your work, or choose what comes next.")</p></div>
|
||||
<div class="writer-connection"><span class="writer-status-dot" aria-hidden="true"></span>Word Companion <strong data-writing-workspace-word aria-live="polite">Checking…</strong><a href="#display-setup">Connection & Display Setup</a></div>
|
||||
</header>
|
||||
@if(TempData["WriterWorkspaceMessage"] is string message){<p class="alert alert-info" role="status">@message</p>}
|
||||
@if(TempData["WriterWorkspaceError"] is string error){<p class="alert alert-warning" role="alert">@error</p>}
|
||||
@if(!Model.Journey)
|
||||
{
|
||||
<section class="writer-next-grid" aria-label="Current work and next opportunity">
|
||||
<article class="writer-card writer-current"><p class="eyebrow">Continue writing</p>
|
||||
@if(next!=null){<h2><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@next.SceneID">@next.SceneTitle</a></h2><p><a asp-action="Chapter" asp-route-id="@next.ChapterID">Chapter @next.ChapterNumber</a> · @next.RevisionStatusName</p><p class="writer-excerpt">@next.Summary</p><div class="button-row"><a class="btn btn-primary" asp-controller="Scenes" asp-action="Edit" asp-route-id="@next.SceneID">Continue scene</a><a class="btn btn-outline-secondary" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@bookId" asp-route-chapterId="@next.ChapterID">Read manuscript</a></div>}
|
||||
else{<h2>Your manuscript, at your pace</h2><p>Choose a book in the application bar to find its chapters and writing work.</p>@if(bookId.HasValue){<a class="btn btn-primary" asp-controller="Chapters" asp-action="Index" asp-route-bookId="@bookId">Open chapters</a>}}
|
||||
</article>
|
||||
<article class="writer-card"><p class="eyebrow">Next writing opportunity · Planned</p>
|
||||
@if(opportunity!=null){<h2>@opportunity.ScheduledDate.ToString("ddd d MMM")</h2><p>@opportunity.TaskType · @opportunity.EstimatedMinutes estimated minutes</p><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@opportunity.SceneID">@opportunity.SceneTitle</a><p class="muted">Planned capacity, not measured writing time.</p>}
|
||||
else{<h2>Make room for your next page</h2><p>No upcoming writing task is scheduled for this book.</p><a class="btn btn-outline-primary" asp-action="ScheduleSetup" asp-route-projectId="@Model.ProjectID">Create a writing plan</a>}
|
||||
<a class="writer-text-link" asp-action="WritingPlans">Manage writing plans</a>
|
||||
</article>
|
||||
</section>
|
||||
@if(!Model.ActivityIsPrivate)
|
||||
{
|
||||
<section class="writer-indicators" aria-label="Recorded progress in the last 30 days">
|
||||
<a class="writer-card" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId"><span class="eyebrow">Observed additions</span><strong>@(totals==null?"—":totals.Added.ToString("N0"))</strong><span>Words between accepted snapshots</span></a>
|
||||
<a class="writer-card" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId"><span class="eyebrow">Observed deletions</span><strong>@(totals==null?"—":totals.Removed.ToString("N0"))</strong><span>Revision can include removing words</span></a>
|
||||
<a class="writer-card" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId"><span class="eyebrow">Net manuscript change</span><strong>@(totals==null?"—":totals.Net.ToString("+0;-0;0"))</strong><span>Last 30 days · receipt dates (UTC)</span></a>
|
||||
<a class="writer-card" asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId" asp-route-workspace="Revision"><span class="eyebrow">Revision workspace</span><strong>@Model.RevisionQueue.Count</strong><span>Scenes marked Needs Work · workflow status</span></a>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
<section class="writer-card writer-journey" aria-labelledby="writer-journey-title">
|
||||
<div class="writer-section-heading"><div><p class="eyebrow">Writing calendar · last 28 days</p><h2 id="writer-journey-title">The shape of your recent work</h2></div><a asp-action="Journey" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId">Writing Journey</a></div>
|
||||
@if(totals==null||totals.RecordedEvents==0)
|
||||
{
|
||||
<p class="writer-empty">@(Model.Activity?.Totals.HasAcceptedEvidence==true?"No accepted change is recorded in this period. Retained baseline evidence is available in activity settings.":"Your accepted manuscript can become the starting point. Earlier writing will not be counted as new activity.")</p>
|
||||
@if(bookId.HasValue&&!Model.ActivityIsPrivate){<a class="btn btn-outline-primary" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId">Activity & baseline settings</a>}
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="writer-calendar" aria-label="Daily observed changes; receipt dates in UTC">
|
||||
@for(var i=27;i>=0;i--){var date=DateTime.UtcNow.Date.AddDays(-i);var day=days.FirstOrDefault(x=>x.Day.Date==date);<a class="writer-day @(day==null?"writer-day-unobserved":"writer-day-observed")" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMM yyyy"): @(day==null?"no recorded change":$"{day.Changes} changes, {day.Added} added, {day.Removed} removed")"><span>@date.ToString("ddd")</span><strong>@date.Day</strong><small>@(day==null?"—":$"+{day.Added} / −{day.Removed}")</small></a>}
|
||||
</div>
|
||||
<p class="writer-coverage"><strong>@totals.ActiveDays observed change days in the last 30 days.</strong> Receipt dates use UTC; they do not establish when the author wrote each word. Grey means no recorded change, not a missed opportunity. @if(totals.PartialComparisons>0){<span>@totals.PartialComparisons comparisons contain qualified minimum estimates.</span>}</p>
|
||||
<details><summary>Manuscript changes by day</summary><div class="writer-change-chart" aria-label="Observed additions and deletions with numeric labels">@foreach(var day in days){<a class="writer-change-row" asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId" asp-route-day="@day.Day.ToString("yyyy-MM-dd")"><span>@day.Day.ToString("d MMM")</span><span class="writer-bar-track"><i class="writer-bar-added" style="width:@((100m*day.Added/maximum).ToString("0.##",System.Globalization.CultureInfo.InvariantCulture))%"></i><i class="writer-bar-removed" style="width:@((100m*day.Removed/maximum).ToString("0.##",System.Globalization.CultureInfo.InvariantCulture))%"></i></span><span>+@day.Added / −@day.Removed</span></a>}</div></details>
|
||||
}
|
||||
@if(Model.ActivityIsPrivate){<p class="muted">Activity evidence is private to the book owner. Your existing writing workspaces remain available.</p>}
|
||||
@if(Model.Activity?.Events.Count>0)
|
||||
{
|
||||
<details class="mt-3"><summary>Recent activity · source evidence</summary><ul class="writer-recent">@foreach(var e in Model.Activity.Events.Take(5)){<li><a asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@bookId" asp-route-day="@e.ReceivedUtc.ToString("yyyy-MM-dd")">@e.ReceivedUtc.ToString("d MMM HH:mm") UTC · @e.Kind</a><span>@e.Source · @(e.Kind=="Change"?$"+{e.Added} / −{e.Removed}":e.Coverage)</span></li>}</ul></details>
|
||||
}
|
||||
@if(Model.Journey&&Model.WritingSchedule.UpcomingTasks.Count>0){<h3 class="mt-3">Planned work ahead</h3><ul>@foreach(var item in Model.WritingSchedule.UpcomingTasks){<li>@item.ScheduledDate.ToString("ddd d MMM") · <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">@item.SceneTitle</a> · @item.TaskType</li>}</ul>}
|
||||
</section>
|
||||
<section class="writer-card writer-workspaces" id="workspaces" aria-labelledby="writer-workspace-title">
|
||||
<div class="writer-section-heading"><div><p class="eyebrow">Workspaces</p><h2 id="writer-workspace-title">Choose your next step</h2></div><a asp-controller="Chapters" asp-action="Index" asp-route-bookId="@bookId">Browse chapters</a></div>
|
||||
<nav class="writer-tabs" aria-label="Writing workspaces">@foreach(var q in queues){<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId" asp-route-workspace="@q.Item1" aria-current="@(Model.Workspace==q.Item1?"page":null)">@q.Item2 <span>@q.Item3.Count</span></a>}<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId" asp-route-workspace="StoryHealth" aria-current="@(Model.Workspace=="StoryHealth"?"page":null)">Story Health <span>@Model.StoryHealthReminders.Count</span></a></nav>
|
||||
@foreach(var q in queues){<div data-writer-queue="@q.Item1" hidden="@(Model.Workspace!=q.Item1)"><partial name="_WriterSceneQueue" model="q.Item3" /></div>}
|
||||
<div hidden="@(Model.Workspace!="StoryHealth")">@if(Model.StoryHealthReminders.Count==0){<p class="muted">No current book reminders are listed. You can also review project story health.</p>}@foreach(var reminder in Model.StoryHealthReminders){<article class="writer-reminder"><span class="status-pill">@reminder.Category</span>@if(reminder.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@reminder.SceneID">@reminder.Title</a>}else if(reminder.EntityType=="Chapter"){<a asp-action="Chapter" asp-route-id="@reminder.EntityID">@reminder.Title</a>}else{<strong>@reminder.Title</strong>}<p>@reminder.Detail</p></article>}<a asp-controller="Analytics" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@bookId">Project story health</a></div>
|
||||
</section>
|
||||
@if(Model.WritingSchedule.TodayTasks.Count>0){<details class="writer-card"><summary>Today's planned writing · @Model.WritingSchedule.TodayTasks.Count tasks</summary>@foreach(var task in Model.WritingSchedule.TodayTasks){<article class="writer-planned-task"><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@task.SceneID">@task.SceneTitle</a><span>@task.TaskType · @task.EstimatedMinutes estimated minutes</span><form asp-action="MarkScheduleItemComplete" method="post"><input type="hidden" name="writingScheduleItemId" value="@task.WritingScheduleItemID" /><input type="hidden" name="projectId" value="@Model.ProjectID" /><button class="btn btn-sm btn-outline-primary">Mark complete</button></form><form asp-action="SkipScheduleItem" method="post"><input type="hidden" name="writingScheduleItemId" value="@task.WritingScheduleItemID" /><input type="hidden" name="projectId" value="@Model.ProjectID" /><button class="btn btn-sm btn-outline-secondary">Skip</button></form></article>}<p class="muted">Task completion is author-declared, not measured writing time.</p></details>}
|
||||
<details class="writer-card writer-display-setup" id="display-setup"><summary>Word Companion & Display Setup</summary>
|
||||
<p class="muted">Open Context and Intent as reference windows. Linked Word controls appear when a document is connected. Display placement depends on browser permission and popup support; moving Word itself is controlled by Windows.</p>
|
||||
<div class="writing-workspace-status-grid"><div>Selected book <strong data-writing-workspace-book>Waiting for Word</strong></div><div>Context <strong data-writing-workspace-context>Checking…</strong></div><div>Intent <strong data-writing-workspace-intent>Checking…</strong></div><div>Layout <strong data-writing-workspace-layout>Adaptive</strong></div></div>
|
||||
<p class="muted" data-writing-workspace-message aria-live="polite">Choose reference windows or detect displays.</p>
|
||||
<div class="writing-workspace-display-controls" data-writing-workspace-display-controls><label>Context display<select class="form-select" data-writing-context-display><option value="left">Left display</option><option value="primary">Primary display</option><option value="right">Right display</option></select></label><label>Intent display<select class="form-select" data-writing-intent-display><option value="right">Right display</option><option value="primary">Primary display</option><option value="left">Left display</option></select></label><button class="btn btn-outline-primary" data-detect-writing-displays type="button">Detect displays</button></div>
|
||||
<div class="button-row"><button class="btn btn-primary" data-start-writing-workspace type="button" hidden>Start / Reapply Workspace</button><button class="btn btn-outline-primary" data-open-writing-context type="button">Open Context</button><button class="btn btn-outline-primary" data-open-writing-intent type="button">Open Intent</button><button class="btn btn-outline-secondary" data-focus-writing-context type="button" hidden>Focus Context</button><button class="btn btn-outline-secondary" data-focus-writing-intent type="button" hidden>Focus Intent</button></div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(message))
|
||||
{
|
||||
<div class="alert alert-info">@message</div>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(error))
|
||||
{
|
||||
<div class="alert alert-warning">@error</div>
|
||||
}
|
||||
|
||||
@if (Model.WritingSchedule.RebalancePlanCount > 0)
|
||||
{
|
||||
<div class="alert alert-info">
|
||||
You have @Model.WritingSchedule.RebalancePlanCount writing schedule(s) that may need rebalancing.
|
||||
<a asp-action="SchedulePreview">Review Schedules</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
<section class="story-bible-section writing-workspace-launcher"
|
||||
data-writing-workspace-launcher
|
||||
data-project-id="@workspaceProjectId"
|
||||
data-book-id="@workspaceBookId">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Writing Workspace</p>
|
||||
<h2>Context | Word | Intent</h2>
|
||||
</div>
|
||||
<span class="soft-count" data-writing-workspace-book>@workspaceBookTitle</span>
|
||||
</div>
|
||||
<div class="writing-workspace-status-grid" aria-label="Writing workspace status">
|
||||
<div><span>Word Companion</span><strong data-writing-workspace-word>Checking...</strong></div>
|
||||
<div><span>Context</span><strong data-writing-workspace-context>Checking...</strong></div>
|
||||
<div><span>Intent</span><strong data-writing-workspace-intent>Checking...</strong></div>
|
||||
<div><span>Layout</span><strong data-writing-workspace-layout>Adaptive</strong></div>
|
||||
</div>
|
||||
<p class="muted writing-workspace-message" data-writing-workspace-message>
|
||||
Open a linked Word manuscript or use a queued scene to start the writing workstation.
|
||||
</p>
|
||||
<div class="writing-workspace-display-controls" data-writing-workspace-display-controls>
|
||||
<label>
|
||||
<span>Context display</span>
|
||||
<select class="form-select form-select-sm" data-writing-context-display>
|
||||
<option value="left">Left display</option>
|
||||
<option value="primary">Primary display</option>
|
||||
<option value="right">Right display</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Intent display</span>
|
||||
<select class="form-select form-select-sm" data-writing-intent-display>
|
||||
<option value="right">Right display</option>
|
||||
<option value="primary">Primary display</option>
|
||||
<option value="left">Left display</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-detect-writing-displays>Detect displays</button>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<button type="button" class="btn btn-primary" data-start-writing-workspace>Start / Reapply Workspace</button>
|
||||
<button type="button" class="btn btn-outline-primary" data-open-writing-context>Open Context</button>
|
||||
<button type="button" class="btn btn-outline-primary" data-open-writing-intent>Open Intent</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-focus-writing-context hidden>Focus Context</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-focus-writing-intent hidden>Focus Intent</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="story-bible-section">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Daily plan</p>
|
||||
<h2>Today's Writing</h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.WritingSchedule.TodayTasks.Count tasks</span>
|
||||
</div>
|
||||
|
||||
@if (!Model.WritingSchedule.HasActivePlans)
|
||||
{
|
||||
<p class="muted">No writing schedule configured.</p>
|
||||
<a class="btn btn-primary" asp-action="ScheduleSetup" asp-route-projectId="@Model.ProjectID">Create Writing Schedule</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (!Model.WritingSchedule.TodayTasks.Any())
|
||||
{
|
||||
<p class="muted">No writing tasks scheduled for today.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-responsive">
|
||||
<table class="table align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Task Type</th>
|
||||
<th>Book</th>
|
||||
<th>Chapter</th>
|
||||
<th>Scene</th>
|
||||
<th>Priority</th>
|
||||
<th>Estimated Minutes</th>
|
||||
<th>Target Words</th>
|
||||
<th>Blocked</th>
|
||||
<th>Writing Plan</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in Model.WritingSchedule.TodayTasks)
|
||||
{
|
||||
<tr>
|
||||
<td>@item.TaskType</td>
|
||||
<td>@item.BookDisplayTitle</td>
|
||||
<td>Chapter @item.ChapterNumber: @item.ChapterTitle</td>
|
||||
<td>
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">
|
||||
Scene @item.SceneNumber: @item.SceneTitle
|
||||
</a>
|
||||
<div class="small">
|
||||
<a asp-controller="Exports" asp-action="WritingSession" asp-route-sceneId="@item.SceneID">Writing Guide</a>
|
||||
</div>
|
||||
</td>
|
||||
<td>@(item.Priority?.ToString() ?? "-")</td>
|
||||
<td>@(item.EstimatedMinutes?.ToString() ?? "-")</td>
|
||||
<td>@(item.TargetWords?.ToString() ?? "-")</td>
|
||||
<td>@(item.IsBlocked ? "Yes" : "No")</td>
|
||||
<td>@item.PlanName</td>
|
||||
<td>
|
||||
<div class="button-row">
|
||||
<form asp-action="MarkScheduleItemComplete" method="post">
|
||||
<input type="hidden" name="writingScheduleItemId" value="@item.WritingScheduleItemID" />
|
||||
<input type="hidden" name="projectId" value="@Model.ProjectID" />
|
||||
<button class="btn btn-sm btn-primary" type="submit">Mark Complete</button>
|
||||
</form>
|
||||
<form asp-action="SkipScheduleItem" method="post">
|
||||
<input type="hidden" name="writingScheduleItemId" value="@item.WritingScheduleItemID" />
|
||||
<input type="hidden" name="projectId" value="@Model.ProjectID" />
|
||||
<button class="btn btn-sm btn-outline-secondary" type="submit">Skip</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="story-bible-section-heading mt-4">
|
||||
<div>
|
||||
<p class="eyebrow">Upcoming work</p>
|
||||
<h2>Coming Up</h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.WritingSchedule.UpcomingTasks.Count tasks</span>
|
||||
</div>
|
||||
|
||||
@if (!Model.WritingSchedule.UpcomingTasks.Any())
|
||||
{
|
||||
<p class="muted">No upcoming writing tasks.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-responsive">
|
||||
<table class="table align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Scheduled Date</th>
|
||||
<th>Task Type</th>
|
||||
<th>Book</th>
|
||||
<th>Chapter</th>
|
||||
<th>Scene</th>
|
||||
<th>Estimated Minutes</th>
|
||||
<th>Target Words</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in Model.WritingSchedule.UpcomingTasks)
|
||||
{
|
||||
<tr>
|
||||
<td>@item.ScheduledDate.ToString("dd MMM yyyy")</td>
|
||||
<td>@item.TaskType</td>
|
||||
<td>@item.BookDisplayTitle</td>
|
||||
<td>Chapter @item.ChapterNumber: @item.ChapterTitle</td>
|
||||
<td>
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">
|
||||
Scene @item.SceneNumber: @item.SceneTitle
|
||||
</a>
|
||||
</td>
|
||||
<td>@(item.EstimatedMinutes?.ToString() ?? "-")</td>
|
||||
<td>@(item.TargetWords?.ToString() ?? "-")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="story-bible-section-heading mt-4">
|
||||
<div>
|
||||
<p class="eyebrow">Schedule</p>
|
||||
<h2>Progress Summary</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!Model.WritingSchedule.HasActiveSchedule)
|
||||
{
|
||||
<p class="muted">No active schedule</p>
|
||||
}
|
||||
|
||||
<div class="story-bible-grid story-bible-grid-compact">
|
||||
<article class="story-bible-card"><h3>Active Plans</h3><strong class="writer-kpi">@Model.WritingSchedule.ActivePlanCount</strong></article>
|
||||
<article class="story-bible-card"><h3>Total Planned Tasks</h3><strong class="writer-kpi">@Model.WritingSchedule.TotalPlannedTasks</strong></article>
|
||||
<article class="story-bible-card"><h3>Completed Tasks</h3><strong class="writer-kpi">@Model.WritingSchedule.CompletedTasks</strong></article>
|
||||
<article class="story-bible-card"><h3>Skipped Tasks</h3><strong class="writer-kpi">@Model.WritingSchedule.SkippedTasks</strong></article>
|
||||
<article class="story-bible-card"><h3>Remaining Tasks</h3><strong class="writer-kpi">@Model.WritingSchedule.RemainingTasks</strong></article>
|
||||
<article class="story-bible-card"><h3>Projected Finish Date</h3><strong class="writer-kpi">@(Model.WritingSchedule.ProjectedFinishDate?.ToString("dd MMM yyyy") ?? "-")</strong></article>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="writer-dashboard-grid">
|
||||
<section class="writer-dashboard-panel">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Write Next</p>
|
||||
<h2>Write Next <help-icon key="workspace.writeNext" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.WriteNext.Count scenes</span>
|
||||
</div>
|
||||
<partial name="_WriterSceneQueue" model="Model.WriteNext" />
|
||||
</section>
|
||||
|
||||
<section class="writer-dashboard-panel">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">In progress</p>
|
||||
<h2>Continue Writing <help-icon key="workspace.writeNext" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.ContinueWriting.Count scenes</span>
|
||||
</div>
|
||||
<partial name="_WriterSceneQueue" model="Model.ContinueWriting" />
|
||||
</section>
|
||||
|
||||
<section class="writer-dashboard-panel">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Revision</p>
|
||||
<h2>Revision Queue <help-icon key="workspace.revisionQueue" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.RevisionQueue.Count scenes</span>
|
||||
</div>
|
||||
<partial name="_WriterSceneQueue" model="Model.RevisionQueue" />
|
||||
</section>
|
||||
|
||||
<section class="writer-dashboard-panel">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Final pass</p>
|
||||
<h2>Polishing Queue <help-icon key="workspace.polishingQueue" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.PolishingQueue.Count scenes</span>
|
||||
</div>
|
||||
<partial name="_WriterSceneQueue" model="Model.PolishingQueue" />
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="story-bible-section">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Story health</p>
|
||||
<h2>Reminders <help-icon key="workspace.reminders" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.StoryHealthReminders.Count items</span>
|
||||
</div>
|
||||
<div class="attention-list">
|
||||
@foreach (var reminder in Model.StoryHealthReminders)
|
||||
{
|
||||
<article>
|
||||
<span class="badge text-bg-light">@reminder.Category</span>
|
||||
@if (reminder.SceneID.HasValue)
|
||||
{
|
||||
<strong>
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@reminder.SceneID">@reminder.Title</a>
|
||||
</strong>
|
||||
}
|
||||
else
|
||||
{
|
||||
<strong>@reminder.Title</strong>
|
||||
}
|
||||
@if (!string.IsNullOrWhiteSpace(reminder.Detail))
|
||||
{
|
||||
<p>@reminder.Detail</p>
|
||||
}
|
||||
@if (reminder.SceneID.HasValue)
|
||||
{
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@reminder.SceneID">Open scene</a>
|
||||
}
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
|
||||
<script>(()=>{const open=()=>{if(location.hash==='#display-setup')document.getElementById('display-setup').open=true;};window.addEventListener('hashchange',open);open();})();</script>
|
||||
}
|
||||
|
||||
@ -8,24 +8,32 @@
|
||||
<a class="btn btn-outline-primary" asp-controller="Writer" asp-action="Index" asp-route-projectId="@Model.Book?.ProjectID" asp-route-bookId="@Model.BookID">Back to Writer</a>
|
||||
</div>
|
||||
<p>These are accepted snapshot differences and separately labelled native observations. They do not measure writing time or prove authorship. Earlier writing and changes between observations may be unavailable.</p>
|
||||
@if(Model.Events.Count == 0)
|
||||
@if(Model.Events.Count == 0 && Model.Day.HasValue)
|
||||
{
|
||||
<section class="story-bible-section"><h2>No retained evidence for @Model.Day.Value.ToString("d MMM yyyy")</h2><p>This does not mean that no writing took place.</p><a asp-action="Index" asp-route-bookId="@Model.BookID">All retained activity</a></section>
|
||||
}
|
||||
else if(Model.Events.Count == 0)
|
||||
{
|
||||
<section class="story-bible-section"><h2>Begin with the manuscript you have</h2><p>No retained activity is available. Record the current accepted manuscript as a baseline; its existing words will not count as new writing.</p>
|
||||
<form asp-action="Baseline" method="post"><input type="hidden" name="bookId" value="@Model.BookID" /><button class="btn btn-primary" disabled="@(!Model.Settings.Enabled)">Record current baseline</button></form></section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<section class="story-bible-section"><h2>Retained evidence</h2><p>Up to 500 records per page. Times below are server receipt times in UTC; source observation time is shown separately when available.</p>
|
||||
<div class="table-responsive"><table class="table"><thead><tr><th>Received (UTC)</th><th>Evidence</th><th>Scope</th><th>Added</th><th>Removed</th><th>Net</th></tr></thead><tbody>
|
||||
<section class="story-bible-section"><h2>Retained evidence @(Model.Day?.ToString("d MMM yyyy"))</h2><p>Up to 500 records per page. Times below are server receipt times in UTC; source observation time is shown separately when available.</p>
|
||||
<div class="table-responsive"><table class="table"><thead><tr><th>Received (UTC)</th><th>Evidence</th><th>Scope</th><th>Added</th><th>Removed</th><th>Net</th><th>Accepted words</th></tr></thead><tbody>
|
||||
@foreach(var e in Model.Events)
|
||||
{
|
||||
<tr><td>@e.ReceivedUtc.ToString("dd MMM yyyy HH:mm:ss")@if(e.ObservedUtc.HasValue){<div class="small">Observed @e.ObservedUtc.Value.ToString("dd MMM yyyy HH:mm:ss") UTC</div>}</td><td><strong>@e.Kind</strong> · @e.Source<div class="small">@e.Provenance · @e.Coverage</div></td><td>@if(e.ChapterID.HasValue){<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@e.ChapterID">@(e.ChapterTitle ?? "Chapter")</a>}else{<span>Manuscript</span>}<div class="small">Accepted revision @e.Revision</div></td><td>@(e.Kind=="Change"?e.Added.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Removed.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Net.ToString("+0;-0;0"):"—")</td></tr>
|
||||
<tr><td>@e.ReceivedUtc.ToString("dd MMM yyyy HH:mm:ss")@if(e.ObservedUtc.HasValue){<div class="small">Observed @e.ObservedUtc.Value.ToString("dd MMM yyyy HH:mm:ss") UTC</div>}</td><td><strong>@e.Kind</strong> · @e.Source<div class="small">@e.Provenance · @e.Coverage</div></td><td>@if(e.ChapterID.HasValue){<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@e.ChapterID">@(e.ChapterTitle ?? "Chapter")</a>}else{<span>Manuscript</span>}<div class="small">@(e.Kind=="Observation"?"Source observation only":$"Accepted revision {e.Revision}")</div></td><td>@(e.Kind=="Change"?e.Added.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Removed.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Net.ToString("+0;-0;0"):"—")</td><td>@(e.Kind=="Observation"?"—":e.WordsAfter.ToString("N0"))</td></tr>
|
||||
}
|
||||
</tbody></table></div>
|
||||
<a class="btn btn-outline-primary" asp-action="Export" asp-route-bookId="@Model.BookID">Export recent evidence (JSON)</a>
|
||||
@if(Model.Events.Count==500){<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-before="@Model.Events.Last().Sequence">Earlier evidence</a>}
|
||||
@if(Model.Events.Count==500){<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-before="@Model.Events.Last().Sequence" asp-route-day="@Model.Day?.ToString("yyyy-MM-dd")">Earlier evidence</a>}
|
||||
</section>
|
||||
}
|
||||
@if(Model.Settings.Enabled && Model.Events.Count>0 && !Model.Totals.HasAcceptedEvidence)
|
||||
{
|
||||
<form asp-action="Baseline" method="post" class="mb-3"><input type="hidden" name="bookId" value="@Model.BookID" /><p>Native observations do not establish an accepted manuscript baseline.</p><button class="btn btn-outline-primary">Record current accepted baseline</button></form>
|
||||
}
|
||||
<section class="story-bible-section"><h2>Privacy and retention</h2><p>Activity stores counts, identifiers and evidence metadata, never a second copy of your prose. Default retention is 365 days. Compact retry receipts remain until the book is permanently deleted to prevent duplicate delivery. Retention runs daily; reducing it also removes older records now. Pausing leaves manuscript synchronisation available.</p>
|
||||
<form asp-action="Settings" method="post"><input type="hidden" name="bookId" value="@Model.BookID" />
|
||||
<label class="form-check"><input class="form-check-input" type="checkbox" name="enabled" value="true" checked="@Model.Settings.Enabled" /> Record activity for this book</label>
|
||||
|
||||
7
PlotLine/wwwroot/css/writer-dashboard.css
Normal file
7
PlotLine/wwwroot/css/writer-dashboard.css
Normal file
@ -0,0 +1,7 @@
|
||||
.writer-studio{max-width:1600px;margin:0 auto;padding:clamp(0px,1vw,16px);color:var(--pd-text)}
|
||||
.writer-heading,.writer-section-heading{display:flex;align-items:center;justify-content:space-between;gap:1.5rem;margin-bottom:1.5rem}.writer-heading h1{font-size:clamp(1.8rem,3vw,3rem);font-family:Georgia,serif;letter-spacing:-.025em;margin:.2rem 0 .5rem}.writer-heading p{margin-bottom:0}.writer-connection{display:flex;align-items:center;flex-wrap:wrap;gap:.5rem;max-width:360px;font-size:.85rem}.writer-connection a{display:block;flex-basis:100%}.writer-status-dot{width:.5rem;height:.5rem;border-radius:50%;background:var(--pd-muted,#777)}
|
||||
.writer-card{padding:clamp(1rem,2vw,1.8rem);border:1px solid var(--pd-border,#ccc);border-radius:16px;background:var(--pd-surface);margin-bottom:1.2rem;min-width:0}.writer-card h2{font-family:Georgia,serif;font-size:clamp(1.3rem,2vw,1.8rem)}.writer-next-grid{display:grid;grid-template-columns:1.6fr 1fr;gap:1.2rem}.writer-current{border-inline-start:4px solid var(--pd-accent,#506a60);background:linear-gradient(125deg,color-mix(in srgb,var(--pd-accent,#506a60) 8%,var(--pd-surface)),var(--pd-surface))}.writer-excerpt{max-width:72ch;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.writer-text-link{display:block;margin-top:1rem}.writer-indicators{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:1.2rem}.writer-indicators>a{display:flex;flex-direction:column;gap:.5rem;text-decoration:none;color:var(--pd-text)}.writer-indicators strong{font-family:Georgia,serif;font-size:2.4rem;line-height:1.2}.writer-indicators .eyebrow{font-size:.7rem}.writer-indicators span:last-child{font-size:.8rem;color:var(--pd-muted-text,var(--pd-text))}.writer-card a:focus-visible,.writer-tabs a:focus-visible{outline:3px solid var(--pd-accent,#506a60);outline-offset:4px}
|
||||
.writer-calendar{display:grid;grid-template-columns:repeat(14,minmax(0,1fr));gap:.4rem}.writer-day{display:flex;flex-direction:column;align-items:center;padding:.6rem .15rem;border:1px solid var(--pd-border,#ccc);border-radius:8px;text-decoration:none;color:var(--pd-text);min-width:0}.writer-day span,.writer-day small{font-size:.65rem}.writer-day strong{font-size:1.1rem}.writer-day-unobserved{background:color-mix(in srgb,var(--pd-text) 3%,var(--pd-surface))}.writer-day-observed{background:color-mix(in srgb,#387855 16%,var(--pd-surface));border-color:#547f63}.writer-coverage{font-size:.82rem;margin:1rem 0 0;line-height:1.6}.writer-journey details{margin-top:1rem}.writer-change-row{display:grid;grid-template-columns:65px 1fr 120px;gap:.7rem;align-items:center;text-decoration:none;color:var(--pd-text);font-size:.8rem;margin:.7rem 0}.writer-bar-track{display:flex;height:16px;border-radius:3px;background:color-mix(in srgb,var(--pd-text) 5%,var(--pd-surface));overflow:hidden}.writer-bar-added{background:#4c8460}.writer-bar-removed{background:#9d8464}.writer-tabs{display:flex;gap:.5rem;overflow-x:auto;padding:.3rem .2rem 1rem;margin-bottom:1rem}.writer-tabs a{white-space:nowrap;padding:.6rem 1rem;border:1px solid var(--pd-border,#ccc);border-radius:24px;color:var(--pd-text);text-decoration:none}.writer-tabs a[aria-current=page]{background:var(--pd-accent,#506a60);color:var(--pd-on-accent,#fff)}.writer-tabs span{font-size:.8rem;margin-left:.3rem}.writer-reminder{padding:1rem 0;border-bottom:1px solid var(--pd-border,#ccc)}.writer-reminder>a{margin-left:.7rem}.writer-planned-task{display:flex;align-items:center;flex-wrap:wrap;gap:.8rem;padding:1rem 0}.writer-display-setup summary{font-weight:600}.writer-display-setup[open] summary{margin-bottom:1rem}.writer-display-setup .writing-workspace-status-grid{margin:1rem 0}.writer-empty{max-width:75ch}.writer-workspaces [hidden]{display:none!important}
|
||||
@media(max-width:1050px){.writer-indicators{grid-template-columns:repeat(2,minmax(0,1fr))}.writer-calendar{grid-template-columns:repeat(7,minmax(0,1fr))}}
|
||||
@media(max-width:650px){.writer-heading{display:block}.writer-connection{margin-top:1rem}.writer-next-grid{grid-template-columns:1fr}.writer-card{padding:1rem}.writer-section-heading{align-items:flex-start;gap:.7rem}.writer-section-heading>a{font-size:.8rem}.writer-calendar{gap:.25rem}.writer-indicators{gap:.6rem}.writer-indicators strong{font-size:1.8rem}.writer-indicators .eyebrow{font-size:.6rem}.writer-change-row{grid-template-columns:50px 1fr 85px;font-size:.7rem}.writer-display-setup .writing-workspace-display-controls{display:flex;flex-direction:column;align-items:stretch}}
|
||||
.writer-recent{padding:0;list-style:none}.writer-recent li{padding:.7rem 0;border-bottom:1px solid var(--pd-border,#ccc);display:flex;gap:1rem;justify-content:space-between;font-size:.85rem}.writer-recent span{max-width:60ch}
|
||||
@ -104,13 +104,21 @@
|
||||
|| (activeScope.bookID && incomingScope.bookID && activeScope.bookID !== incomingScope.bookID))) {
|
||||
// Presence broadcasts cover all this author's books. They must not change
|
||||
// the workspace chosen here by a canonical position or explicit command.
|
||||
if(root.dataset.compactWriter === "true"){if(startButton)startButton.hidden=true;root.dataset.linkedDocument="false";}
|
||||
text(statusNodes.word, status.wordCompanionConnected || status.WordCompanionConnected ? "Connected" : "Not connected");
|
||||
return;
|
||||
}
|
||||
if (root.dataset.compactWriter === "true") {
|
||||
const connected = Boolean(status?.wordCompanionConnected || status?.WordCompanionConnected);
|
||||
const linked = connected && Boolean(status?.wordDocumentOpen || status?.WordDocumentOpen) && Number(status?.wordBookID || status?.WordBookID) === activeScope.bookID;
|
||||
if(startButton) startButton.hidden = !linked;
|
||||
root.dataset.linkedDocument = String(linked);
|
||||
}
|
||||
latestStatus = status;
|
||||
activeScope = workspace.statusScope(status, activeScope);
|
||||
text(statusNodes.book, activeScope.bookID ? `Book ${activeScope.bookID}` : "Waiting for book");
|
||||
text(statusNodes.word, status?.wordCompanionConnected || status?.WordCompanionConnected ? "Connected" : "Not connected");
|
||||
if(root.dataset.compactWriter === "true" && (status?.wordCompanionConnected || status?.WordCompanionConnected) && root.dataset.linkedDocument !== "true") text(statusNodes.word,"Connected · no linked document");
|
||||
text(statusNodes.context, statusText(status, "Context"));
|
||||
text(statusNodes.intent, statusText(status, "Intent"));
|
||||
const contextOpen = statusText(status, "Context") !== "Not open";
|
||||
@ -227,6 +235,7 @@
|
||||
document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => {
|
||||
const position = window.PlotDirectorStoryPosition?.normalise?.(event.detail, event.detail?.source || event.detail?.Source) || event.detail;
|
||||
if (position?.projectId && position?.bookId) {
|
||||
if(root.dataset.compactWriter === "true" && fallbackScope.bookID && position.bookId !== fallbackScope.bookID) return;
|
||||
activeScope = { projectID: position.projectId, bookID: position.bookId };
|
||||
void workspace.registerWindow({
|
||||
...activeScope,
|
||||
@ -249,7 +258,7 @@
|
||||
text(statusNodes.word, "Unavailable");
|
||||
text(statusNodes.context, "Unavailable");
|
||||
text(statusNodes.intent, "Unavailable");
|
||||
setMessage("Writing workspace presence is unavailable. Check your connection and retry Start / Reapply Workspace; other PlotDirector sections remain available.");
|
||||
setMessage("Writing workspace presence is unavailable. Check your connection and retry opening a reference window; other PlotDirector sections remain available.");
|
||||
console.debug("Writing workspace registration unavailable.", error);
|
||||
});
|
||||
})();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user