diff --git a/PlotLine.Tests/Browser/context-threads.cjs b/PlotLine.Tests/Browser/context-threads.cjs index 19c619c8..4758abc6 100644 --- a/PlotLine.Tests/Browser/context-threads.cjs +++ b/PlotLine.Tests/Browser/context-threads.cjs @@ -1,131 +1,115 @@ -// Isolated browser interaction checks. Mock persistence is not live Development acceptance. +// Isolated interaction coverage. The in-memory fixture does not verify SQL persistence. const { chromium } = require('playwright'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); + const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/js/context-threads.js'), 'utf8'); (async () => { const browser = await chromium.launch({ headless: true }); try { - const context = await browser.newContext(); - const links = new Map([[11, new Set([1])], [22, new Set()]]); - const errors = [], writes = [], guards = []; - let reject = false, readonly = false; - const threads = [ - { plotThreadID: 1, plotLineID: 10, plotLineName: 'Journey', title: 'A question' }, - { plotThreadID: 2, plotLineID: 10, plotLineName: 'Journey', title: 'Promise' }, - { plotThreadID: 3, plotLineID: 20, plotLineName: 'Discovery', title: 'Hidden answer' } - ]; - function state(sceneID) { - return { scope: { label: `Chapter 1 · Scene ${sceneID}: Saved scene`, canEdit: !readonly }, - threads: threads.map(t => ({ ...t, linked: links.get(sceneID).has(t.plotThreadID), canRemove: !readonly && links.get(sceneID).has(t.plotThreadID), - previousScenes: sceneID === 22 && links.get(11).has(t.plotThreadID) - ? [{ chapterID: 1, sceneID: 11, chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [] })) }; - } - await context.route('http://context.test/**', async route => { + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + const writes = []; + const invalidations = []; + const placements = new Map([[1, { sceneID: 11 }]]); + let reject = true; + let canEdit = true; + const threads = ['A question', 'Promise', 'Hidden answer']; + await page.route('http://context.test/**', async route => { const url = new URL(route.request().url()); - if (url.pathname === '/ContextThreads/State') return route.fulfill({ json: state(Number(url.searchParams.get('sceneId'))) }); - if (url.pathname === '/ContextThreads/Add') { - const body = route.request().postDataJSON(); writes.push(body); - assert.equal(route.request().headers()['requestverificationtoken'], 'fixture-token'); - if (reject) return route.fulfill({ status: 409, json: { message: 'Thread was archived. Review selection.' } }); - for (const id of body.threadIDs) links.get(body.sceneID).add(id); + if (url.pathname === '/ContextThreads/State') { + const sceneID = Number(url.searchParams.get('sceneId')); + return route.fulfill({ json: { + scope: { label: `Chapter 1 · Scene ${sceneID}`, canEdit }, + threads: threads.map((title, index) => { + const plotThreadID = index + 1; + const target = placements.get(plotThreadID); + const includedInChapter = target?.chapterID === 101; + const includedInScene = target?.sceneID === sceneID; + return { + plotThreadID, title, plotLineName: 'Journey', includedInChapter, includedInScene, + canRemove: canEdit && (includedInChapter || includedInScene), assigned: !!target, + assignedElsewhere: !!target && !includedInChapter && !includedInScene, + assignmentLabel: target?.sceneID ? `Scene ${target.sceneID}` : null, + hasManuscriptAssociation: plotThreadID === 1 && sceneID === 11, + previousScenes: plotThreadID === 1 && sceneID === 22 + ? [{ chapterID: 101, sceneID: 11, chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [], + chapterBlock: plotThreadID === 3 ? 'Place Promise earlier in this book.' : null + }; + }) + } }); + } + if (['/ContextThreads/Add', '/ContextThreads/Remove'].includes(url.pathname)) { + const body = route.request().postDataJSON(); + writes.push(body); + assert.equal(route.request().headers().requestverificationtoken, 'fixture-token'); + if (url.pathname.endsWith('/Add')) { + if (reject) return route.fulfill({ status: 409, json: { message: 'The saved assignment changed.' } }); + for (const id of body.threadIDs) + placements.set(id, body.chapter ? { chapterID: body.chapterID } : { sceneID: body.sceneID }); + } else { + placements.delete(body.threadID); + } return route.fulfill({ json: { saved: true } }); } - if (url.pathname === '/ContextThreads/Remove') { - const body = route.request().postDataJSON(); writes.push(body); - assert.equal(route.request().headers()['requestverificationtoken'], 'fixture-token'); - links.get(body.sceneID).delete(body.threadID); - return route.fulfill({ json: { saved: true } }); - } - if (url.pathname !== '/') throw Error(`Unexpected navigation: ${url.pathname}`); - return route.fulfill({ contentType: 'text/html', body: '
' }); + assert.equal(url.pathname, '/'); + return route.fulfill({ contentType: 'text/html', body: '
' }); }); - const page = await context.newPage(); page.on('pageerror', e => errors.push(e.message)); await page.goto('http://context.test/'); await page.addScriptTag({ content: script }); - async function mount(sceneID, pane = 0) { - await page.evaluate(({ sceneID, pane }) => { - let host = document.querySelector(`[data-test-pane="${pane}"]`); - if (!host) { host = document.createElement('section'); host.dataset.testPane = pane; document.querySelector('main').append(host); } - const old = host.firstElementChild; - if (old) window.PlotDirectorContextLifecycles.threads.dispose(old); - host.innerHTML = `

`; - window.guardEvents ??= []; - host.firstElementChild.addEventListener('context-panel-state', e => window.guardEvents.push(e.detail.dirty)); + await page.evaluate(() => { + window.invalidations = []; + document.querySelector('main').contextController = { invalidate: hint => window.invalidations.push(hint) }; + }); + async function mount(sceneID) { + await page.evaluate(scene => { + const host = document.querySelector('main'); + if (host.firstElementChild) window.PlotDirectorContextLifecycles.threads.dispose(host.firstElementChild); + host.innerHTML = `
+ +

`; window.PlotDirectorContextLifecycles.threads.mount(host.firstElementChild); - }, { sceneID, pane }); - await page.locator(`[data-test-pane="${pane}"] [data-thread-add]`).waitFor({ state: 'visible' }); - if (!readonly) await page.waitForFunction(pane => !document.querySelector(`[data-test-pane="${pane}"] [data-thread-add]`).disabled, pane); + }, sceneID); + await page.getByRole('heading', { name: 'Included here' }).waitFor(); } await mount(11); - assert.equal(await page.getByRole('heading', {name: 'A question', exact: true}).count(), 1); - await page.getByRole('button', { name: 'Add thread', exact: true }).click(); - await page.getByText('Chapter 1 · Scene 11: Saved scene', { exact: true }).waitFor(); + const add = page.getByRole('button', { name: 'Include threads', exact: true }); + await page.getByRole('button', { name: 'Remove A question from scene' }).waitFor(); + await add.click(); const dialog = page.getByRole('dialog'); - await dialog.locator('summary').filter({ hasText: 'Journey' }).click(); - assert.equal(await dialog.getByLabel(/A question.*Already linked/).isDisabled(), true); - await dialog.getByLabel('Promise', { exact: true }).check(); - await dialog.getByRole('searchbox').fill('answer'); - await dialog.locator('summary').filter({ hasText: 'Discovery' }).waitFor({ state: 'visible' }); - await dialog.getByLabel('Hidden answer', { exact: true }).check(); - await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click(); - await dialog.waitFor({ state: 'detached' }); - assert.deepEqual(writes[0], { bookID: 12, sceneID: 11, threadIDs: [2, 3] }); - assert.equal(await page.locator('[data-thread-rows] article').count(), 3); - assert.equal(await page.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true); - guards.push(...await page.evaluate(() => window.guardEvents)); - assert.deepEqual(guards, [true, false]); - await mount(22); - await page.getByRole('button', { name: 'Add thread', exact: true }).click(); - await dialog.getByRole('searchbox').fill('question'); - await dialog.getByLabel('A question', { exact: true }).check(); - reject = true; - await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click(); - await dialog.getByText('Thread was archived. Review selection.', { exact: true }).waitFor(); - assert.equal(links.get(22).size, 0); + assert.equal(await dialog.getByRole('checkbox', { name: /A question/ }).count(), 0); + assert.equal(await dialog.getByRole('checkbox', { name: /Hidden answer/ }).isDisabled(), true); + await dialog.getByRole('searchbox').fill('promise'); + await dialog.getByRole('checkbox', { name: /Promise · Journey/ }).check(); + const include = dialog.getByRole('button', { name: 'Include selected' }); + await include.click(); + await dialog.getByText('The saved assignment changed.').waitFor(); + assert.equal(placements.has(2), false); reject = false; - await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click(); + await include.click(); await dialog.waitFor({ state: 'detached' }); - await page.getByRole('link', {name: 'Scene 1: Earlier scene'}).waitFor(); - await mount(22); // Reload saved state through a fresh lifecycle. - await page.getByRole('link', {name: 'Scene 1: Earlier scene'}).waitFor(); - // An external saved-data hint updates the existing node without stealing focus. - links.get(22).add(2); - await page.locator('[data-thread-add]').focus(); - assert.equal(await page.evaluate(() => window.PlotDirectorContextLifecycles.threads.onInvalidation(document.querySelector('[data-test-pane="0"]').firstElementChild)), true); - await page.waitForFunction(() => document.querySelectorAll('[data-test-pane="0"] [data-thread-rows] article').length === 2); - assert.equal(await page.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true); - await mount(11, 1); - assert.equal(await page.locator('[data-test-pane="0"] [data-thread-rows] article').count(), 2); - assert.equal(await page.locator('[data-test-pane="1"] [data-thread-rows] article').count(), 3); - await page.locator('[data-test-pane="1"] [data-thread-add]').click(); - await page.keyboard.press('Escape'); - await dialog.waitFor({ state: 'detached' }); - readonly = true; - await mount(11, 1); - await page.waitForFunction(() => document.querySelector('[data-test-pane="1"] [data-thread-rows] article')); - assert.equal(await page.locator('[data-test-pane="1"] [data-thread-add]').isDisabled(), true); - readonly = false; + assert.deepEqual(writes.at(-1), { bookID: 12, chapterID: 101, sceneID: 11, threadIDs: [2], chapter: true }); + assert.equal(await add.evaluate(button => document.activeElement === button), true); await mount(22); - const later = page.locator('[data-test-pane="0"]'); - const previous = later.getByRole('link', {name: 'Scene 1: Earlier scene'}).first(); - assert.equal(await previous.getAttribute('href'), '/Scenes/Edit/11?retainNarrativeFocus=true'); - assert.equal(await previous.getAttribute('data-context-narrative'), 'author'); - assert.equal(await later.getByText('Last pickup', {exact: true}).first().isVisible(), true); - await later.locator('summary').first().click(); - assert.equal(await later.locator('details').first().getAttribute('open'), null); - await later.getByRole('button', {name: 'Remove A question from scene', exact: true}).click(); - await later.getByRole('heading', {name: 'A question', exact: true}).waitFor({state: 'detached'}); - assert.deepEqual(writes.at(-1), {bookID: 12, sceneID: 22, threadID: 1}); - assert.equal(links.get(11).has(1), true); - assert.equal(await later.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true); - await later.getByRole('button', { name: 'Add thread', exact: true }).click(); - await dialog.getByRole('searchbox').fill('question'); - assert.equal(await dialog.getByLabel('A question', {exact: true}).isEnabled(), true); - await dialog.getByRole("button", {name: "Cancel", exact: true}).click(); - await dialog.waitFor({state: 'detached'}); + await page.getByRole('button', { name: 'Remove Promise from chapter' }).waitFor(); + await page.locator('summary', { hasText: 'Assigned elsewhere and scene history' }).click(); + const earlier = page.getByRole('link', { name: 'Scene 1: Earlier scene' }); + assert.equal(await earlier.getAttribute('href'), '/Scenes/Edit/11?retainNarrativeFocus=true'); + await page.getByRole('button', { name: 'Remove Promise from chapter' }).click(); + await page.getByText('No threads included here.').waitFor(); + assert.deepEqual(writes.at(-1), { bookID: 12, chapterID: 101, sceneID: 22, threadID: 2, chapter: true }); + assert.deepEqual([...placements.keys()], [1]); + invalidations.push(...await page.evaluate(() => window.invalidations)); + assert.deepEqual(invalidations, [{ bookId: 12, kind: 'threads' }, { bookId: 12, kind: 'threads' }]); + canEdit = false; + await mount(11); + assert.equal(await add.isDisabled(), true); + assert.equal(await page.getByRole('button', { name: 'Remove A question from scene' }).count(), 0); assert.deepEqual(errors, []); - console.log('PASS Context Threads nested search, parent context, linked state, multi-select, explicit target, guards, failure recovery, history, unlink, reload, split panes and read-only state (isolated fixtures)'); - } finally { await browser.close(); } -})().catch(e => { console.error(e); process.exitCode = 1; }); + console.log('PASS Context Threads search, blocked selection, exclusive assignment, chapter persistence across scenes, invalidation, history, and read-only controls (mocked)'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/PlotLine.Tests/ContextThreadsTests.cs b/PlotLine.Tests/ContextThreadsTests.cs index 625c64fd..cd009a72 100644 --- a/PlotLine.Tests/ContextThreadsTests.cs +++ b/PlotLine.Tests/ContextThreadsTests.cs @@ -35,7 +35,7 @@ internal static class ContextThreadsTests "Historical links remain visible after unassigning a thread."); Check(panel.Threads.Single(t => t.PlotThreadID == 14).AssignedElsewhere, "A chapter assignment prevents a competing scene assignment."); var planOnly = ContextThreads.Build(scope, data, [], plan); - Check(planOnly.Threads.Single(t => t.PlotThreadID == 10) is { Linked: true, CanRemove: true }, + Check(planOnly.Threads.Single(t => t.PlotThreadID == 10) is { Linked: true, CanRemove: true, HasManuscriptAssociation: false }, "A planning assignment appears in Context without generating a historical link."); Check(panel.Threads.Count == 3, "Exclude other books and projects; include project-wide lines."); var question = panel.Threads.Single(t => t.PlotThreadID == 10); @@ -47,6 +47,14 @@ internal static class ContextThreadsTests Check(earlier.Threads.Single(t => t.PlotThreadID == 10).PreviousScenes.Single().SceneID == 15, "History follows the selected scene, not IDs or latest saved scene."); Check(!earlier.Threads.Single(t => t.PlotThreadID == 10).CanRemove, "Read-only scopes cannot offer removal."); Check(typeof(ContextThreadsController).GetMethod("Remove")!.IsDefined(typeof(ValidateAntiForgeryTokenAttribute), true), "Thread removal requires antiforgery."); + var chapterScope = new SpatialScope { ProjectID = 7, BookID = 12, ChapterID = 3, CanEdit = true }; + var chapterPanel = ContextThreads.Build(chapterScope, data, links, + [.. plan, new(11, null, null, "Requires Question", "Requires Question")]); + Check(chapterPanel.Threads.Single(t => t.PlotThreadID == 14) is + { IncludedInChapter: true, IncludedInScene: false, CanRemove: true, AssignedElsewhere: false }, + "Chapter placement is editable without a scene and does not create a manuscript association."); + Check(chapterPanel.Threads.Single(t => t.PlotThreadID == 11) is { Assigned: false, ChapterBlock: "Requires Question" }, + "An unassigned prerequisite-blocked thread carries its eligibility explanation."); var backup = new ProjectBackupExport { Project = new() { ProjectID = 7 }, diff --git a/PlotLine/Controllers/ContextIntentController.cs b/PlotLine/Controllers/ContextIntentController.cs index bbc4d47a..97d01850 100644 --- a/PlotLine/Controllers/ContextIntentController.cs +++ b/PlotLine/Controllers/ContextIntentController.cs @@ -8,7 +8,7 @@ namespace PlotLine.Controllers; [Authorize] [Route("Writing/Context/Intent")] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] -public sealed class ContextIntentController(ContextIntentPalette palette, ContextIntentChecklist checklist) : Controller +public sealed class ContextIntentController(ContextIntentPalette palette, ContextIntentChecklist checklist, ContextIntentMaterial material) : Controller { // Reusable read endpoint for both Context and the docked Writer component. // It takes an explicit held scope and never follows or changes the Word caret. @@ -18,12 +18,31 @@ public sealed class ContextIntentController(ContextIntentPalette palette, Contex if (!ModelState.IsValid || projectId <= 0 || bookId <= 0 || chapterId <= 0 || sceneId <= 0) return BadRequest(); - // The fragment contains only caller-supplied IDs. The palette read - // below authorises the exact scope before returning saved information. + // Data endpoints authorise the exact scope before returning saved information. return PartialView("~/Views/Writing/_ContextIntentPanel.cshtml", new IntentPaletteScope(projectId, bookId, chapterId, sceneId)); } + [HttpGet("Material")] + public async Task Material(int bookId, int chapterId, int? sceneId) + { + if (!ModelState.IsValid) return BadRequest(); + try { return PartialView("~/Views/Writing/_ContextIntentMaterial.cshtml", await material.Read(bookId, chapterId, sceneId)); } + catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); } + } + + [HttpPost("Notes")] + [ValidateAntiForgeryToken] + public async Task Notes([FromBody] IntentNotesSave? request) + { + if (!ModelState.IsValid || request is null) return BadRequest(); + try { await material.SaveNotes(request); return NoContent(); } + catch (ArgumentException e) { return BadRequest(new { message = e.Message }); } + catch (UnauthorizedAccessException) { return StatusCode(StatusCodes.Status403Forbidden); } + catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); } + catch (SqlException e) when (e.Number == 51011) { return Conflict(new { message = e.Message }); } + } + [HttpGet("Checklist")] public Task Checklist(int bookId, int chapterId, int? sceneId) => ReadChecklist(bookId, chapterId, sceneId); diff --git a/PlotLine/Controllers/ContextThreadsController.cs b/PlotLine/Controllers/ContextThreadsController.cs index 3f63acb2..3bad70fa 100644 --- a/PlotLine/Controllers/ContextThreadsController.cs +++ b/PlotLine/Controllers/ContextThreadsController.cs @@ -18,13 +18,13 @@ public sealed class ContextThreadsController(ContextThreads threads) : Controlle } [HttpGet] - public Task State(int bookId, int sceneId) => Guard(async () => - ModelState.IsValid && bookId > 0 && sceneId > 0 ? Json(await threads.Read(bookId, sceneId)) : BadRequest()); + public Task State(int bookId, int? sceneId, int? chapterId) => Guard(async () => + ModelState.IsValid && bookId > 0 && (sceneId is > 0 || chapterId is > 0 && sceneId is null) ? Json(await threads.Read(bookId, sceneId, chapterId)) : BadRequest()); [HttpPost, ValidateAntiForgeryToken] public Task Add([FromBody] ContextThreadSelection input) => Guard(async () => { - if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0) return BadRequest(); + if (!ModelState.IsValid || input == null || input.BookID <= 0 || (input.SceneID is not > 0 && !(input.SceneID is null && input.Chapter && input.ChapterID is > 0))) return BadRequest(); await threads.Add(input); return Json(new { saved = true }); }); @@ -32,7 +32,7 @@ public sealed class ContextThreadsController(ContextThreads threads) : Controlle [HttpPost, ValidateAntiForgeryToken] public Task Remove([FromBody] ContextThreadRemoval input) => Guard(async () => { - if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0 || input.ThreadID <= 0) return BadRequest(); + if (!ModelState.IsValid || input == null || input.BookID <= 0 || (input.SceneID is not > 0 && !(input.SceneID is null && input.Chapter && input.ChapterID is > 0)) || input.ThreadID <= 0) return BadRequest(); await threads.Remove(input); return Json(new { saved = true }); }); diff --git a/PlotLine/Controllers/StoryElementReferencesController.cs b/PlotLine/Controllers/StoryElementReferencesController.cs index 6aa0ba90..946c6b76 100644 --- a/PlotLine/Controllers/StoryElementReferencesController.cs +++ b/PlotLine/Controllers/StoryElementReferencesController.cs @@ -65,12 +65,13 @@ public sealed class StoryElementReferencesController( { if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound(); var scope = new StoryElementReferenceScope(entityType, entityId); + if (entityType is StoryElementType.Chapter or StoryElementType.Scene && !WantsJson) return BadRequest(); var list = await references.ListAsync(userId, scope); if (list?.Access.CanEdit != true) return NotFound(); note = (note ?? "").Trim(); if (note.Length > 500) return Return(scope, "Use 500 characters or fewer."); - if (kind == "Characteristic" && scope.EntityType != StoryElementType.PlotThread && upload is null && note.Length > 0) + if (kind == "Characteristic" && !scope.AttachmentsOnly && upload is null && note.Length > 0) { return await Finish(scope, await references.ChangeAsync(userId, scope, "add", null, null, kind, note)); } @@ -147,6 +148,7 @@ public sealed class StoryElementReferencesController( if (!ModelState.IsValid || currentUser.UserId is not int userId || operation is not ("edit" or "delete" or "caption" or "primary" or "clear")) return NotFound(); var scope = new StoryElementReferenceScope(entityType, entityId); + if (entityType is StoryElementType.Chapter or StoryElementType.Scene && !WantsJson) return BadRequest(); note = (note ?? "").Trim(); if (note.Length > 500) return Return(scope, "Use 500 characters or fewer."); title = title?.Trim(); @@ -169,7 +171,12 @@ public sealed class StoryElementReferencesController( if (change.QuotaExceeded) return Return(scope, "This upload would exceed the account storage allowance."); if (!change.Changed) return Return(scope, "The reference changed or the note is empty. Review the saved references and try again."); - await savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID); + await (scope.EntityType switch + { + StoryElementType.Chapter => savedData.Chapter(scope.EntityID, "intent"), + StoryElementType.Scene => savedData.Scene(scope.EntityID, "intent"), + _ => savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID) + }); return Success(scope); } diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 8533f480..a8125ff1 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -138,18 +138,20 @@ public sealed class WritingController( [HttpGet("Context/Threads")] public async Task ContextThreadsTab(int? projectId, int? bookId, int? chapterId, int? sceneId, - Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextSpatial spatial) + Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextThreads threads) { - if (!ModelState.IsValid || bookId is not > 0 || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); + if (!ModelState.IsValid || bookId is not > 0 || (sceneId is not > 0 && !(sceneId is null && chapterId is > 0)) || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); var native = instanceId.HasValue ? await NativeTarget(bookId, instanceId, sessionId) : null; if (instanceId.HasValue && (native == null || native.SceneId != sceneId || chapterId.HasValue && native.ChapterId != chapterId)) return Conflict(); try { - var scope = await spatial.Scope(bookId.Value, sceneId.Value); + var scope = await threads.Scope(bookId.Value, sceneId, chapterId); if (projectId.HasValue && projectId != scope.ProjectID || chapterId.HasValue && chapterId != scope.ChapterID) return BadRequest(); if (instanceId.HasValue && !SameNativeTarget(native, await NativeTarget(bookId, instanceId, sessionId))) return Conflict(); return PartialView("_ContextThreads", scope); } + catch (UnauthorizedAccessException) { return Forbid(); } + catch (ArgumentException) { return BadRequest(); } catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); } } diff --git a/PlotLine/Data/StoryElementReferenceRepository.cs b/PlotLine/Data/StoryElementReferenceRepository.cs index 525ecdd9..a0160388 100644 --- a/PlotLine/Data/StoryElementReferenceRepository.cs +++ b/PlotLine/Data/StoryElementReferenceRepository.cs @@ -3,10 +3,12 @@ using Dapper; namespace PlotLine.Data; -public enum StoryElementType { Character, Location, Asset, PlotThread } +public enum StoryElementType { Character, Location, Asset, PlotThread, Chapter, Scene } public sealed record StoryElementReferenceScope(StoryElementType EntityType, int EntityID) { + public bool AttachmentsOnly => EntityType is StoryElementType.PlotThread or StoryElementType.Chapter or StoryElementType.Scene; + public string DetailsController => EntityType switch { StoryElementType.Character => "Characters", diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 365ed9ab..22c1f1f9 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -314,6 +314,10 @@ public sealed class ProjectBackupStoryElementReference { [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] public int? PlotThreadID { get; set; } + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public int? ChapterID { get; set; } + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public int? SceneID { get; set; } public int ReferenceID { get; set; } public int? CharacterID { get; set; } public int? LocationID { get; set; } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index be3ec8df..c9a0c5c8 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -316,6 +316,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/BookBackupGraph.cs b/PlotLine/Services/BookBackupGraph.cs index 6c5811fb..7938ef0c 100644 --- a/PlotLine/Services/BookBackupGraph.cs +++ b/PlotLine/Services/BookBackupGraph.cs @@ -35,6 +35,9 @@ public static class BookBackupGraph if (!removed) break; } var scenes = b.Data.Scenes.Select(s => s.SceneID).ToHashSet(); + var chapters = b.Data.Chapters.Select(c => c.ChapterID).ToHashSet(); + b.Data.StoryElementReferences = b.Data.StoryElementReferences?.Where(r => (!r.ChapterID.HasValue || chapters.Contains(r.ChapterID.Value)) + && (!r.SceneID.HasValue || scenes.Contains(r.SceneID.Value))).ToList(); if (source.Data.SceneDependencies.Any(d => scenes.Contains(d.SourceSceneID) != scenes.Contains(d.TargetSceneID))) throw new ArgumentException("These books have a cross-book scene dependency. Include the connected books to preserve it."); if (source.Data.MapJourneyNotes.Any(n => scenes.Contains(n.FromSceneID) != scenes.Contains(n.ToSceneID))) throw new ArgumentException("A saved map journey connects these books. Include the connected books to preserve it."); b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Where(r => Identity(r.Collection) is string identity && Rows(b, r.Collection).Any(owner => Equals(Value(owner, identity), r.OwnerID))).ToList(); diff --git a/PlotLine/Services/Context/ContextIntentMaterial.cs b/PlotLine/Services/Context/ContextIntentMaterial.cs new file mode 100644 index 00000000..34b6f0b7 --- /dev/null +++ b/PlotLine/Services/Context/ContextIntentMaterial.cs @@ -0,0 +1,46 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; + +namespace PlotLine.Services.Context; + +public sealed record IntentNotesSave(int BookID, int ChapterID, int? SceneID, string? Original, string? Notes); +public sealed record IntentSourceNote(string ThreadTitle, string? WritingNotes, string? PlanningChecklist, int? SceneID) +{ + public IReadOnlyList Items => PlanningChecklist is null ? [] + : JsonSerializer.Deserialize>(PlanningChecklist) ?? []; +} +public sealed record IntentSourceReference(int ReferenceID, string EntityType, int EntityID, + string Kind, string Note, string? Title, string? OriginalFileName, string Source, int? SceneID); +public sealed record IntentMaterial(IReadOnlyList Notes, IReadOnlyList References); + +public sealed class ContextIntentMaterial(ISqlConnectionFactory connections, ICurrentUserService user, + ContextWorkspaceNotifications notifications) +{ + public async Task Read(int bookId, int chapterId, int? sceneId) + { + using var db = connections.CreateConnection(); + using var result = await db.QueryMultipleAsync("dbo.ContextIntent_Material", + new { UserID = user.UserId!.Value, BookID = bookId, ChapterID = chapterId, SceneID = sceneId }, + commandType: CommandType.StoredProcedure); + var notes = (await result.ReadAsync()).AsList(); + var references = (await result.ReadAsync()).DistinctBy(row => row.ReferenceID).ToArray(); + return new(notes, references); + } + + public async Task SaveNotes(IntentNotesSave request) + { + ContextIntentPalette.Validate(new(request.BookID, request.ChapterID, request.SceneID)); + if (request.Notes?.Length > 100_000) + throw new ArgumentException("Use 100,000 characters or fewer."); + var author = user.UserId ?? throw new UnauthorizedAccessException(); + using var db = connections.CreateConnection(); + var project = await db.QuerySingleAsync("dbo.ContextIntent_SaveNotes", + new { UserID = author, request.BookID, request.ChapterID, request.SceneID, request.Original, request.Notes }, + commandType: CommandType.StoredProcedure); + await notifications.Invalidate(author, request.BookID, request.ChapterID, request.SceneID, project, kind: "intent"); + } +} diff --git a/PlotLine/Services/Context/ContextThreads.cs b/PlotLine/Services/Context/ContextThreads.cs index e1716757..e1926362 100644 --- a/PlotLine/Services/Context/ContextThreads.cs +++ b/PlotLine/Services/Context/ContextThreads.cs @@ -7,24 +7,40 @@ using PlotLine.Models; namespace PlotLine.Services.Context; public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName, - bool Linked, bool CanRemove, IReadOnlyList PreviousScenes, bool AssignedElsewhere); -public sealed record ContextThreadPlacement(int PlotThreadID, int? AssignedSceneID, int? AssignedChapterID); + bool Linked, bool CanRemove, IReadOnlyList PreviousScenes, bool AssignedElsewhere, bool IncludedInChapter, bool IncludedInScene, + string? SceneBlock, string? ChapterBlock, bool Assigned, string? AssignmentLabel, bool HasManuscriptAssociation); +public sealed record ContextThreadPlacement(int PlotThreadID, int? AssignedSceneID, int? AssignedChapterID, + string? SceneBlock = null, string? ChapterBlock = null, string? AssignmentLabel = null); public sealed record ContextThreadsPanel(SpatialScope Scope, IReadOnlyList Threads); -public sealed record ContextThreadSelection(int BookID, int SceneID, int[] ThreadIDs); -public sealed record ContextThreadRemoval(int BookID, int SceneID, int ThreadID); +public sealed record ContextThreadSelection(int BookID, int? SceneID, int[] ThreadIDs, bool Chapter = false, int? ChapterID = null); +public sealed record ContextThreadRemoval(int BookID, int? SceneID, int ThreadID, bool Chapter = false, int? ChapterID = null); public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace, ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications) { - public async Task Read(int book, int scene) + public async Task Scope(int book, int? scene, int? chapter) { - var scope = await spatial.Scope(book, scene); + if (scene.HasValue) + { + var scope = await spatial.Scope(book, scene.Value); + if (chapter.HasValue && scope.ChapterID != chapter) throw new ArgumentException("Choose a scene in this chapter."); + return scope; + } + using var db = connections.CreateConnection(); + return await db.QuerySingleOrDefaultAsync("dbo.ContextThreads_Chapter", + new { BookID = book, ChapterID = chapter, UserID = user.UserId!.Value }, + commandType: CommandType.StoredProcedure) ?? throw new UnauthorizedAccessException(); + } + + public async Task Read(int book, int? scene, int? chapter) + { + var scope = await Scope(book, scene, chapter); var data = await workspace.GetAsync(scope.ProjectID, book, null); using var db = connections.CreateConnection(); var links = await db.QueryAsync("dbo.SceneThread_ListByBook", new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure); - var placements = await db.QueryAsync("dbo.PlotThreadPlanning_ListByBook", - new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure); + var placements = await db.QueryAsync("dbo.ContextThreads_List", + new { BookID = book, SceneID = scene, ChapterID = scope.ChapterID, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure); return Build(scope, data, links, placements); } @@ -32,12 +48,10 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep IEnumerable planning) { var scenes = data.AttributionScenes.Where(s => s.BookID == scope.BookID).ToDictionary(s => s.SceneID); - if (!scenes.TryGetValue(scope.SceneID, out var current)) throw new ArgumentException("Scene order is unavailable."); + if (!scenes.TryGetValue(scope.SceneID, out var current) && scope.SceneID > 0) throw new ArgumentException("Scene order is unavailable."); var lines = data.PlotLines.Where(l => l.ProjectID == scope.ProjectID && (l.BookID == null || l.BookID == scope.BookID)).ToDictionary(l => l.PlotLineID); var plans = planning.ToDictionary(p => p.PlotThreadID); var associations = links.Select(l => (l.PlotThreadID, l.SceneID)).ToHashSet(); - associations.UnionWith(plans.Values.Where(p => p.AssignedSceneID.HasValue) - .Select(p => (p.PlotThreadID, p.AssignedSceneID!.Value))); associations.UnionWith(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID))); // Established milestones are authoritative associations too. A planned resolution // alone is a future intention, not a scene where the thread has been picked up. @@ -46,14 +60,22 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep if (thread.IntroducedSceneID is int introduced) associations.Add((thread.PlotThreadID, introduced)); if (thread.ActualResolutionSceneID is int resolved) associations.Add((thread.PlotThreadID, resolved)); } - var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t => new ContextThreadRow( - t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName, - associations.Contains((t.PlotThreadID, scope.SceneID)), - scope.CanEdit && plans.GetValueOrDefault(t.PlotThreadID)?.AssignedSceneID == scope.SceneID, - scenes.Values.Where(s => s.NarrativeOrder < current.NarrativeOrder && associations.Contains((t.PlotThreadID, s.SceneID))) - .OrderBy(s => s.NarrativeOrder).ToArray(), - plans.GetValueOrDefault(t.PlotThreadID) is { } plan - && (plan.AssignedChapterID.HasValue || (plan.AssignedSceneID.HasValue && plan.AssignedSceneID != scope.SceneID)))).OrderBy(t => t.PlotLineName, StringComparer.CurrentCultureIgnoreCase).ThenBy(t => t.Title, StringComparer.CurrentCultureIgnoreCase).ToArray(); + var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t => + { + var placement = plans.GetValueOrDefault(t.PlotThreadID); + var includedInScene = placement?.AssignedSceneID == scope.SceneID; + var includedInChapter = scope.ChapterID > 0 && placement?.AssignedChapterID == scope.ChapterID; + var assigned = placement?.AssignedChapterID is not null || placement?.AssignedSceneID is not null; + var recordedHere = associations.Contains((t.PlotThreadID, scope.SceneID)); + var history = scenes.Values.Where(s => current is not null && s.NarrativeOrder < current.NarrativeOrder + && associations.Contains((t.PlotThreadID, s.SceneID))) + .OrderBy(s => s.NarrativeOrder).ToArray(); + return new ContextThreadRow(t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName, + recordedHere || includedInScene, scope.CanEdit && (includedInScene || includedInChapter), history, + assigned && !includedInScene && !includedInChapter, includedInChapter, includedInScene, + placement?.SceneBlock, placement?.ChapterBlock, assigned, placement?.AssignmentLabel, recordedHere); + }).OrderBy(t => t.PlotLineName, StringComparer.CurrentCultureIgnoreCase) + .ThenBy(t => t.Title, StringComparer.CurrentCultureIgnoreCase).ToArray(); return new(scope, rows); } @@ -62,8 +84,8 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep if (input.ThreadIDs is not { Length: > 0 and <= 200 } || input.ThreadIDs.Any(id => id <= 0)) throw new ArgumentException("Choose between 1 and 200 threads."); using var db = connections.CreateConnection(); - var project = await db.QuerySingleAsync("dbo.PlotThreadPlanning_ChangeScene", - new { input.BookID, input.SceneID, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()), Remove = false }, + var project = await db.QuerySingleAsync("dbo.ContextThreads_Change", + new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()), Remove = false }, commandType: CommandType.StoredProcedure); // Any earlier scene can affect history in all later scenes of the same book. await notifications.Invalidate(user.UserId!.Value, projectId: project, bookId: input.BookID, kind: "threads"); @@ -73,8 +95,8 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep { var userId = user.UserId ?? throw new UnauthorizedAccessException(); using var db = connections.CreateConnection(); - var project = await db.QuerySingleAsync("dbo.PlotThreadPlanning_ChangeScene", - new { input.BookID, input.SceneID, UserID = userId, ThreadIDs = JsonSerializer.Serialize(new[] { input.ThreadID }), Remove = true }, + var project = await db.QuerySingleAsync("dbo.ContextThreads_Change", + new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = userId, ThreadIDs = JsonSerializer.Serialize(new[] { input.ThreadID }), Remove = true }, commandType: CommandType.StoredProcedure); await notifications.Invalidate(userId, projectId: project, bookId: input.BookID, kind: "threads"); } diff --git a/PlotLine/Services/ContextSavedData.cs b/PlotLine/Services/ContextSavedData.cs index 20ee099d..8533e1c3 100644 --- a/PlotLine/Services/ContextSavedData.cs +++ b/PlotLine/Services/ContextSavedData.cs @@ -39,7 +39,7 @@ public sealed class ContextSavedData(ContextWorkspaceNotifications notifications { "Character" => "characters", "Relationship" => "relationships", "Location" or "Location Relationship" => "locations", - "Plot Line" => "plotlines", "Thread" or "Thread Event" => "threads", + "Plot Line" => "plotlines", "PlotThread" or "Thread" or "Thread Event" => "threads", "Floor Plan" or "Floor Plan Transition" or "Floor Plan Background" => "floorplans", "Asset" or "Asset Event" => "assets", _ => null }; diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 8a685fc2..b1f72136 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -47,7 +47,8 @@ internal static class ProjectBackupGraphValidation new("OnboardingManuscriptBuildCharacterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("CharacterID","Characters","CharacterID")), new("StoryElementReferences", "ReferenceID", new Link("CharacterID", "Characters", "CharacterID"), new Link("LocationID", "Locations", "LocationID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID"), - new Link("PlotThreadID", "PlotThreads", "PlotThreadID")), + new Link("PlotThreadID", "PlotThreads", "PlotThreadID"), + new Link("ChapterID", "Chapters", "ChapterID"), new Link("SceneID", "Scenes", "SceneID")), new("CharacterImages","CharacterImageID",new Link("CharacterID","Characters","CharacterID"),new Link("ProjectID","Project","ProjectID")), new("WordCompanionSceneAssets","WordCompanionSceneAssetID",new Link("SceneID","Scenes","SceneID"),new Link("StoryAssetID","StoryAssets","StoryAssetID")), new("WordCompanionSceneLocations","WordCompanionSceneLocationID",new Link("SceneID","Scenes","SceneID"),new Link("LocationID","Locations","LocationID")), @@ -148,16 +149,17 @@ internal static class ProjectBackupGraphValidation var primaryReferenceOwners = new HashSet<(int? LocationID, int? StoryAssetID)>(); foreach (var reference in backup.Data.StoryElementReferences ?? []) { + var intentAttachment = reference.ChapterID.HasValue || reference.SceneID.HasValue; if (reference.Title?.Length > 160 || (reference.IsPrimary.HasValue && (reference.IsPrimary != true || reference.Kind != "Image" || - reference.CharacterID.HasValue || reference.PlotThreadID.HasValue || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID))))) + reference.CharacterID.HasValue || reference.PlotThreadID.HasValue || intentAttachment || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID))))) return "Project backup contains invalid attachment metadata."; - if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID, reference.PlotThreadID }.Count(id => id.HasValue) != 1 || + if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID, reference.PlotThreadID, reference.ChapterID, reference.SceneID }.Count(id => id.HasValue) != 1 || reference.Note is null || reference.Note.Length > 500) return "Project backup contains an invalid story element reference."; if (reference.Kind == "Characteristic") { - if (string.IsNullOrWhiteSpace(reference.Note) || reference.StoragePath is not null || reference.OriginalFileName is not null) + if (intentAttachment || string.IsNullOrWhiteSpace(reference.Note) || reference.StoragePath is not null || reference.OriginalFileName is not null) return "Project backup contains an invalid key characteristic."; } else if (reference.Kind is not ("Image" or "Attachment") || diff --git a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs index 0df59d86..bd47faac 100644 --- a/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs +++ b/PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs @@ -22,7 +22,7 @@ internal static partial class ProjectBackupStoredFieldContract ["CharacterAttributeTypes"]=("CharacterAttributeTypeID,ProjectID,AttributeName,DataType,IsNormallyStable,SortOrder,IsActive","ProjectID"), ["CharacterEnrichmentEvidence"]=("CharacterEnrichmentEvidenceID,CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source,CreatedUtc","SceneID,Value,Evidence"), ["CharacterEnrichmentRuns"]=("CharacterEnrichmentRunID,ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,IsCurrent,UpdatedUtc,CharacterID","StoryIntelligenceBookPipelineID,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,FailedUtc,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,CharacterID"), - ["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,PlotThreadID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,PlotThreadID,StoragePath,OriginalFileName,Title,IsPrimary"), + ["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,PlotThreadID,ChapterID,SceneID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,PlotThreadID,ChapterID,SceneID,StoragePath,OriginalFileName,Title,IsPrimary"), ["CharacterImages"]=("CharacterImageID,CharacterID,ProjectID,ImagePath,ThumbnailPath,Caption,SortOrder,UploadedDateUTC,IsDeleted,DeletedDateUTC","Caption,DeletedDateUTC"), ["CharacterIntelligenceEvidenceEvents"]=("CharacterIntelligenceEvidenceEventID,CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source,CreatedUtc","PreviousValue,NewValue,Evidence"), ["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"), diff --git a/PlotLine/Sql/361_ContextIntentMaterial.sql b/PlotLine/Sql/361_ContextIntentMaterial.sql new file mode 100644 index 00000000..6421d68a --- /dev/null +++ b/PlotLine/Sql/361_ContextIntentMaterial.sql @@ -0,0 +1,207 @@ +CREATE OR ALTER PROCEDURE dbo.ContextIntent_Material + @UserID int, @BookID int, @ChapterID int, @SceneID int = NULL +AS +BEGIN + SET NOCOUNT ON; + DECLARE @ProjectID int; + SELECT @ProjectID = p.ProjectID + FROM dbo.Chapters c + JOIN dbo.Books b ON b.BookID = c.BookID AND b.IsArchived = 0 + JOIN dbo.Projects p ON p.ProjectID = b.ProjectID AND p.IsArchived = 0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1 + WHERE c.ChapterID = @ChapterID AND c.BookID = @BookID AND c.IsArchived = 0; + IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS + (SELECT 1 FROM dbo.Scenes WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0)) + THROW 51010, 'This Intent scope is unavailable.', 1; + + SELECT t.PlotThreadID, t.ThreadTitle, t.WritingNotes, t.PlanningChecklist, + p.SceneID, p.AssignmentOrder + INTO #Included + FROM dbo.PlotThreadPlacements p + JOIN dbo.PlotThreads t ON t.PlotThreadID = p.PlotThreadID + WHERE p.ProjectID = @ProjectID AND p.BookID = @BookID AND p.ChapterID = @ChapterID + AND (p.SceneID IS NULL OR p.SceneID = @SceneID); + + SELECT ThreadTitle, WritingNotes, PlanningChecklist, SceneID + FROM #Included ORDER BY SceneID, AssignmentOrder, PlotThreadID; + + SELECT r.ReferenceID, 'PlotThread' AS EntityType, i.PlotThreadID AS EntityID, + r.Kind, r.Note, r.Title, r.OriginalFileName, i.ThreadTitle AS Source, i.SceneID + FROM #Included i JOIN dbo.StoryElementReferences r ON r.PlotThreadID = i.PlotThreadID + UNION ALL + SELECT r.ReferenceID, CASE e.ElementType WHEN 'C' THEN 'Character' WHEN 'L' THEN 'Location' ELSE 'Asset' END, + e.ElementID, r.Kind, r.Note, r.Title, r.OriginalFileName, e.Label, i.SceneID + FROM #Included i + JOIN dbo.PlotThreadPlannedElements l ON l.PlotThreadID = i.PlotThreadID + JOIN dbo.PlotThreadPlanningElements e ON e.ProjectID = @ProjectID AND e.IsArchived = 0 + AND e.ElementType = l.ElementType AND e.ElementID = l.ElementID + JOIN dbo.StoryElementReferences r ON (e.ElementType = 'C' AND r.CharacterID = e.ElementID) + OR (e.ElementType = 'L' AND r.LocationID = e.ElementID) + OR (e.ElementType = 'A' AND r.StoryAssetID = e.ElementID) + ORDER BY ReferenceID, SceneID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ContextIntent_SaveNotes + @UserID int, @BookID int, @ChapterID int, @SceneID int = NULL, + @Original nvarchar(max), @Notes nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + DECLARE @ProjectID int, @Saved nvarchar(max); + SELECT @ProjectID = b.ProjectID FROM dbo.Chapters c WITH (HOLDLOCK) + JOIN dbo.Books b WITH (HOLDLOCK) ON b.BookID = c.BookID AND b.IsArchived = 0 + JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = b.ProjectID AND p.IsArchived = 0 + JOIN dbo.ProjectUserAccess a WITH (HOLDLOCK) ON a.ProjectID = p.ProjectID AND a.UserID = @UserID + AND a.IsActive = 1 AND a.AccessRole IN ('Owner', 'Collaborator') + WHERE c.ChapterID = @ChapterID AND c.BookID = @BookID AND c.IsArchived = 0; + IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS + (SELECT 1 FROM dbo.Scenes WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0)) + THROW 51010, 'This Intent scope is unavailable.', 1; + + IF @SceneID IS NULL + SELECT @Saved = GoalSummary FROM dbo.ChapterGoals WITH (UPDLOCK, HOLDLOCK) WHERE ChapterID = @ChapterID; + ELSE + SELECT @Saved = ScenePurposeNotes FROM dbo.Scenes WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID; + + IF CONVERT(varbinary(max), COALESCE(@Saved, N'')) <> CONVERT(varbinary(max), COALESCE(@Original, N'')) + THROW 51011, 'The saved notes changed. Your draft is still here.', 1; + + IF @SceneID IS NOT NULL + UPDATE dbo.Scenes SET ScenePurposeNotes = CASE WHEN DATALENGTH(@Notes) = 0 THEN NULL ELSE @Notes END WHERE SceneID = @SceneID; + ELSE + BEGIN + UPDATE dbo.ChapterGoals SET GoalSummary = CASE WHEN DATALENGTH(@Notes) = 0 THEN NULL ELSE @Notes END, UpdatedDate = SYSUTCDATETIME() + WHERE ChapterID = @ChapterID; + IF @@ROWCOUNT = 0 AND DATALENGTH(@Notes) > 0 + INSERT dbo.ChapterGoals (ChapterID, GoalSummary) VALUES (@ChapterID, @Notes); + END; + COMMIT TRANSACTION; + SELECT @ProjectID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.SceneWorkflow_Get @SceneID int +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + IF NOT EXISTS (SELECT 1 FROM dbo.SceneWorkflow WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID) + INSERT dbo.SceneWorkflow (SceneID) VALUES (@SceneID); + COMMIT TRANSACTION; + + SELECT SceneWorkflowID, SceneID, DraftStatus, EstimatedWordCount, ActualWordCount, DraftedDate, LastWorkedOn, + ReadyForDraft, ReadyForRevision, ReadyForPolish, IsBlocked, BlockedReason, Priority, CreatedDate, UpdatedDate + FROM dbo.SceneWorkflow WHERE SceneID = @SceneID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ContextThreads_List + @BookID int, @UserID int, @SceneID int = NULL, @ChapterID int = NULL +AS +BEGIN + SET NOCOUNT ON; + SELECT t.PlotThreadID, t.AssignedSceneID, t.AssignedChapterID, + sceneBlock.Reason AS SceneBlock, chapterBlock.Reason AS ChapterBlock, placement.Label AS AssignmentLabel + FROM dbo.PlotPlanningTargets currentScene + JOIN dbo.PlotPlanningTargets currentChapter ON currentChapter.BookID = currentScene.BookID + AND currentChapter.ChapterID = currentScene.ChapterID AND currentChapter.SceneID IS NULL + JOIN dbo.PlotLines l ON l.ProjectID = currentScene.ProjectID AND l.IsArchived = 0 + AND (l.BookID IS NULL OR l.BookID = @BookID) + JOIN dbo.PlotThreads t ON t.PlotLineID = l.PlotLineID AND t.IsArchived = 0 + LEFT JOIN dbo.PlotThreadPlacements placement ON placement.PlotThreadID = t.PlotThreadID + OUTER APPLY ( + SELECT TOP (1) CONCAT(N'Place “', COALESCE(r.ThreadTitle, N'deleted thread'), N'” earlier in this book.') AS Reason + FROM dbo.PlotThreadPrerequisites e + LEFT JOIN dbo.PlotThreads r ON r.PlotThreadID = e.PrerequisiteID + LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID + WHERE e.PlotThreadID = t.PlotThreadID AND + (p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= currentScene.NarrativeOrder) + ORDER BY e.PrerequisiteID + ) sceneBlock + OUTER APPLY ( + SELECT TOP (1) CONCAT(N'Place “', COALESCE(r.ThreadTitle, N'deleted thread'), N'” earlier in this book.') AS Reason + FROM dbo.PlotThreadPrerequisites e + LEFT JOIN dbo.PlotThreads r ON r.PlotThreadID = e.PrerequisiteID + LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID + WHERE e.PlotThreadID = t.PlotThreadID AND + (p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= currentChapter.NarrativeOrder) + ORDER BY e.PrerequisiteID + ) chapterBlock + WHERE currentScene.BookID = @BookID + AND (currentScene.SceneID = @SceneID OR (@SceneID IS NULL AND currentScene.SceneID IS NULL AND currentScene.ChapterID = @ChapterID)) + AND EXISTS (SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID = a.ProjectID AND p.IsArchived = 0 + WHERE a.ProjectID = currentScene.ProjectID AND a.UserID = @UserID AND a.IsActive = 1); +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ContextThreads_Change + @BookID int, @SceneID int, @UserID int, @ThreadIDs nvarchar(max), @Remove bit, @Chapter bit, @ChapterID int = NULL +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + DECLARE @ProjectID int, @TargetChapterID int, @TargetOrder bigint; + SELECT @ProjectID = ProjectID, @TargetChapterID = ChapterID, @TargetOrder = NarrativeOrder + FROM dbo.PlotPlanningTargets WHERE BookID = @BookID + AND (SceneID = @SceneID OR (@Chapter = 1 AND @SceneID IS NULL AND SceneID IS NULL AND ChapterID = @ChapterID)) + AND (@ChapterID IS NULL OR ChapterID = @ChapterID); + IF @ProjectID IS NULL OR NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess a WITH (HOLDLOCK) + JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0 + WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1 AND a.AccessRole IN ('Owner', 'Collaborator')) + THROW 51100, 'Edit access to this scene is required.', 1; + + DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'PlotThreadPlanning:', @ProjectID); + EXEC @LockResult = sys.sp_getapplock @Resource, 'Exclusive', 'Transaction', 10000; + IF @LockResult < 0 THROW 51101, 'Planning is busy. Try again.', 1; + + IF @Chapter = 1 + SELECT @TargetOrder = NarrativeOrder FROM dbo.PlotPlanningTargets + WHERE BookID = @BookID AND ChapterID = @TargetChapterID AND SceneID IS NULL; + IF @Remove = 0 AND EXISTS ( + SELECT 1 FROM dbo.PlotThreadPrerequisites e + LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID + WHERE e.PlotThreadID IN (SELECT TRY_CONVERT(int, value) FROM OPENJSON(@ThreadIDs)) + AND (p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= @TargetOrder)) + THROW 51101, 'Place the prerequisite threads earlier in this book before including this thread.', 1; + + DECLARE @ThreadCount int = (SELECT COUNT(DISTINCT TRY_CONVERT(int, value)) FROM OPENJSON(@ThreadIDs)); + UPDATE t SET AssignedSceneID = CASE WHEN @Remove = 0 AND @Chapter = 0 THEN @SceneID END, + AssignedChapterID = CASE WHEN @Remove = 0 AND @Chapter = 1 THEN @TargetChapterID END, + AssignmentOrder = CASE WHEN @Remove = 0 THEN t.AssignmentOrder ELSE 0 END, + UpdatedDate = SYSUTCDATETIME() + FROM dbo.PlotThreads t + JOIN dbo.PlotLines l ON l.PlotLineID = t.PlotLineID AND l.ProjectID = @ProjectID AND l.IsArchived = 0 + WHERE t.IsArchived = 0 AND (l.BookID IS NULL OR l.BookID = @BookID) + AND t.PlotThreadID IN (SELECT TRY_CONVERT(int, value) FROM OPENJSON(@ThreadIDs)) + AND ((@Remove = 1 AND ((@Chapter = 0 AND t.AssignedSceneID = @SceneID) + OR (@Chapter = 1 AND t.AssignedChapterID = @TargetChapterID))) + OR (@Remove = 0 AND t.AssignedChapterID IS NULL AND t.AssignedSceneID IS NULL)); + IF @@ROWCOUNT <> @ThreadCount + THROW 51101, 'An assignment changed or is outside this book. Open the thread editor to move it.', 1; + + EXEC dbo.PlotThreadPlanning_Validate @ProjectID; + COMMIT; + SELECT @ProjectID; +END; +GO + + +CREATE OR ALTER PROCEDURE dbo.ContextThreads_Chapter + @BookID int, @ChapterID int, @UserID int +AS +BEGIN + SET NOCOUNT ON; + SELECT b.ProjectID, b.BookID, c.ChapterID, c.ChapterTitle, c.ChapterNumber, + CONVERT(bit, CASE WHEN a.AccessRole IN ('Owner', 'Collaborator') THEN 1 ELSE 0 END) AS CanEdit + FROM dbo.Chapters c + JOIN dbo.Books b ON b.BookID = c.BookID AND b.IsArchived = 0 + JOIN dbo.Projects p ON p.ProjectID = b.ProjectID AND p.IsArchived = 0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1 + WHERE b.BookID = @BookID AND c.ChapterID = @ChapterID AND c.IsArchived = 0; +END; +GO diff --git a/PlotLine/Sql/362_ContextIntentAttachments.sql b/PlotLine/Sql/362_ContextIntentAttachments.sql new file mode 100644 index 00000000..64dbe9b6 --- /dev/null +++ b/PlotLine/Sql/362_ContextIntentAttachments.sql @@ -0,0 +1,249 @@ +IF COL_LENGTH('dbo.StoryElementReferences', 'ChapterID') IS NULL + ALTER TABLE dbo.StoryElementReferences ADD ChapterID int NULL REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE; +IF COL_LENGTH('dbo.StoryElementReferences', 'SceneID') IS NULL + ALTER TABLE dbo.StoryElementReferences ADD SceneID int NULL REFERENCES dbo.Scenes(SceneID) ON DELETE CASCADE; +GO + +IF OBJECT_ID('dbo.CK_StoryElementReferences_IntentFile', 'C') IS NULL +BEGIN + ALTER TABLE dbo.StoryElementReferences DROP CONSTRAINT CK_StoryElementReferences_Entity; + ALTER TABLE dbo.StoryElementReferences WITH CHECK ADD CONSTRAINT CK_StoryElementReferences_Entity CHECK + ((CASE WHEN CharacterID IS NULL THEN 0 ELSE 1 END + + CASE WHEN LocationID IS NULL THEN 0 ELSE 1 END + + CASE WHEN StoryAssetID IS NULL THEN 0 ELSE 1 END + + CASE WHEN PlotThreadID IS NULL THEN 0 ELSE 1 END + + CASE WHEN ChapterID IS NULL THEN 0 ELSE 1 END + + CASE WHEN SceneID IS NULL THEN 0 ELSE 1 END) = 1); + ALTER TABLE dbo.StoryElementReferences WITH CHECK ADD CONSTRAINT CK_StoryElementReferences_IntentFile + CHECK ((ChapterID IS NULL AND SceneID IS NULL) OR (Kind IN ('Image', 'Attachment') AND IsPrimary IS NULL)); + CREATE INDEX IX_StoryElementReferences_Chapter ON dbo.StoryElementReferences(ChapterID, ReferenceID) WHERE ChapterID IS NOT NULL; + CREATE INDEX IX_StoryElementReferences_Scene ON dbo.StoryElementReferences(SceneID, ReferenceID) WHERE SceneID IS NOT NULL; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Access + @UserID int, @EntityType varchar(12), @EntityID int, @Action varchar(12), + @ReferenceID int = NULL, @Version binary(8) = NULL, @Kind varchar(14) = NULL, + @Note nvarchar(500) = NULL, @StoragePath nvarchar(1000) = NULL, + @OriginalFileName nvarchar(300) = NULL, @FileSizeBytes bigint = NULL, + @Title nvarchar(160) = NULL, @StorageLimitBytes bigint = NULL +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + DECLARE @ProjectID int, @EntityName nvarchar(300), @CanEdit bit, @OwnerID int, + @CharacterID int, @LocationID int, @AssetID int, @ThreadID int, @ChapterID int, @SceneID int, @LegacyImagePath nvarchar(1000); + BEGIN TRY + BEGIN TRANSACTION; + IF @EntityType = 'Character' + BEGIN + SET @CharacterID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = CharacterName + FROM dbo.Characters WITH (HOLDLOCK) WHERE CharacterID = @EntityID AND IsArchived = 0; + END + ELSE IF @EntityType = 'Location' + BEGIN + SET @LocationID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = LocationName + FROM dbo.Locations WITH (HOLDLOCK) WHERE LocationID = @EntityID AND IsArchived = 0; + END + ELSE IF @EntityType = 'Asset' + BEGIN + SET @AssetID = @EntityID; + SELECT @ProjectID = ProjectID, @EntityName = AssetName, @LegacyImagePath = ImagePath + FROM dbo.StoryAssets WITH (HOLDLOCK) WHERE StoryAssetID = @EntityID AND IsArchived = 0; + END + + ELSE IF @EntityType = 'PlotThread' + BEGIN + SET @ThreadID = @EntityID; + SELECT @ProjectID = l.ProjectID, @EntityName = t.ThreadTitle + FROM dbo.PlotThreads t WITH (HOLDLOCK) + JOIN dbo.PlotLines l WITH (HOLDLOCK) ON l.PlotLineID = t.PlotLineID + WHERE t.PlotThreadID = @EntityID AND t.IsArchived = 0 AND l.IsArchived = 0; + END + + ELSE IF @EntityType IN ('Chapter', 'Scene') + BEGIN + SELECT @ProjectID = t.ProjectID, @EntityName = t.Label, + @ChapterID = CASE WHEN @EntityType = 'Chapter' THEN t.ChapterID END, + @SceneID = t.SceneID + FROM dbo.PlotPlanningTargets t + WHERE (@EntityType = 'Chapter' AND t.ChapterID = @EntityID AND t.SceneID IS NULL) + OR (@EntityType = 'Scene' AND t.SceneID = @EntityID); + END + + SELECT @CanEdit = CONVERT(bit, MAX(CASE WHEN a.AccessRole IN (N'Owner', N'Collaborator') THEN 1 ELSE 0 END)) + FROM dbo.ProjectUserAccess a WITH (HOLDLOCK) + INNER JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0 + WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1; + + IF @CanEdit IS NULL OR (@Action NOT IN ('list', 'file') AND @CanEdit = 0) + BEGIN + IF @Action = 'list' + SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, + @LegacyImagePath AS LegacyImagePath WHERE 1 = 0; + COMMIT; + RETURN; + END + + IF @Action = 'list' + BEGIN + SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, @LegacyImagePath AS LegacyImagePath; + SELECT ReferenceID, Kind, Note, OriginalFileName, Version, Title, CONVERT(bit, COALESCE(IsPrimary, 0)) AS IsPrimary + FROM dbo.StoryElementReferences + WHERE CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID + ORDER BY ReferenceID; + END + ELSE IF @Action = 'file' + BEGIN + SELECT Kind, StoragePath, OriginalFileName + FROM dbo.StoryElementReferences + WHERE ReferenceID = @ReferenceID AND StoragePath IS NOT NULL + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID); + END + ELSE IF @Action = 'add' + BEGIN + IF @StoragePath IS NOT NULL + BEGIN + SELECT TOP (1) @OwnerID = UserID FROM dbo.ProjectUserAccess WITH (HOLDLOCK) + WHERE ProjectID = @ProjectID AND AccessRole = N'Owner' AND IsActive = 1 + ORDER BY ProjectUserAccessID; + IF @OwnerID IS NULL THROW 51010, 'Project owner unavailable.', 1; + IF @StorageLimitBytes IS NOT NULL AND @FileSizeBytes > + @StorageLimitBytes - (SELECT COALESCE(SUM(FileSizeBytes), 0) + FROM dbo.UserFile WITH (UPDLOCK, HOLDLOCK) WHERE UserID = @OwnerID AND IsDeleted = 0) + BEGIN + SELECT @ProjectID AS ProjectID, CONVERT(bit, 0) AS Changed, CONVERT(bit, 1) AS QuotaExceeded; + COMMIT; + RETURN; + END + END + + INSERT dbo.StoryElementReferences (CharacterID, LocationID, StoryAssetID, PlotThreadID, ChapterID, SceneID, Kind, Note, StoragePath, OriginalFileName) + VALUES (@CharacterID, @LocationID, @AssetID, @ThreadID, @ChapterID, @SceneID, @Kind, @Note, @StoragePath, @OriginalFileName); + IF @StoragePath IS NOT NULL + INSERT dbo.UserFile (UserID, ProjectID, EntityType, EntityID, FileName, OriginalFileName, ContentType, FileSizeBytes, StoragePath) + VALUES (@OwnerID, @ProjectID, N'StoryElementReference', CONVERT(int, SCOPE_IDENTITY()), + RIGHT(@StoragePath, CHARINDEX('/', REVERSE(@StoragePath)) - 1), @OriginalFileName, + CASE @Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END, @FileSizeBytes, @StoragePath); + SELECT @ProjectID AS ProjectID, CONVERT(bit, 1) AS Changed; + END + ELSE IF @Action = 'caption' + BEGIN + UPDATE dbo.CharacterImages SET Caption = NULLIF(@Note, N'') + WHERE CharacterImageID = @ReferenceID AND CharacterID = @CharacterID AND ProjectID = @ProjectID AND IsDeleted = 0; + SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed; + END + ELSE IF @Action IN ('primary', 'clear') + BEGIN + DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'StoryReferencePrimary:', @EntityType, N':', @EntityID); + EXEC @LockResult = sys.sp_getapplock @Resource = @Resource, @LockMode = 'Exclusive', + @LockOwner = 'Transaction', @LockTimeout = 5000; + IF @LockResult < 0 THROW 51010, 'Primary image selection is busy.', 1; + + DECLARE @ImageID int; + SELECT @ImageID = ReferenceID FROM dbo.StoryElementReferences WITH (UPDLOCK) + WHERE ReferenceID = @ReferenceID AND Version = @Version AND Kind = 'Image' + AND (@Action = 'primary' OR IsPrimary = 1) + AND (LocationID = @LocationID OR StoryAssetID = @AssetID); + + IF @ImageID IS NOT NULL + BEGIN + UPDATE dbo.StoryElementReferences + SET IsPrimary = NULL + WHERE IsPrimary = 1 AND (LocationID = @LocationID OR StoryAssetID = @AssetID); + IF @Action = 'primary' + UPDATE dbo.StoryElementReferences SET IsPrimary = 1 WHERE ReferenceID = @ImageID; + END + SELECT @ProjectID AS ProjectID, CONVERT(bit, CASE WHEN @ImageID IS NULL THEN 0 ELSE 1 END) AS Changed; + END + ELSE IF @Action = 'edit' + BEGIN + UPDATE dbo.StoryElementReferences SET Note = @Note, Title = @Title + WHERE ReferenceID = @ReferenceID AND Version = @Version + AND (Kind <> 'Characteristic' OR LEN(@Note) > 0) + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID); + SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed; + END + ELSE IF @Action = 'delete' + BEGIN + DECLARE @Removed TABLE (StoragePath nvarchar(1000)); + DELETE dbo.StoryElementReferences + OUTPUT deleted.StoragePath INTO @Removed + WHERE ReferenceID = @ReferenceID AND Version = @Version + AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID); + SELECT @ProjectID AS ProjectID, CONVERT(bit, COUNT(*)) AS Changed, MAX(StoragePath) AS StoragePath + FROM @Removed; + END + + COMMIT; + END TRY + BEGIN CATCH + IF XACT_STATE() <> 0 ROLLBACK; + THROW; + END CATCH +END; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Backup @ProjectID int +AS +BEGIN + SET NOCOUNT ON; + SELECT r.ReferenceID, r.CharacterID, r.LocationID, r.StoryAssetID, r.PlotThreadID, r.ChapterID, r.SceneID, + r.Kind, r.Note, r.StoragePath, r.OriginalFileName, r.Title, r.IsPrimary + FROM dbo.StoryElementReferences r + LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID + LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID + LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID + LEFT JOIN dbo.PlotThreads t ON t.PlotThreadID = r.PlotThreadID + LEFT JOIN dbo.PlotLines pl ON pl.PlotLineID = t.PlotLineID + LEFT JOIN dbo.Scenes sc ON sc.SceneID = r.SceneID + LEFT JOIN dbo.Chapters ch ON ch.ChapterID = COALESCE(r.ChapterID, sc.ChapterID) + LEFT JOIN dbo.Books b ON b.BookID = ch.BookID + WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID, pl.ProjectID, b.ProjectID) = @ProjectID + ORDER BY r.ReferenceID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Restore @ProjectID int, @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + IF EXISTS ( + SELECT 1 + FROM OPENJSON(@JsonData, '$.Data.StoryElementReferences') WITH + ( + ReferenceID int, CharacterID int, LocationID int, StoryAssetID int, PlotThreadID int, ChapterID int, SceneID int, StoragePath nvarchar(1000) + ) r + LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID + LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID + LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID + LEFT JOIN dbo.PlotThreads t ON t.PlotThreadID = r.PlotThreadID + LEFT JOIN dbo.PlotLines pl ON pl.PlotLineID = t.PlotLineID + LEFT JOIN dbo.Scenes sc ON sc.SceneID = r.SceneID + LEFT JOIN dbo.Chapters ch ON ch.ChapterID = COALESCE(r.ChapterID, sc.ChapterID) + LEFT JOIN dbo.Books b ON b.BookID = ch.BookID + WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID, pl.ProjectID, b.ProjectID, -1) <> @ProjectID + OR (r.StoragePath IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM dbo.UserFile f + WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference' + AND f.EntityID = r.ReferenceID AND f.StoragePath = r.StoragePath AND f.IsDeleted = 0 + AND f.FileSizeBytes BETWEEN 1 AND 10485760 + AND f.StoragePath LIKE N'/uploads/story-element-references/%.blob' + AND CHARINDEX(N'/', f.StoragePath, LEN(N'/uploads/story-element-references/') + 1) = 0 + )) + ) + THROW 51005, 'Story element reference has an invalid project link or missing staged file.', 1; + + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryElementReferences', + N'$.Data.StoryElementReferences', @JsonData, @ProjectID, 0; + + UPDATE f SET OriginalFileName = r.OriginalFileName, + ContentType = CASE r.Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END + FROM dbo.UserFile f + INNER JOIN dbo.StoryElementReferences r ON r.ReferenceID = f.EntityID AND r.StoragePath = f.StoragePath + WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference' AND f.IsDeleted = 0; +END; +GO diff --git a/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml b/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml index f4cf0b83..d52cc293 100644 --- a/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml +++ b/PlotLine/Views/Shared/Components/StoryElementReferences/Default.cshtml @@ -15,11 +15,12 @@ string? FileUrl(StoryElementReference item, bool save = false) => Url.Action("Download", "StoryElementReferences", new { entityType = scope.EntityType, entityId = scope.EntityID, referenceId = item.ReferenceID, save }); var editable = references.Access.CanEdit; - var threadAttachments = scope.EntityType == StoryElementType.PlotThread; + var attachmentsOnly = scope.AttachmentsOnly; + var attachmentId = $"reference-attachments-{scope.EntityType}-{scope.EntityID}"; var tabs = new[] { "Images", "Audio", "Documents" }; var primary = references.Items.FirstOrDefault(item => item.IsPrimary); } -