From 978bf2b5a3c211bbe557414f565dd24de2593552 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 4 Nov 2026 03:00:12 +0000 Subject: [PATCH] Retain scene suggestion review history and manuscript statistics in backups --- .../2026-11-03-phase2-data-coverage.csv | 8 +- .../2026-11-03-phase2-field-coverage.csv | 42 ++ .../2026-11-03-phase2-roundtrip-coverage.csv | 4 + Docs/Sprints/2026-11-03-phase2.md | 10 +- .../Fixtures/ProjectTransferPlanning.sql | 8 + .../ProjectTransferDatabaseTests.cs | 17 +- PlotLine/Data/ProjectBackupRepository.cs | 9 + PlotLine/Models/ProjectBackupModels.cs | 63 +++ PlotLine/Services/ImportServices.cs | 27 +- .../Services/ProjectBackupGraphValidation.cs | 4 + .../Sql/221_ProjectBackupSceneReviewState.sql | 374 ++++++++++++++++++ 11 files changed, 557 insertions(+), 9 deletions(-) create mode 100644 PlotLine/Sql/221_ProjectBackupSceneReviewState.sql diff --git a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv index 51b94372..ce24f0e8 100644 --- a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv @@ -91,16 +91,16 @@ ScenarioSceneOrder,ProjectID or FK descendant,ScenarioSceneOrder,Serialized pers ScenarioValidationRuns,ProjectID or FK descendant,ScenarioValidationRuns,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated ScenarioWarnings,ProjectID or FK descendant,ScenarioWarnings,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneAssetLocations,ProjectID or FK descendant,SceneAssetLocations,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated -SceneAssetSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneAssetSuggestions,ProjectID or FK descendant,SceneAssetSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneAttachments,ProjectID or FK descendant,SceneAttachments,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" SceneAttachmentTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending SceneCharacters,ProjectID or FK descendant,SceneCharacters,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated -SceneCharacterSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneCharacterSuggestions,ProjectID or FK descendant,SceneCharacterSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneChecklistItems,ProjectID or FK descendant,SceneChecklistItems,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneDependencies,ProjectID or FK descendant,SceneDependencies,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneDependencyTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending SceneFloorPlanOccupancy,ProjectID or FK descendant,SceneFloorPlanOccupancy,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated -SceneLocationSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneLocationSuggestions,ProjectID or FK descendant,SceneLocationSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneManuscriptSources,ProjectID or FK descendant,SceneManuscriptSources,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneMetricTypes,ProjectID or FK descendant,SceneMetricTypes,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneMetricValues,ProjectID or FK descendant,SceneMetricValues,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated @@ -110,7 +110,7 @@ SceneOutcomes,ProjectID or FK descendant,SceneOutcomes,Serialized persistent set ScenePurposes,ProjectID or FK descendant,ScenePurposes,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated ScenePurposeTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending Scenes,ProjectID or FK descendant,Scenes,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated -SceneTextStatistics,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneTextStatistics,ProjectID or FK descendant,SceneTextStatistics,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated StoryAssets,ProjectID or FK descendant,StoryAssets,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" StoryIntelligenceBookPipelines,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending diff --git a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv index d2312e3e..894c116a 100644 --- a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv @@ -573,6 +573,17 @@ SceneAssetLocations,SceneAssetLocations,LocationID,int,False,False,True,Represen SceneAssetLocations,SceneAssetLocations,Description,nvarchar,True,False,True,Represented; projection and semantic comparison still required SceneAssetLocations,SceneAssetLocations,CreatedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required SceneAssetLocations,SceneAssetLocations,UpdatedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,SceneAssetSuggestionID,int,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,AssetID,int,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,SuggestionSource,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,DetectedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,Confidence,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,Reason,nvarchar,True,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,CreatedByUserID,int,False,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,ReviewedByUserID,int,True,False,True,Represented; projection and semantic comparison still required +SceneAssetSuggestions,SceneAssetSuggestions,ReviewedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required SceneAttachments,SceneAttachments,SceneAttachmentID,int,False,False,True,Represented; projection and semantic comparison still required SceneAttachments,SceneAttachments,SceneID,int,False,False,True,Represented; projection and semantic comparison still required SceneAttachments,SceneAttachments,SceneAttachmentTypeID,int,False,False,True,Represented; projection and semantic comparison still required @@ -605,6 +616,17 @@ SceneCharacters,SceneCharacters,MatchSource,nvarchar,True,False,True,Represented SceneCharacters,SceneCharacters,MatchedText,nvarchar,True,False,True,Represented; projection and semantic comparison still required SceneCharacters,SceneCharacters,OccurrenceCount,int,True,False,True,Represented; projection and semantic comparison still required SceneCharacters,SceneCharacters,FirstOccurrenceIndex,int,True,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,SceneCharacterSuggestionID,int,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,CharacterID,int,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,SuggestionSource,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,DetectedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,Confidence,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,Reason,nvarchar,True,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,CreatedByUserID,int,False,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,ReviewedByUserID,int,True,False,True,Represented; projection and semantic comparison still required +SceneCharacterSuggestions,SceneCharacterSuggestions,ReviewedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required SceneChecklistItems,SceneChecklistItems,SceneChecklistItemID,int,False,False,True,Represented; projection and semantic comparison still required SceneChecklistItems,SceneChecklistItems,SceneID,int,False,False,True,Represented; projection and semantic comparison still required SceneChecklistItems,SceneChecklistItems,ItemText,nvarchar,False,False,True,Represented; projection and semantic comparison still required @@ -635,6 +657,17 @@ SceneFloorPlanOccupancy,SceneFloorPlanOccupancy,StoryAssetID,int,True,False,True SceneFloorPlanOccupancy,SceneFloorPlanOccupancy,LocationID,int,False,False,True,Represented; projection and semantic comparison still required SceneFloorPlanOccupancy,SceneFloorPlanOccupancy,CreatedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required SceneFloorPlanOccupancy,SceneFloorPlanOccupancy,ModifiedDate,datetime2,True,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,SceneLocationSuggestionID,int,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,LocationID,int,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,SuggestionSource,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,DetectedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,Confidence,nvarchar,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,Reason,nvarchar,True,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,CreatedByUserID,int,False,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,ReviewedByUserID,int,True,False,True,Represented; projection and semantic comparison still required +SceneLocationSuggestions,SceneLocationSuggestions,ReviewedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required SceneManuscriptSources,SceneManuscriptSources,SceneID,int,False,False,True,Represented; projection and semantic comparison still required SceneManuscriptSources,SceneManuscriptSources,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required SceneManuscriptSources,SceneManuscriptSources,BookID,int,False,False,True,Represented; projection and semantic comparison still required @@ -728,6 +761,15 @@ Scenes,Scenes,POVConfidence,decimal,True,False,True,Represented; projection and Scenes,Scenes,POVEvidence,nvarchar,True,False,True,Represented; projection and semantic comparison still required Scenes,Scenes,POVSuggestedName,nvarchar,True,False,True,Represented; projection and semantic comparison still required Scenes,Scenes,StructuralSetting,nvarchar,True,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,TotalWordCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,DialogueWordCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,ProseWordCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,TotalParagraphCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,DialogueParagraphCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,ProseParagraphCount,int,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,CalculatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +SceneTextStatistics,SceneTextStatistics,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required SceneWorkflow,SceneWorkflow,SceneWorkflowID,int,False,False,True,Represented; projection and semantic comparison still required SceneWorkflow,SceneWorkflow,SceneID,int,False,False,True,Represented; projection and semantic comparison still required SceneWorkflow,SceneWorkflow,DraftStatus,nvarchar,False,False,True,Represented; projection and semantic comparison still required diff --git a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv index bd8436b9..688856fe 100644 --- a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv @@ -1,4 +1,8 @@ Collection,SourceRows,CopyRows,InPlaceRows,Verification +SceneAssetSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +SceneCharacterSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +SceneLocationSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +SceneTextStatistics,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present OnboardingManuscriptBuilds,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present OnboardingManuscriptBuildChapterMap,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present OnboardingManuscriptBuildSceneMap,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 2bb8be82..07db539d 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -16,7 +16,7 @@ 2. COMPLETE: Writer/shared surface spacing, requested icon changes, Locations conventional commands/grips, mobile Chapter table repair and rendered coverage inventory (9d78a63, 016b58f, 869e305). 3. DEFERRED ACCEPTANCE: authenticated live Writer/PWA testing; no session is available. Real full-layout browser/Hub fixture results are recorded separately. 4. DEFERRED DEPLOYMENT: two illustration records were Generating at restart preflight. No interruption authorised; expanded gate b523a86 refuses restart. Recheck only at the next meaningful deployment checkpoint. -5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 73 collections (69 persistent plus 4 diagnostic/shared vocabulary), 74 SQL entities / 865 columns with no missing non-computed model properties. All 69 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff. +5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 77 collections (73 persistent plus 4 diagnostic/shared vocabulary), 78 SQL entities / 907 columns with no missing non-computed model properties. All 73 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff. 6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Eight HTTP/SQL export packets and five formats/aliases passed; expanded legacy JSON verification passed. Word structure API and Core Import SQL/source/provenance workflows now pass; next: remaining persistent project review data. 7. PENDING: remaining persistent table classification and historical fixture discovery. Unrepresented SI review/audit/provenance is persistent under its runtime contract, not an expendable cache; project-derived illustration catalogue/files also remain outside verified backup coverage. Do not claim a complete 167-table audit. 8. PENDING: finish independently safe data gaps and meaningful format round trips; record concrete limits/deferred work. No historical compatibility claim without actual fixtures. @@ -226,3 +226,11 @@ Real isolated SQL Core Import builds now cover two chapters/three scenes, canoni Reproduced same-project restore failure against retained Core Import build-map foreign keys. Migration 220 and backup models now carry all four build/map sets, retain completed history in place, remap canonical IDs/ownership on copy and assign new preview identities. Copies never activate Word bindings; unfinished operations become cancelled history with a preview warning. Older snapshots missing existing build history and restores during unfinished marker operations are refused before mutation. Combined matrix passed: 73 serialized data collections, all 69 persistent collections populated; SQL projection 1,051 values across 72 populated entities; copy 1,011 values; in-place 1,015 values. Schema census: 74 entities / 865 columns / zero missing non-computed model properties. Evidence: `/tmp/plotdirector-phase2-core-transfer-before.log`, `core-transfer-after.log`, `transfer-core-matrix.log`, `core-guards.log` (all prefixed `/tmp/plotdirector-phase2-`). Solution build zero warnings/errors; full 405-check harness passed before the added refusal guards. Development unchanged; migration 220 applied only to the isolated synthetic database. + +## Scene suggestion history and statistics — 4 November + +Populated all three scene suggestion tables and reproduced both omissions from backup and an in-place restore failure against retained scene foreign keys. These are retained author review records, including Pending, Accepted, Rejected and Dismissed, not expendable detection caches. Migration 221 adds their full projections, restored identities, canonical references, review timestamps/reasons and imported actor remapping. Stored scene dialogue/prose word and paragraph statistics are also preserved exactly. An older snapshot missing any existing suggestion table is refused before mutation (all three independently tested). + +Real isolated SQL matrix passed: 77 serialized collections, all 73 persistent collections populated, source 1,192 stored values across 76 populated entities; copy 1,152 and in-place 1,156 values. Schema census 78 entities / 907 columns / zero missing non-computed model properties. Full solution build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-scene-review-before.log` (restore failure), `scene-review-projection-before.log` (explicit missing collection), `scene-review-after.log`, `scene-review-guards.log`, `census-scene-review.log` (each with the same `/tmp/plotdirector-phase2-` prefix). Still no Development writes/deployment. SI candidate JSON/audit graph and illustration catalogue/files remain outside the verified portable graph; no full 167-table coverage claim. + +Scene review checkpoint: full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-scene-review.log`). Migration 221 and all three old-snapshot refusal cases passed in the synthetic database only. diff --git a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql index 252fbc46..1ac0f3bb 100644 --- a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql +++ b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql @@ -96,3 +96,11 @@ SET @completedBuild=SCOPE_IDENTITY(); INSERT dbo.OnboardingManuscriptBuildChapterMap(OnboardingManuscriptBuildID,TemporaryChapterKey,ChapterID) VALUES(@completedBuild,N'fixture-chapter-Ω',@chapter); INSERT dbo.OnboardingManuscriptBuildSceneMap(OnboardingManuscriptBuildID,TemporarySceneKey,SceneID) VALUES(@completedBuild,N'fixture-scene-雨',@scene),(@completedBuild,N'fixture-scene-雪',@secondScene); INSERT dbo.OnboardingManuscriptBuildCharacterMap(OnboardingManuscriptBuildID,TemporaryCharacterKey,CharacterID,Created) VALUES(@completedBuild,N'fixture-narrator-Ω',@character,1); + +INSERT dbo.SceneAssetSuggestions(SceneID,AssetID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) VALUES(@scene,@asset,N'Accepted',N'Medium',N'Author accepted asset 雨',@user,@user,'2026-10-02'); +INSERT dbo.SceneCharacterSuggestions(SceneID,CharacterID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) VALUES(@scene,@character,N'Rejected',N'Low',N'Author rejected identity Ω',@user,@user,'2026-10-03'); +INSERT dbo.SceneLocationSuggestions(SceneID,LocationID,Status,Confidence,Reason,CreatedByUserID) VALUES(@scene,@location,N'Pending',N'High',N'Awaiting author café',@user); +INSERT dbo.SceneTextStatistics(SceneID,TotalWordCount,DialogueWordCount,ProseWordCount,TotalParagraphCount,DialogueParagraphCount,ProseParagraphCount) VALUES(@scene,1234,234,1000,8,2,6); +INSERT dbo.SceneAssetSuggestions(SceneID,AssetID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@asset,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x WHERE x.SceneID=@scene AND x.AssetID=@asset AND x.Status=v.Status); +INSERT dbo.SceneCharacterSuggestions(SceneID,CharacterID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@character,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x WHERE x.SceneID=@scene AND x.CharacterID=@character AND x.Status=v.Status); +INSERT dbo.SceneLocationSuggestions(SceneID,LocationID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@location,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x WHERE x.SceneID=@scene AND x.LocationID=@location AND x.Status=v.Status); diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs index 025741b2..fb29dcee 100644 --- a/PlotLine.Tests/ProjectTransferDatabaseTests.cs +++ b/PlotLine.Tests/ProjectTransferDatabaseTests.cs @@ -43,7 +43,7 @@ internal static class ProjectTransferDatabaseTests } if(applyMigrations) { - foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql"}) + foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql"}) foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(file), @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase)) if(!string.IsNullOrWhiteSpace(batch)) await db.ExecuteAsync(batch,commandTimeout:180); Console.WriteLine("Applied required migrations to the verified synthetic database only."); @@ -156,6 +156,9 @@ internal static class ProjectTransferDatabaseTests await db.ExecuteAsync("UPDATE dbo.SceneAttachments SET FilePath=@attachment WHERE SceneID=@scene;INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,FilePath) SELECT @scene,MIN(SceneAttachmentTypeID),N'Empty text attachment',@emptyAttachment FROM dbo.SceneAttachmentTypes",new{scene,attachment,emptyAttachment}); var before=(await backups.GetProjectBackupAsync(project,user))!; await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported."); + using(var encoded=JsonDocument.Parse(JsonSerializer.Serialize(before))) + foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics"}) + Check(encoded.RootElement.GetProperty("Data").TryGetProperty(required,out var rows) && rows.GetArrayLength()>0,"Backup must retain populated scene review/statistics set: "+required); await VerifyStoredProjectionAsync(db,before); Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").Summary=="“Hello”—雪 🖋","Core Unicode export content."); if(coreOnly) @@ -306,6 +309,14 @@ internal static class ProjectTransferDatabaseTests var pointService=new ProjectRestorePointService(new ProjectRepository(factory),exportService,pointRepository,NullLogger.Instance); var restoreService=new ProjectRestoreService(pointRepository,pointService,NullLogger.Instance,assetFiles); var savedPoint=(await pointService.CreateManualAsync(project,"Synthetic baseline","Round-trip fixture"))!; + foreach(var omitted in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions"}) + { + var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!; + older["Data"]!.AsObject().Remove(omitted); + try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing suggestion history."); } + catch(SqlException error) when(error.Number==51009) { } + Check((await backups.GetProjectBackupAsync(project,user))!.Data.SceneAssetSuggestions.Count==4,"Older snapshot refusal retains review history."); + } await db.ExecuteAsync("UPDATE dbo.SceneManuscriptSources SET SourceText=N'Changed source' WHERE SceneID=@scene;UPDATE dbo.WritingPlans SET PlanName=N'Changed plan' WHERE WritingPlanID=@plan;UPDATE dbo.CharacterAliases SET Alias=N'Changed alias' WHERE CharacterID=@character;",new{scene,plan,character}); var restored=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID); Check(restored.Succeeded && restored.SafetyBackup is not null,"Actual restore workflow creates a safety backup and succeeds."); @@ -345,7 +356,7 @@ internal static class ProjectTransferDatabaseTests coverage.Add($"{property.Name},{Count(before)},{Count(after)},{Count(sameProject)},{(diagnostic?"Diagnostic/shared vocabulary; excluded from portable restoration comparison":"Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present")}"); } await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv",coverage); - Console.WriteLine("PASS 69 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending."); + Console.WriteLine("PASS 73 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending."); } private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser) { @@ -389,7 +400,7 @@ internal static class ProjectTransferDatabaseTests if(collection.Name=="ManuscriptDocuments" && column=="DocumentGuid") {Check(!Equals(expected,actual),"Copy document GUID must change");continue;} if(collection.Name=="ManuscriptDocuments" && column=="IsActive" || collection.Name is "Scenes" or "Chapters" && column=="IsLinkedToManuscript")expected=false; if(collection.Name is "Scenes" or "Chapters" && column=="LinkedUtc" || collection.Name=="Scenes" && column=="ImportRunID")expected=null; - if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" && column=="UserID")expected=importingUser.Value; + if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || column=="ReviewedByUserID" && expected is not null || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" && column=="UserID")expected=importingUser.Value; if(collection.Name=="ThreadEvents" && column=="SourceKey" && expected is not null)expected=$"backup:{restored.Project.ProjectID}:{Read(collection.After[index],"ThreadEventID")}"; if(collection.Name=="ThreadEvents" && column=="SourceReferenceID")expected=null; if(collection.Name=="StoryMaps" && column=="ReferenceJson")continue; // Exact placement/image identity asserted separately. diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index 5eb6eeec..10ea1567 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -109,6 +109,11 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact data.OnboardingManuscriptBuildChapterMap = (await state.ReadAsync()).ToList(); data.OnboardingManuscriptBuildSceneMap = (await state.ReadAsync()).ToList(); data.OnboardingManuscriptBuildCharacterMap = (await state.ReadAsync()).ToList(); + data.SceneAssetSuggestions = (await state.ReadAsync()).ToList(); + data.SceneCharacterSuggestions = (await state.ReadAsync()).ToList(); + data.SceneLocationSuggestions = (await state.ReadAsync()).ToList(); + data.SceneTextStatistics = (await state.ReadAsync()).ToList(); + } @@ -148,6 +153,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact ProjectId = projectId, IncludedEntitySets = [ + nameof(data.SceneAssetSuggestions), + nameof(data.SceneCharacterSuggestions), + nameof(data.SceneLocationSuggestions), + nameof(data.SceneTextStatistics), nameof(data.OnboardingManuscriptBuilds), nameof(data.OnboardingManuscriptBuildChapterMap), nameof(data.OnboardingManuscriptBuildSceneMap), diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 71374618..eae01543 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -14,6 +14,11 @@ public sealed class ProjectBackupExport public sealed class ProjectBackupData { + public IReadOnlyList SceneAssetSuggestions { get; set; } = []; + public IReadOnlyList SceneCharacterSuggestions { get; set; } = []; + public IReadOnlyList SceneLocationSuggestions { get; set; } = []; + public IReadOnlyList SceneTextStatistics { get; set; } = []; + public IReadOnlyList OnboardingManuscriptBuilds { get; set; } = []; public IReadOnlyList OnboardingManuscriptBuildChapterMap { get; set; } = []; public IReadOnlyList OnboardingManuscriptBuildSceneMap { get; set; } = []; @@ -309,3 +314,61 @@ public sealed class ProjectBackupOnboardingManuscriptBuildCharacterMap public int CharacterID { get; set; } public bool Created { get; set; } } + +public sealed class ProjectBackupSceneAssetSuggestions +{ + public int SceneAssetSuggestionID { get; set; } + public int SceneID { get; set; } + public int AssetID { get; set; } + public string SuggestionSource { get; set; } = ""; + public DateTime DetectedUtc { get; set; } + public string Status { get; set; } = ""; + public string Confidence { get; set; } = ""; + public string? Reason { get; set; } + public int CreatedByUserID { get; set; } + public int? ReviewedByUserID { get; set; } + public DateTime? ReviewedUtc { get; set; } +} + +public sealed class ProjectBackupSceneCharacterSuggestions +{ + public int SceneCharacterSuggestionID { get; set; } + public int SceneID { get; set; } + public int CharacterID { get; set; } + public string SuggestionSource { get; set; } = ""; + public DateTime DetectedUtc { get; set; } + public string Status { get; set; } = ""; + public string Confidence { get; set; } = ""; + public string? Reason { get; set; } + public int CreatedByUserID { get; set; } + public int? ReviewedByUserID { get; set; } + public DateTime? ReviewedUtc { get; set; } +} + +public sealed class ProjectBackupSceneLocationSuggestions +{ + public int SceneLocationSuggestionID { get; set; } + public int SceneID { get; set; } + public int LocationID { get; set; } + public string SuggestionSource { get; set; } = ""; + public DateTime DetectedUtc { get; set; } + public string Status { get; set; } = ""; + public string Confidence { get; set; } = ""; + public string? Reason { get; set; } + public int CreatedByUserID { get; set; } + public int? ReviewedByUserID { get; set; } + public DateTime? ReviewedUtc { get; set; } +} + +public sealed class ProjectBackupSceneTextStatistics +{ + public int SceneID { get; set; } + public int TotalWordCount { get; set; } + public int DialogueWordCount { get; set; } + public int ProseWordCount { get; set; } + public int TotalParagraphCount { get; set; } + public int DialogueParagraphCount { get; set; } + public int ProseParagraphCount { get; set; } + public DateTime CalculatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } +} diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index dec14cf2..16062f31 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -839,7 +839,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService private static readonly string[] ProjectBackupIdentityTables = [ "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps", - "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", + "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", "SceneOutcomes", "PlotLines", "PlotThreads", "ThreadEvents", "AssetStates", "StoryAssets", "AssetEvents", "AssetDependencies", "AssetCustodyEvents", "AssetCustodyEventCharacters", "Characters", "SceneCharacters", "CharacterAttributeTypes", "CharacterAttributeEvents", "CharacterKnowledge", "CharacterRelationships", @@ -1524,6 +1524,31 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService note.FromSceneID = ExistingOrNew("Scenes", note.FromSceneID); note.ToSceneID = ExistingOrNew("Scenes", note.ToSceneID); } + foreach(var row in backup.Data.SceneAssetSuggestions) + { + row.SceneAssetSuggestionID=NewId("SceneAssetSuggestions",row.SceneAssetSuggestionID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + row.AssetID=ExistingOrNew("StoryAssets",row.AssetID); + if(row.ReviewedByUserID.HasValue) row.ReviewedByUserID=importingUserId; + } + foreach(var row in backup.Data.SceneCharacterSuggestions) + { + row.SceneCharacterSuggestionID=NewId("SceneCharacterSuggestions",row.SceneCharacterSuggestionID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + row.CharacterID=ExistingOrNew("Characters",row.CharacterID); + if(row.ReviewedByUserID.HasValue) row.ReviewedByUserID=importingUserId; + } + foreach(var row in backup.Data.SceneLocationSuggestions) + { + row.SceneLocationSuggestionID=NewId("SceneLocationSuggestions",row.SceneLocationSuggestionID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + row.LocationID=ExistingOrNew("Locations",row.LocationID); + if(row.ReviewedByUserID.HasValue) row.ReviewedByUserID=importingUserId; + } + foreach(var row in backup.Data.SceneTextStatistics) + { + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + } foreach(var build in backup.Data.OnboardingManuscriptBuilds) { build.OnboardingManuscriptBuildID=NewId("OnboardingManuscriptBuilds",build.OnboardingManuscriptBuildID); diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 62cfa455..f7976665 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -8,6 +8,10 @@ internal static class ProjectBackupGraphValidation private sealed record Link(string Column, string TargetCollection, string TargetColumn); private sealed record Entity(string Collection, string? Identity, params Link[] Links); private static readonly Entity[] Entities = [ + new("SceneAssetSuggestions","SceneAssetSuggestionID",new Link("SceneID","Scenes","SceneID"),new Link("AssetID","StoryAssets","StoryAssetID")), + new("SceneCharacterSuggestions","SceneCharacterSuggestionID",new Link("CharacterID","Characters","CharacterID"),new Link("SceneID","Scenes","SceneID")), + new("SceneLocationSuggestions","SceneLocationSuggestionID",new Link("LocationID","Locations","LocationID"),new Link("SceneID","Scenes","SceneID")), + new("SceneTextStatistics",null,new Link("SceneID","Scenes","SceneID")), new("OnboardingManuscriptBuilds","OnboardingManuscriptBuildID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ManuscriptDocumentID","ManuscriptDocuments","ManuscriptDocumentID")), new("OnboardingManuscriptBuildChapterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("ChapterID","Chapters","ChapterID")), new("OnboardingManuscriptBuildSceneMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("SceneID","Scenes","SceneID")), diff --git a/PlotLine/Sql/221_ProjectBackupSceneReviewState.sql b/PlotLine/Sql/221_ProjectBackupSceneReviewState.sql new file mode 100644 index 00000000..0fcf2f5c --- /dev/null +++ b/PlotLine/Sql/221_ProjectBackupSceneReviewState.sql @@ -0,0 +1,374 @@ +-- Version 1.3 additive scene suggestion decisions and stored text statistics. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.ProjectBackup_PersistentState_List @ProjectID int +AS +BEGIN + SET NOCOUNT ON; + SELECT * FROM dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID ORDER BY ManuscriptDocumentID; + SELECT * FROM dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID ORDER BY SceneID; + SELECT * FROM dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID ORDER BY ChapterID; + SELECT * FROM dbo.WritingPlans WHERE ProjectID=@ProjectID ORDER BY WritingPlanID; + SELECT i.* FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID ORDER BY i.WritingScheduleItemID; + SELECT a.* FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY a.CharacterAliasID; + SELECT a.* FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID ORDER BY a.AssetAliasID; + SELECT a.* FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID ORDER BY a.LocationAliasID; + SELECT * FROM dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID ORDER BY AuthorPlotSeedID; + SELECT * FROM dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID ORDER BY ContinuityWarningAcknowledgementID; + SELECT x.* FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID ORDER BY x.PlotEventID,x.PlotLineID; + SELECT x.* FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneAssetID; + SELECT x.* FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneLocationID; + + SELECT * FROM dbo.CharacterImages WHERE ProjectID=@ProjectID ORDER BY CharacterImageID; + SELECT * FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID ORDER BY OnboardingManuscriptBuildID; + SELECT m.* FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryChapterKey; + SELECT m.* FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporarySceneKey; + SELECT m.* FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryCharacterKey; + + SELECT x.* FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneAssetSuggestionID; + SELECT x.* FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneCharacterSuggestionID; + SELECT x.* FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneLocationSuggestionID; + SELECT x.* FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson + @ProjectID int, + @SourceRestorePointID int = NULL, + @SafetyRestorePointID int = NULL, + @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF ISNULL(ISJSON(@JsonData), 0) <> 1 + THROW 51001, 'Restore JSON is invalid.', 1; + + IF ISNULL(JSON_VALUE(@JsonData, '$.Format'), N'') <> N'PlotDirector.ProjectBackup' + THROW 51002, 'Restore JSON format is not recognised.', 1; + + IF ISNULL(JSON_VALUE(@JsonData, '$.FormatVersion'), N'') NOT IN (N'1.0', N'1.1', N'1.2', N'1.3') + THROW 51003, 'Restore JSON format version is not supported.', 1; + + IF ISNULL(@ProjectID,0)<=0 OR ISNULL(TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')),-1) <> @ProjectID + THROW 51004, 'Restore point does not belong to this project.', 1; + + DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY); + INSERT INTO @RestoreTables (TableName) + VALUES + (N'SceneAssetSuggestions'), + (N'SceneCharacterSuggestions'), + (N'SceneLocationSuggestions'), + (N'SceneTextStatistics'), + (N'OnboardingManuscriptBuilds'), + (N'OnboardingManuscriptBuildChapterMap'), + (N'OnboardingManuscriptBuildSceneMap'), + (N'OnboardingManuscriptBuildCharacterMap'), + (N'CharacterImages'), (N'WordCompanionSceneAssets'), (N'WordCompanionSceneLocations'), (N'ManuscriptDocuments'), (N'SceneManuscriptSources'), (N'ManuscriptStructuralChapterSources'), (N'WritingPlans'), (N'WritingScheduleItems'), (N'CharacterAliases'), (N'AssetAliases'), (N'LocationAliases'), (N'AuthorPlotSeeds'), (N'ContinuityWarningAcknowledgements'), (N'PlotEventTargetPlotLines'), + (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'), + (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'), + (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'), + (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'), + (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'), + (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'), + (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'), + (N'MapReferenceImages'), (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'), + (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'), + (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'), + (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'), + (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'), + (N'ScenarioWarnings'); + + IF JSON_VALUE(@JsonData,'$.FormatVersion')<>N'1.3' AND EXISTS(SELECT 1 FROM dbo.CharacterImages WHERE ProjectID=@ProjectID) + THROW 51006,'This older restore point does not include the existing character gallery. Restore was aborted without changing it.',1; + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID) + AND JSON_QUERY(@JsonData,'$.Data.OnboardingManuscriptBuilds') IS NULL + THROW 51007,'This older restore point does not include existing Core Import build history. Restore was aborted without changing it.',1; + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID + AND (Status NOT IN (N'Built',N'Complete',N'Completed',N'Failed',N'Cancelled') + OR (Status=N'Built' AND ISNULL(MarkerStatus,N'') NOT IN (N'UserConfirmedSave',N'Completed',N'Complete')))) + THROW 51008,'Core Import is unfinished for this project. Complete or cancel it before restoring.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneAssetSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneCharacterSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneLocationSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + BEGIN TRANSACTION; + DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0); + + + DECLARE @TableName sysname; + DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN DisableCursor; + FETCH NEXT FROM DisableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;'; + EXEC (@DisableSql); + FETCH NEXT FROM DisableCursor INTO @TableName; + END + CLOSE DisableCursor; + DEALLOCATE DisableCursor; + + DELETE x FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID; + DELETE FROM dbo.CharacterImages WHERE ProjectID=@ProjectID; + DELETE x FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE i FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID; + DELETE dbo.WritingPlans WHERE ProjectID=@ProjectID; + DELETE dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID; + DELETE dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID; + DELETE a FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID; + DELETE a FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID; + DELETE a FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID; + DELETE x FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID; + DELETE dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID; + DELETE dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID; + DELETE dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID; + + DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; + DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID; + DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID; + DELETE dbo.MapReferenceImages WHERE ProjectID=@ProjectID; + UPDATE dbo.UserFile SET IsDeleted=1,DeletedDateUTC=SYSUTCDATETIME() WHERE ProjectID=@ProjectID AND EntityType=N'MapReferenceImage'; + + DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID; + + DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + + DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo + INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE b.ProjectID = @ProjectID; + + DELETE sd FROM dbo.SceneDependencies sd + LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID + LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID; + + DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID; + DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID; + DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID; + + DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID; + + DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID; + + DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID; + DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID; + + DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID; + + DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID; + + DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.Books WHERE ProjectID = @ProjectID; + DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID; + + UPDATE p + SET ProjectName = src.ProjectName, + Description = src.Description, + CreatedDate = src.CreatedDate, + UpdatedDate = SYSUTCDATETIME(), + CreatedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedByUserID ELSE p.CreatedByUserID END, + ModifiedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedByUserID ELSE p.ModifiedByUserID END, + CreatedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedDateUTC ELSE p.CreatedDateUTC END, + ModifiedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedDateUTC ELSE p.ModifiedDateUTC END, + IsArchived = src.IsArchived, + ArchivedDate = src.ArchivedDate, + ArchivedReason = src.ArchivedReason + FROM dbo.Projects p + CROSS APPLY OPENJSON(@JsonData, '$.Project') + WITH + ( + ProjectID int '$.ProjectID', + ProjectName nvarchar(200) '$.ProjectName', + Description nvarchar(max) '$.Description', + CreatedDate datetime2 '$.CreatedDate', + CreatedByUserID int '$.CreatedByUserID', + ModifiedByUserID int '$.ModifiedByUserID', + CreatedDateUTC datetime2 '$.CreatedDateUTC', + ModifiedDateUTC datetime2 '$.ModifiedDateUTC', + IsArchived bit '$.IsArchived', + ArchivedDate datetime2 '$.ArchivedDate', + ArchivedReason nvarchar(1000) '$.ArchivedReason' + ) src + WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterImages',N'$.Data.CharacterImages',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0; + + -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography. + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ProjectID int '$.ProjectID') WHERE ProjectID IS NULL OR ProjectID<>@ProjectID) THROW 51005,'Reference images cross project boundaries.',1; + INSERT dbo.MapReferenceImages(ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,ImageData) + SELECT x.ImageID,@ProjectID,x.OriginalFileName,x.ContentType,x.Width,x.Height,CAST(N'' AS xml).value('xs:base64Binary(sql:column("x.ImageData"))','varbinary(max)') + FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ImageID uniqueidentifier '$.ImageID',OriginalFileName nvarchar(200) '$.OriginalFileName',ContentType nvarchar(40) '$.ContentType',Width int '$.Width',Height int '$.Height',ImageData nvarchar(max) '$.ImageData') x; + DECLARE @ImageOwner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID); + INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath) + SELECT @ImageOwner,@ProjectID,N'MapReferenceImage',@ProjectID,CONVERT(nvarchar(36),ImageID)+N'.webp',OriginalFileName,ContentType,FileSizeBytes,N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),ImageID) FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + THROW 51005,'Map backup contains features outside this project.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID) + OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID) + THROW 51005,'Map hierarchy or Location links cross projects.',1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n + WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID) + OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID) + OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@ProjectID AND s.SceneID IN(n.FromSceneID,n.ToSceneID))<>2 + OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path'))) + THROW 51005,'Journey annotations cross project or map boundaries.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND (ISJSON(m.AppearanceJson)<>1 OR ISJSON(m.ReferenceJson)<>1 OR (JSON_VALUE(m.ReferenceJson,'$.imageID') IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages i WHERE i.ProjectID=@ProjectID AND i.ImageID=TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.ReferenceJson,'$.imageID')))))) THROW 51005,'Invalid map appearance or foreign reference image.',1; + UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptDocuments',N'$.Data.ManuscriptDocuments',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneManuscriptSources',N'$.Data.SceneManuscriptSources',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptStructuralChapterSources',N'$.Data.ManuscriptStructuralChapterSources',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'WritingPlans',N'$.Data.WritingPlans',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'WritingScheduleItems',N'$.Data.WritingScheduleItems',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAliases',N'$.Data.CharacterAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetAliases',N'$.Data.AssetAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationAliases',N'$.Data.LocationAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AuthorPlotSeeds',N'$.Data.AuthorPlotSeeds',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarningAcknowledgements',N'$.Data.ContinuityWarningAcknowledgements',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotEventTargetPlotLines',N'$.Data.PlotEventTargetPlotLines',@JsonData,@ProjectID,0; + + EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneAssets',N'$.Data.WordCompanionSceneAssets',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneLocations',N'$.Data.WordCompanionSceneLocations',@JsonData,@ProjectID,0; + + INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath) + SELECT @ImageOwner,@ProjectID,x.EntityType,x.EntityID,x.RestoredFileName,x.OriginalFileName,x.ContentType,x.FileSizeBytes,x.RestoredPath + FROM OPENJSON(@JsonData,'$.Files') WITH( + EntityType nvarchar(80) '$.EntityType',EntityID int '$.EntityID',RestoredFileName nvarchar(260) '$.RestoredFileName', + OriginalFileName nvarchar(260) '$.OriginalFileName',ContentType nvarchar(200) '$.ContentType', + FileSizeBytes bigint '$.FileSizeBytes',RestoredPath nvarchar(1000) '$.RestoredPath') x + WHERE x.RestoredPath LIKE N'/uploads/%'; + + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuilds',N'$.Data.OnboardingManuscriptBuilds',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildChapterMap',N'$.Data.OnboardingManuscriptBuildChapterMap',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildSceneMap',N'$.Data.OnboardingManuscriptBuildSceneMap',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildCharacterMap',N'$.Data.OnboardingManuscriptBuildCharacterMap',@JsonData,@ProjectID,0; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetSuggestions',N'$.Data.SceneAssetSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacterSuggestions',N'$.Data.SceneCharacterSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneLocationSuggestions',N'$.Data.SceneLocationSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneTextStatistics',N'$.Data.SceneTextStatistics',@JsonData,@ProjectID,0; + + DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN EnableCursor; + FETCH NEXT FROM EnableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;'; + EXEC (@EnableSql); + FETCH NEXT FROM EnableCursor INTO @TableName; + END + CLOSE EnableCursor; + DEALLOCATE EnableCursor; + + IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL + BEGIN + INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes) + VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.'); + END; + + COMMIT TRANSACTION; +END; +GO