From 6ae371558bc29fbbaf0461f1c51f6600ee8f366b Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 4 Nov 2026 00:42:06 +0000 Subject: [PATCH] Verify stored backup values and preserve timeline and event identities --- .../2026-11-03-phase2-data-coverage.csv | 124 ++-- .../2026-11-03-phase2-roundtrip-coverage.csv | 67 ++ Docs/Sprints/2026-11-03-phase2.md | 12 + .../Fixtures/ProjectTransferPlanning.sql | 88 +++ .../ProjectTransferDatabaseTests.cs | 149 +++- PlotLine/Services/ImportServices.cs | 6 + .../Services/ProjectBackupGraphValidation.cs | 2 +- .../Services/ProjectBackupTimelineState.cs | 59 ++ PlotLine/Services/ProjectRestoreService.cs | 2 - .../215_ProjectBackupMapStoredMetadata.sql | 644 ++++++++++++++++++ 10 files changed, 1077 insertions(+), 76 deletions(-) create mode 100644 Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv create mode 100644 PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql create mode 100644 PlotLine/Services/ProjectBackupTimelineState.cs create mode 100644 PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql diff --git a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv index 07f8818a..9370bd1d 100644 --- a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv @@ -1,35 +1,35 @@ Table,ProjectOwnershipEvidence,BackupCollection,Classification,RestoreVerified,AssetsVerified AppUser,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending -AssetAliases,ProjectID or FK descendant,AssetAliases,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -AssetCustodyEventCharacters,ProjectID or FK descendant,AssetCustodyCharacters,Serialized; field completeness unverified,Pending,Pending -AssetCustodyEvents,ProjectID or FK descendant,AssetCustodyEvents,Serialized; field completeness unverified,Pending,Pending +AssetAliases,ProjectID or FK descendant,AssetAliases,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 +AssetCustodyEventCharacters,ProjectID or FK descendant,AssetCustodyCharacters,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 +AssetCustodyEvents,ProjectID or FK descendant,AssetCustodyEvents,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 AssetCustodyEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -AssetDependencies,ProjectID or FK descendant,AssetDependencies,Serialized; field completeness unverified,Pending,Pending +AssetDependencies,ProjectID or FK descendant,AssetDependencies,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 AssetDependencyTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -AssetEvents,ProjectID or FK descendant,AssetEvents,Serialized; field completeness unverified,Pending,Pending +AssetEvents,ProjectID or FK descendant,AssetEvents,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 AssetEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending AssetKinds,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -AssetStates,ProjectID or FK descendant,AssetStates,Serialized; field completeness unverified,Pending,Pending -AuthorPlotSeeds,ProjectID or FK descendant,AuthorPlotSeeds,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -Books,ProjectID or FK descendant,Books,Serialized; era/locale omission repaired by migration 213 (isolated only),Unicode title and era/locale initial import comparison passed; other fields pending,Pending -ChapterGoals,ProjectID or FK descendant,ChapterGoals,Serialized; field completeness unverified,Pending,Pending +AssetStates,ProjectID or FK descendant,AssetStates,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 +AuthorPlotSeeds,ProjectID or FK descendant,AuthorPlotSeeds,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 +Books,ProjectID or FK descendant,Books,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 +ChapterGoals,ProjectID or FK descendant,ChapterGoals,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 ChapterPurposeTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -Chapters,ProjectID or FK descendant,Chapters,Serialized; field completeness unverified,Pending,Pending -CharacterAliases,ProjectID or FK descendant,CharacterAliases,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -CharacterAttributeEvents,ProjectID or FK descendant,CharacterAttributeEvents,Serialized; field completeness unverified,Pending,Pending -CharacterAttributeTypes,ProjectID or FK descendant,CharacterAttributeTypes,Serialized; field completeness unverified,Pending,Pending +Chapters,ProjectID or FK descendant,Chapters,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 +CharacterAliases,ProjectID or FK descendant,CharacterAliases,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 +CharacterAttributeEvents,ProjectID or FK descendant,CharacterAttributeEvents,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 +CharacterAttributeTypes,ProjectID or FK descendant,CharacterAttributeTypes,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 CharacterEnrichmentEvidence,ProjectID or FK descendant,,Pending classification,Pending,Pending CharacterEnrichmentRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending CharacterImages,ProjectID or FK descendant,,Pending classification,Pending,Pending CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,,Pending classification,Pending,Pending CharacterIntelligenceProfiles,ProjectID or FK descendant,,Pending classification,Pending,Pending -CharacterKnowledge,ProjectID or FK descendant,CharacterKnowledge,Serialized; field completeness unverified,Pending,Pending -CharacterRelationships,ProjectID or FK descendant,CharacterRelationships,Serialized; field completeness unverified,Pending,Pending +CharacterKnowledge,ProjectID or FK descendant,CharacterKnowledge,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 +CharacterRelationships,ProjectID or FK descendant,CharacterRelationships,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 CharacterRoleInSceneTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -Characters,ProjectID or FK descendant,Characters,Serialized; field completeness unverified,Pending,Pending +Characters,ProjectID or FK descendant,Characters,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 CharacterSexValues,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -ContinuityWarningAcknowledgements,ProjectID or FK descendant,ContinuityWarningAcknowledgements,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -ContinuityWarnings,ProjectID or FK descendant,ContinuityWarnings,Serialized; field completeness unverified,Pending,Pending +ContinuityWarningAcknowledgements,ProjectID or FK descendant,ContinuityWarningAcknowledgements,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 +ContinuityWarnings,ProjectID or FK descendant,ContinuityWarnings,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 CoreImportBasicLocationCandidates,ProjectID or FK descendant,,Pending classification,Pending,Pending CoreImportBasicLocationEvidence,ProjectID or FK descendant,,Pending classification,Pending,Pending CoreImportBasicLocationReviews,ProjectID or FK descendant,,Pending classification,Pending,Pending @@ -38,26 +38,26 @@ DurationUnits,Global/user/independent,,Reference/user/system; scope review pendi EmailQueue,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending FeatureRequestMessages,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending FeatureRequests,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -FloorPlanBlocks,ProjectID or FK descendant,FloorPlanBlocks,Serialized; field completeness unverified,Pending,Pending -FloorPlanFloors,ProjectID or FK descendant,FloorPlanFloors,Serialized; field completeness unverified,Pending,Pending -FloorPlans,ProjectID or FK descendant,FloorPlans,Serialized; field completeness unverified,Pending,Pending -FloorPlanTransitions,ProjectID or FK descendant,FloorPlanTransitions,Serialized; field completeness unverified,Pending,Pending +FloorPlanBlocks,ProjectID or FK descendant,FloorPlanBlocks,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 +FloorPlanFloors,ProjectID or FK descendant,FloorPlanFloors,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 +FloorPlans,ProjectID or FK descendant,FloorPlans,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 +FloorPlanTransitions,ProjectID or FK descendant,FloorPlanTransitions,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 GenreMetricPresetMetrics,ProjectID or FK descendant,GenreMetricPresetMetrics,Serialized; field completeness unverified,Pending,Pending GenreMetricPresets,Global/user/independent,GenreMetricPresets,Serialized; field completeness unverified,Pending,Pending GivenNames,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending IllustrationLibraryItems,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending KnowledgeStates,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -LocationAliases,ProjectID or FK descendant,LocationAliases,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -LocationRelationships,ProjectID or FK descendant,LocationRelationships,Serialized; field completeness unverified,Pending,Pending +LocationAliases,ProjectID or FK descendant,LocationAliases,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 +LocationRelationships,ProjectID or FK descendant,LocationRelationships,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 LocationRelationshipTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -Locations,ProjectID or FK descendant,Locations,Serialized; field completeness unverified,Pending,Pending +Locations,ProjectID or FK descendant,Locations,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 LocationTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -ManuscriptDocuments,ProjectID or FK descendant,ManuscriptDocuments,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -ManuscriptStructuralChapterSources,ProjectID or FK descendant,ManuscriptStructuralChapterSources,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -MapFeatures,ProjectID or FK descendant,MapFeatures,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending -MapJourneyNotes,ProjectID or FK descendant,MapJourneyNotes,Serialized; field completeness unverified,Pending,Pending -MapReferenceImages,ProjectID or FK descendant,MapReferenceImages,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Exact normalized bytes and remapped image placement passed -MapRelationships,ProjectID or FK descendant,MapRelationships,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending +ManuscriptDocuments,ProjectID or FK descendant,ManuscriptDocuments,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 +ManuscriptStructuralChapterSources,ProjectID or FK descendant,ManuscriptStructuralChapterSources,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 +MapFeatures,ProjectID or FK descendant,MapFeatures,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 +MapJourneyNotes,ProjectID or FK descendant,MapJourneyNotes,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 +MapReferenceImages,ProjectID or FK descendant,MapReferenceImages,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,Exact normalized bytes and remapped image placement passed +MapRelationships,ProjectID or FK descendant,MapRelationships,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 NameLocales,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending NameReferenceImports,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending NameRelationships,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending @@ -66,53 +66,53 @@ OnboardingManuscriptBuildChapterMap,ProjectID or FK descendant,,Pending classifi OnboardingManuscriptBuildCharacterMap,ProjectID or FK descendant,,Pending classification,Pending,Pending OnboardingManuscriptBuilds,ProjectID or FK descendant,,Pending classification,Pending,Pending OnboardingManuscriptBuildSceneMap,ProjectID or FK descendant,,Pending classification,Pending,Pending -PlotEventTargetPlotLines,ProjectID or FK descendant,PlotEventTargetPlotLines,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) +PlotEventTargetPlotLines,ProjectID or FK descendant,PlotEventTargetPlotLines,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 PlotEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending PlotImportance,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -PlotLines,ProjectID or FK descendant,PlotLines,Serialized; field completeness unverified,Pending,Pending +PlotLines,ProjectID or FK descendant,PlotLines,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 PlotLineTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -PlotThreads,ProjectID or FK descendant,PlotThreads,Serialized; field completeness unverified,Pending,Pending +PlotThreads,ProjectID or FK descendant,PlotThreads,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 PresenceTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending ProjectActivity,ProjectID or FK descendant,,Pending classification,Pending,Pending ProjectInvitation,ProjectID or FK descendant,,Pending classification,Pending,Pending ProjectRestoreHistory,ProjectID or FK descendant,,Pending classification,Pending,Pending ProjectRestorePoints,ProjectID or FK descendant,,Pending classification,Pending,Pending Projects,ProjectID or FK descendant,Project,Serialized; field completeness unverified,Pending,Pending -ProjectTimelineMetricSettings,ProjectID or FK descendant,TimelineMetricSettings,Serialized; field completeness unverified,Pending,Pending -ProjectTimelineSettings,ProjectID or FK descendant,TimelineSettings,Serialized; field completeness unverified,Pending,Pending +ProjectTimelineMetricSettings,ProjectID or FK descendant,TimelineMetricSettings,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 +ProjectTimelineSettings,ProjectID or FK descendant,TimelineSettings,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 ProjectUserAccess,ProjectID or FK descendant,ProjectAccess,Serialized; field completeness unverified,Pending,Pending RelationshipCategories,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -RelationshipEvents,ProjectID or FK descendant,RelationshipEvents,Serialized; field completeness unverified,Pending,Pending +RelationshipEvents,ProjectID or FK descendant,RelationshipEvents,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 RelationshipStates,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending RelationshipTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending RevisionStatuses,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -Scenarios,ProjectID or FK descendant,Scenarios,Serialized; field completeness unverified,Pending,Pending -ScenarioSceneOrder,ProjectID or FK descendant,ScenarioSceneOrder,Serialized; field completeness unverified,Pending,Pending -ScenarioValidationRuns,ProjectID or FK descendant,ScenarioValidationRuns,Serialized; field completeness unverified,Pending,Pending -ScenarioWarnings,ProjectID or FK descendant,ScenarioWarnings,Serialized; field completeness unverified,Pending,Pending -SceneAssetLocations,ProjectID or FK descendant,SceneAssetLocations,Serialized; field completeness unverified,Pending,Pending +Scenarios,ProjectID or FK descendant,Scenarios,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 +ScenarioSceneOrder,ProjectID or FK descendant,ScenarioSceneOrder,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 +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 -SceneAttachments,ProjectID or FK descendant,SceneAttachments,Serialized; field completeness unverified,Pending,Pending +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,External file bytes not covered; embedded/text/JSON values compared where populated SceneAttachmentTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -SceneCharacters,ProjectID or FK descendant,SceneCharacters,Serialized; field completeness unverified,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 -SceneChecklistItems,ProjectID or FK descendant,SceneChecklistItems,Serialized; field completeness unverified,Pending,Pending -SceneDependencies,ProjectID or FK descendant,SceneDependencies,Serialized; field completeness unverified,Pending,Pending +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; field completeness unverified,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 -SceneManuscriptSources,ProjectID or FK descendant,SceneManuscriptSources,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -SceneMetricTypes,ProjectID or FK descendant,SceneMetricTypes,Serialized; field completeness unverified,Pending,Pending -SceneMetricValues,ProjectID or FK descendant,SceneMetricValues,Serialized; field completeness unverified,Pending,Pending -SceneNotes,ProjectID or FK descendant,SceneNotes,Serialized; field completeness unverified,Pending,Pending +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 +SceneNotes,ProjectID or FK descendant,SceneNotes,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 SceneNoteTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -SceneOutcomes,ProjectID or FK descendant,SceneOutcomes,Serialized; field completeness unverified,Pending,Pending -ScenePurposes,ProjectID or FK descendant,ScenePurposes,Serialized; field completeness unverified,Pending,Pending +SceneOutcomes,ProjectID or FK descendant,SceneOutcomes,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 +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; field completeness unverified,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 -SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized; field completeness unverified,Pending,Pending -StoryAssets,ProjectID or FK descendant,StoryAssets,Serialized; field completeness unverified,Pending,Pending +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,External file bytes not covered; embedded/text/JSON values compared where populated StoryIntelligenceBookPipelines,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending StoryIntelligenceChapterResults,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryIntelligenceConsents,ProjectID or FK descendant,,Pending classification,Pending,Pending @@ -127,7 +127,7 @@ StoryIntelligenceReviewCandidateGenerations,ProjectID or FK descendant,,Persiste StoryIntelligenceReviewCandidates,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending StoryIntelligenceRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryIntelligenceSceneResults,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending -StoryMaps,ProjectID or FK descendant,StoryMaps,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending +StoryMaps,ProjectID or FK descendant,StoryMaps,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 StoryMemoryAssets,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryMemoryCharacterAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryMemoryCharacterAttributes,ProjectID or FK descendant,,Pending classification,Pending,Pending @@ -143,12 +143,12 @@ SubscriptionAdministrationAudit,Global/user/independent,,Account/billing/system SubscriptionBookSlotReservation,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending SubscriptionLevel,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending SubscriptionOverride,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending -ThreadEvents,ProjectID or FK descendant,ThreadEvents,Serialized; field completeness unverified,Pending,Pending +ThreadEvents,ProjectID or FK descendant,ThreadEvents,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 ThreadEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending ThreadStatuses,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending ThreadTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending TimeConfidences,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -TimelineViewPresets,ProjectID or FK descendant,TimelineViewPresets,Serialized; field completeness unverified,Pending,Pending +TimelineViewPresets,ProjectID or FK descendant,TimelineViewPresets,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 TimeModes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending UserEmailVerificationToken,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending UserFile,ProjectID or FK descendant,UserFiles,Serialized; field completeness unverified,Pending,Pending @@ -157,12 +157,12 @@ UserOnboardingState,ProjectID or FK descendant,,Pending classification,Pending,P UserPasswordResetToken,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending UserSubscription,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending UserTwoFactor,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -ValidationRuns,ProjectID or FK descendant,ValidationRuns,Serialized; field completeness unverified,Pending,Pending +ValidationRuns,ProjectID or FK descendant,ValidationRuns,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 WarningSeverities,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending WarningTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending WholeBookPlotSynthesisRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending WordCompanionSceneAssets,ProjectID or FK descendant,,Pending classification,Pending,Pending WordCompanionSceneLocations,ProjectID or FK descendant,,Pending classification,Pending,Pending -WritingPlans,ProjectID or FK descendant,WritingPlans,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) -WritingScheduleItems,ProjectID or FK descendant,WritingScheduleItems,Version 1.2 persisted state; initial isolated content/reference comparison passed,Import-as-new and actual same-project restore/safety/SQL rollback passed; broader all-entity matrix pending,Text/JSON state (no external file bytes) +WritingPlans,ProjectID or FK descendant,WritingPlans,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 +WritingScheduleItems,ProjectID or FK descendant,WritingScheduleItems,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 WritingSolverVersions,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending diff --git a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv new file mode 100644 index 00000000..243d3257 --- /dev/null +++ b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv @@ -0,0 +1,67 @@ +Collection,SourceRows,CopyRows,InPlaceRows,Verification +ManuscriptDocuments,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneManuscriptSources,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ManuscriptStructuralChapterSources,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +WritingPlans,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +WritingScheduleItems,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +CharacterAliases,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetAliases,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +LocationAliases,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AuthorPlotSeeds,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ContinuityWarningAcknowledgements,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +PlotEventTargetPlotLines,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +MapReferenceImages,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +MapJourneyNotes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +StoryMaps,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +MapFeatures,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +MapRelationships,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Books,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Chapters,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Scenes,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +ScenePurposes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneOutcomes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneMetricTypes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneMetricValues,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +TimelineSettings,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +TimelineMetricSettings,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +TimelineViewPresets,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +PlotLines,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +PlotThreads,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ThreadEvents,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +StoryAssets,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetStates,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetEvents,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetDependencies,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetCustodyEvents,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +AssetCustodyCharacters,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Characters,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneCharacters,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +CharacterAttributeTypes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +CharacterAttributeEvents,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +CharacterKnowledge,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +CharacterRelationships,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +RelationshipEvents,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Locations,2,2,2,Stored field comparison passed; only populated values exercised; external file bytes excluded +LocationRelationships,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +FloorPlans,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +FloorPlanFloors,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +FloorPlanBlocks,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +FloorPlanTransitions,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneAssetLocations,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneFloorPlanOccupancy,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneDependencies,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ValidationRuns,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ContinuityWarnings,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneNotes,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneWorkflow,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneChecklistItems,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +SceneAttachments,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ChapterGoals,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +Scenarios,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ScenarioSceneOrder,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ScenarioValidationRuns,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +ScenarioWarnings,1,1,1,Stored field comparison passed; only populated values exercised; external file bytes excluded +GenreMetricPresets,0,0,0,Diagnostic/shared vocabulary; excluded from portable restoration comparison +GenreMetricPresetMetrics,0,0,0,Diagnostic/shared vocabulary; excluded from portable restoration comparison +ProjectAccess,1,1,1,Diagnostic/shared vocabulary; excluded from portable restoration comparison +UserFiles,1,1,2,Diagnostic/shared vocabulary; excluded from portable restoration comparison diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 293614a8..25cfc132 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -141,3 +141,15 @@ Compared all 67 serialized entities (66 collections plus project) with the isola Expanded real-SQL verification passed for retained relationship review keys, archived scenario date/reason and audit actor/timestamp behavior. A second synthetic author cannot access the source project, scene or backup; imported ownership belongs exclusively to that author, and the original owner cannot access the copy. Original Word bindings remain active and copied bindings require reconnection. The actual restore workflow, safety backups and real SQL constraint-failure rollback passed again. A synthetic RelationshipTypes default pointed to an absent lookup category in the schema-only database; corrected the fixture vocabulary rather than claiming a product repair. Verification: solution build 0 warnings/errors; 405 regression checks passed (exit 0); isolated specialist `/tmp/plotdirector-phase2-transfer-stored-metadata.log` passed. Only the synthetic database received migration 214. Remaining all-entity semantic comparison, SI/review persistence, file assets and other import/export workflows remain pending. Development is still unchanged and undeployed. + +### Populated serialized-data matrix and further defects + +The synthetic project now populates all 62 serialized persistent collections restored by the current implementation, including floor plans/rooms/transitions, asset states/dependencies/custody, character knowledge/attributes/appearances, custom metrics and separate timeline display settings, warnings, scene workflow/checklists/notes/link attachments, chapter goals, scenario order/validation/warnings and map journeys. The other four collections are shared genre vocabulary or diagnostic access/file accounting; their exclusion from portable restoration comparisons is explicit. `2026-11-03-phase2-roundtrip-coverage.csv` records row counts and scope per collection. + +Real SQL → backup projection comparison checks 970 stored values across 65 populated entities (including project and diagnostic rows). Copy comparison checks 931 stored values across all 62 persistent collections, normalizing new identities, references, importing actors, intentionally detached Word/analysis bindings and concurrency revision. In-place restore checks 934 stored values across the same 62 collections. Timeline JSON and map image placements receive separate reference/unknown-property comparisons. Nullable fields are compared as stored, not claimed to have every possible non-null value exercised. These results cover serialized data only: 48 additional FK/project-related tables and external uploaded file bytes still need separate classification/repair. + +Confirmed further export omissions: appearance detection provenance, character knowledge review key, character avatar/sex metadata, location detection settings, plot-event provenance and map modification timestamp. Custom metric `SortOrder` was replaced by project display order in export. Forward-only migration 215 repairs these projections. In-place restore validation also rewrote map appearance/reference JSON, changing saved settings and removing unknown properties; shared validation now leaves the validated original JSON intact. + +Confirmed copied Timeline presets retained original focus/filter entity IDs. Copy now remaps their explicit and embedded references while preserving unrecognised filter properties; invalid/missing references fail preview before allocation. Expanded malformed preview matrix: 15 cases. Persisted event source keys, once correctly exported, exposed their global uniqueness constraint: importing a copy collided with the original event. Copies now receive project/event-specific source identities and detach original analysis references, with an explicit preview warning. In-place restore retains original provenance keys. No claim is made that unexported SI review history has been restored. + +Verification: latest isolated run `/tmp/plotdirector-phase2-transfer-planning.log` passed, including actual safety backups, constraint-failure rollback and cross-author boundaries. Build zero warnings/errors. Broader harness running before commit. Migration 215, like 213/214, has only been applied to the synthetic database; Development remains unchanged. diff --git a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql new file mode 100644 index 00000000..d7235ce3 --- /dev/null +++ b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql @@ -0,0 +1,88 @@ +-- Only executed after the specialist harness verifies its literal synthetic-only database. +DECLARE @secondScene int, @otherLocation int, @otherAsset int, @state int, @metric int, + @attribute int, @custody int, @floorPlan int, @floor int, @validation int, + @scenario int, @scenarioValidation int; +INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,Summary,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) +VALUES(@chapter,2.5,N'Second empty scene',N'',2,@revision,@timeMode,@confidence); +SET @secondScene=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@project,N'Corridor 雪',@location); +SET @otherLocation=SCOPE_IDENTITY(); +INSERT dbo.StoryAssets(ProjectID,AssetName,AssetKindID) VALUES(@project,N'Envelope Ω',@kind); +SET @otherAsset=SCOPE_IDENTITY(); +INSERT dbo.AssetStates(ProjectID,AssetKindID,StateName,SortOrder,Description) VALUES(@project,@kind,N'Sealed Ω',1,N'Authored state café'); +SET @state=SCOPE_IDENTITY(); +UPDATE dbo.StoryAssets SET CurrentStateID=@state,CurrentLocationID=@location WHERE StoryAssetID=@asset; +INSERT dbo.ScenePurposes(SceneID,ScenePurposeTypeID) SELECT @scene,MIN(ScenePurposeTypeID) FROM dbo.ScenePurposeTypes; +INSERT dbo.SceneOutcomes(SceneID,OutcomeDescription) VALUES(@scene,N'An outcome — 雨'); +INSERT dbo.SceneMetricTypes(ProjectID,MetricName,Description,MinValue,MaxValue,DefaultValue,SortOrder) +VALUES(@project,N'Tension Ω',N'Custom metric 雪',0,20,7,1); +SET @metric=SCOPE_IDENTITY(); +INSERT dbo.SceneMetricValues(SceneID,MetricTypeID,Value,Notes) VALUES(@scene,@metric,8,N'Escalates café'); +IF NOT EXISTS(SELECT 1 FROM dbo.ProjectTimelineSettings WHERE ProjectID=@project) +INSERT dbo.ProjectTimelineSettings(ProjectID,ShowStoryAssets,ShowCharacterAppearances) VALUES(@project,1,1); +UPDATE dbo.ProjectTimelineSettings SET ShowSceneCards=0,ShowStoryAssets=1 WHERE ProjectID=@project; +INSERT dbo.ProjectTimelineMetricSettings(ProjectID,MetricTypeID,SortOrder) VALUES(@project,@metric,2); +INSERT dbo.TimelineViewPresets(ProjectID,BookID,PresetName,FilterJson,VisibilityJson,FocusType,FocusID) +VALUES(@project,@book,N'Authored view Ω',N'{"query":"café"}',N'{"warnings":true}',N'Character',@character); +UPDATE dbo.TimelineViewPresets SET FilterJson=CONCAT(N'{"ProjectID":',@project,N',"BookID":',@book,N',"SelectedSceneID":',@scene,N',"ChapterFromID":',@chapter,N',"ChapterToID":',@chapter,N',"SceneFromID":',@scene,N',"SceneToID":',@secondScene,N',"PlotLineID":',@line,N',"PlotThreadID":',@thread,N',"StoryAssetID":',@asset,N',"CharacterID":',@character,N',"POVCharacterID":',@character,N',"LocationID":',@location,N',"FocusType":"character","FocusID":',@character,N',"ShowWarningsOnly":true,"extension":{"query":"café"}}') WHERE ProjectID=@project; +INSERT dbo.AssetEvents(StoryAssetID,SceneID,AssetEventTypeID,ToStateID,EventTitle,EventDescription) +SELECT @asset,@scene,MIN(AssetEventTypeID),@state,N'Sealed Ω',N'Unicode event 雨' FROM dbo.AssetEventTypes; +INSERT dbo.AssetDependencies(SourceAssetID,TargetAssetID,AssetDependencyTypeID,SourceRequiredStateID,TargetBlockedStateID,Description) +SELECT @asset,@otherAsset,MIN(AssetDependencyTypeID),@state,@state,N'Asset prerequisite 雪' FROM dbo.AssetDependencyTypes; +INSERT dbo.AssetCustodyEvents(StoryAssetID,SceneID,AssetCustodyEventTypeID,Description) +SELECT @asset,@scene,MIN(AssetCustodyEventTypeID),N'Custody café' FROM dbo.AssetCustodyEventTypes; +SET @custody=SCOPE_IDENTITY(); +INSERT dbo.AssetCustodyEventCharacters(AssetCustodyEventID,CharacterID,CustodyRoleID) +SELECT @custody,@character,MIN(CustodyRoleID) FROM dbo.CustodyRoles; +INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,EmotionalState,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex) +SELECT @scene,@character,(SELECT MIN(CharacterRoleInSceneTypeID) FROM dbo.CharacterRoleInSceneTypes),MIN(PresenceTypeID),@location,@location,@otherLocation,N'Appears 雪',N'Coat Ω',N'Uneasy café',N'Manual',N'Narrator Ω',2,5 FROM dbo.PresenceTypes; +INSERT dbo.CharacterAttributeTypes(ProjectID,AttributeName,DataType,SortOrder) VALUES(@project,N'Voice Ω',N'Text',1); +SET @attribute=SCOPE_IDENTITY(); +INSERT dbo.CharacterAttributeEvents(CharacterID,CharacterAttributeTypeID,SceneID,AttributeValue,Description) +VALUES(@character,@attribute,@scene,N'Whispering 雨',N'Authored trait'); +INSERT dbo.CharacterKnowledge(CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,SourceReviewKey) +SELECT @character,@asset,@thread,@scene,MIN(KnowledgeStateID),@threadEvent,N'Knows the secret 雨',N'synthetic-knowledge-review' FROM dbo.KnowledgeStates; +INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,IsBidirectional,CanTravelDirectly,Notes) +SELECT @location,@otherLocation,MIN(LocationRelationshipTypeID),1,1,N'Connected rooms 雨' FROM dbo.LocationRelationshipTypes; +INSERT dbo.FloorPlans(ProjectID,Name,Description,LocationID) VALUES(@project,N'Layout Ω',N'Floor plan café',@location); +SET @floorPlan=SCOPE_IDENTITY(); +INSERT dbo.FloorPlanFloors(FloorPlanID,Name,SortOrder,GridWidth,GridHeight,LocationID,BackgroundOpacity,BackgroundScale,BackgroundOffsetX,BackgroundOffsetY,Description) +VALUES(@floorPlan,N'Ground 雪',1,30,20,@location,.6,1.5,3,4,N'Floor notes Ω'); +SET @floor=SCOPE_IDENTITY(); +INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells,BlockType,LabelOverride,Notes) +VALUES(@floor,@location,2,3,6,4,N'Room',N'Room label 雪',N'Block notes café'); +INSERT dbo.FloorPlanTransitions(FloorPlanFloorID,FromLocationID,ToLocationID,TransitionType,Notes,IsLocked,DisplayLabel) +VALUES(@floor,@location,@otherLocation,N'Door',N'Transition Ω',1,N'Locked café'); +UPDATE dbo.Scenes SET FloorPlanID=@floorPlan,InitialFloorPlanFloorID=@floor WHERE SceneID=@scene; +INSERT dbo.SceneAssetLocations(SceneID,StoryAssetID,LocationID,Description) VALUES(@scene,@asset,@location,N'On desk 雨'); +INSERT dbo.SceneFloorPlanOccupancy(SceneID,FloorPlanID,FloorPlanFloorID,CharacterID,LocationID) +VALUES(@scene,@floorPlan,@floor,@character,@location); +INSERT dbo.SceneDependencies(SourceSceneID,TargetSceneID,SceneDependencyTypeID,Description,ProjectID,IsHardDependency) +SELECT @scene,@secondScene,MIN(SceneDependencyTypeID),N'Before the next scene 雨',@project,1 FROM dbo.SceneDependencyTypes; +INSERT dbo.ValidationRuns(ProjectID,BookID,CompletedDate,TriggeredBy,ScopeDescription) +VALUES(@project,@book,'2026-11-03',N'Synthetic fixture',N'Book Ω'); +SET @validation=SCOPE_IDENTITY(); +INSERT dbo.ContinuityWarnings(ValidationRunID,ProjectID,BookID,ChapterID,SceneID,EntityType,EntityID,WarningTypeID,WarningSeverityID,Message,Details,IsIntentional) +SELECT @validation,@project,@book,@chapter,@scene,N'Character',@character,(SELECT MIN(WarningTypeID) FROM dbo.WarningTypes),MIN(WarningSeverityID),N'Warning café',N'Intentional 雨',1 FROM dbo.WarningSeverities; +INSERT dbo.SceneNotes(SceneID,SceneNoteTypeID,NoteTitle,NoteText,SortOrder,IsPinned) +SELECT @scene,MIN(SceneNoteTypeID),N'Note Ω',N'Long-form author note “雨”',1,1 FROM dbo.SceneNoteTypes; +INSERT dbo.SceneWorkflow(SceneID,DraftStatus,EstimatedWordCount,ActualWordCount,ReadyForDraft,IsBlocked,BlockedReason,Priority) +VALUES(@scene,N'Drafting',2500,1234,1,1,N'Needs research café',2); +INSERT dbo.SceneChecklistItems(SceneID,ItemText,IsCompleted,SortOrder) VALUES(@scene,N'Check continuity 雨',1,3); +INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,ExternalUrl,Notes) +SELECT @scene,MIN(SceneAttachmentTypeID),N'Research Ω',N'https://example.invalid/synthetic',N'External link only; no file-byte claim' FROM dbo.SceneAttachmentTypes; +INSERT dbo.ChapterGoals(ChapterID,GoalSummary,EmotionalGoal,ReaderTakeaway,MustInclude,RisksOrConcerns) +VALUES(@chapter,N'Goal Ω',N'Unease 雨',N'Question café',N'A clue',N'Ambiguity'); +SELECT @scenario=ScenarioID FROM dbo.Scenarios WHERE ProjectID=@project; +INSERT dbo.ScenarioSceneOrder(ScenarioID,SceneID,ProposedChapterID,ProposedSortOrder,Notes) +VALUES(@scenario,@scene,@chapter,2,N'Alternative sequence 雨'); +INSERT dbo.ScenarioValidationRuns(ScenarioID,CompletedDate,WarningCount) VALUES(@scenario,'2026-11-03',1); +SET @scenarioValidation=SCOPE_IDENTITY(); +INSERT dbo.ScenarioWarnings(ScenarioValidationRunID,ScenarioID,SceneID,EntityType,EntityID,WarningTypeName,SeverityName,Message,Details) +VALUES(@scenarioValidation,@scenario,@scene,N'Character',@character,N'SyntheticWarning',N'Warning',N'Scenario warning 雨',N'Alternative detail café'); +INSERT dbo.MapJourneyNotes(MapID,CharacterID,FromSceneID,ToSceneID,TravelMethod,TypicalMinutes) +VALUES(@map,@character,@scene,@secondScene,N'Walking café',18); +UPDATE dbo.StoryMaps SET AppearanceJson=JSON_MODIFY(AppearanceJson,'$.extension',JSON_QUERY(N'{"texture":"雨"}')), +ReferenceJson=JSON_MODIFY(ReferenceJson,'$.extension',JSON_QUERY(N'{"source":"café"}')) WHERE MapID=@map; +UPDATE dbo.Locations SET DetectionPriority=7,ExcludeFromCompanionDetection=1 WHERE LocationID=@otherLocation; +UPDATE dbo.ThreadEvents SET Source=N'Manual',SourceKey=CONCAT(N'synthetic-event-source-key-',@project),Confidence=.85 WHERE ThreadEventID=@threadEvent; diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs index 76cbeaf4..104ab46d 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"}) + foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.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."); @@ -124,8 +124,11 @@ internal static class ProjectTransferDatabaseTests var plan=await db.ExecuteScalarAsync("INSERT dbo.WritingPlans(UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes) VALUES(@user,@project,@book,N'Synthetic drafting plan',N'Draft','2026-11-01','2026-12-01',N'[1,3,5]',45);SELECT CONVERT(int,SCOPE_IDENTITY());",new{user,project,book}); await db.ExecuteAsync("INSERT dbo.WritingScheduleItems(WritingPlanID,SceneID,ScheduledDate,TaskType,ScheduleStatus,Notes) VALUES(@plan,@scene,'2026-11-03',N'Draft',N'Pending',N'Synthetic task café');",new{plan,scene}); await db.ExecuteAsync("UPDATE dbo.Books SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE BookID=@book;UPDATE dbo.Scenes SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE SceneID=@scene;",new{user,book,scene}); + var planningParameters=new DynamicParameters(new{project,book,chapter,scene,revision,timeMode,confidence,location,asset,kind,character,line,thread,threadEvent,map}){RemoveUnused=false}; + await db.ExecuteAsync(await File.ReadAllTextAsync("PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql"),planningParameters); var before=(await backups.GetProjectBackupAsync(project,user))!;Check(before.Project is not null,"Fixture project exported."); - Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single().Summary=="“Hello”—雪 🖋","Core Unicode export content."); + 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."); Console.WriteLine($"Synthetic project {project}: core, map and writing schedule populated; {before.Diagnostics.IncludedEntitySets.Count} advertised backup sets."); var userService=Proxy((name,args)=>name switch {"get_UserId"=>(int?)user,"get_IsAuthenticated"=>true,"get_Email"=>"phase2-synthetic@example.invalid","get_DisplayName"=>"Synthetic author",_=>throw new NotSupportedException(name)}); var subscription=Proxy((name,args)=>name switch {"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),"ReserveBookSlotsAsync"=>Task.FromResult(new BookSlotReservation{Allowed=true}),_=>throw new NotSupportedException(name)}); @@ -146,6 +149,9 @@ internal static class ProjectTransferDatabaseTests root=>root["Data"]!["MapFeatures"]![0]!["MapID"]=-1, root=>root["Data"]!["Scenes"]![0]!["ChapterID"]=-12345, root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="", + root=>root["Data"]!["TimelineViewPresets"]![0]!["FocusID"]=-12345, + root=>root["Data"]!["TimelineViewPresets"]![0]!["FilterJson"]="{\"SceneFromID\":-12345}", + root=>root["Data"]!["TimelineViewPresets"]![0]!["FilterJson"]="[]", root=>root["FormatVersion"]="999.0" }) { @@ -171,14 +177,29 @@ internal static class ProjectTransferDatabaseTests Console.WriteLine($"Import result: {result.Succeeded}; {result.Message}; {result.TechnicalDetail}"); Check(result.Succeeded,"Full project backup import must preserve a synthetic map and core structure."); var after=(await backups.GetProjectBackupAsync(result.ProjectID!.Value,importingUser))!; + await VerifyStoredRoundTripAsync(db,before,after,importingUser); Check(after.Data.StoryMaps.Count==2,"Restored maps are present."); Check(await access.UserCanOwnProjectAsync(result.ProjectID!.Value,importingUser) && !await access.UserCanAccessProjectAsync(result.ProjectID.Value,user),"Imported project belongs only to its importing author."); + Check(after.Data.TimelineViewPresets.Single().FocusID==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID,"Timeline focus follows the copied character."); + var copiedFilter=JsonDocument.Parse(after.Data.TimelineViewPresets.Single().FilterJson).RootElement; + Check(copiedFilter.GetProperty("ProjectID").GetInt32()==after.Project!.ProjectID && copiedFilter.GetProperty("BookID").GetInt32()==after.Data.Books.Single().BookID && copiedFilter.GetProperty("SelectedSceneID").GetInt32()==after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID && copiedFilter.GetProperty("CharacterID").GetInt32()==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID && copiedFilter.GetProperty("extension").GetProperty("query").GetString()=="café" && copiedFilter.GetProperty("ShowWarningsOnly").GetBoolean(),"Timeline embedded references are remapped and unknown filter properties retained."); + var copiedFilterIds=new Dictionary { + ["ProjectID"]=after.Project!.ProjectID,["BookID"]=after.Data.Books.Single().BookID, + ["SelectedSceneID"]=after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID, + ["SceneFromID"]=after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID,["SceneToID"]=after.Data.Scenes.Single(x=>x.SceneTitle=="Second empty scene").SceneID, + ["ChapterFromID"]=after.Data.Chapters.Single().ChapterID,["ChapterToID"]=after.Data.Chapters.Single().ChapterID, + ["PlotLineID"]=after.Data.PlotLines.Single(x=>x.PlotLineName=="Arc Ω").PlotLineID,["PlotThreadID"]=after.Data.PlotThreads.Single().PlotThreadID, + ["StoryAssetID"]=after.Data.StoryAssets.Single(x=>x.AssetName=="Notebook 雨").StoryAssetID,["LocationID"]=after.Data.Locations.Single(x=>x.LocationName=="Room Ω").LocationID, + ["CharacterID"]=after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID,["POVCharacterID"]=after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID, + ["FocusID"]=after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID }; + foreach(var entry in copiedFilterIds)Check(copiedFilter.GetProperty(entry.Key).GetInt32()==entry.Value,"Copied timeline filter "+entry.Key); var restoredMap=after.Data.StoryMaps.Single(x=>x.Name=="Synthetic map 雨"); Check(restoredMap.MapID!=map && after.Data.StoryMaps.Single(x=>x.Name=="Child map 雨").ParentMapID==restoredMap.MapID,"Map hierarchy is remapped."); Check(after.Data.MapFeatures.Count==2 && after.Data.MapFeatures.Single(x=>x.Name=="Island 雪").GeometryJson==second.GeometryJson,"Map shapes and Unicode retained."); Check(after.Data.MapRelationships.Single().MeasuredDistance==12.5m && after.Data.MapRelationships.Single().MapID==restoredMap.MapID,"Map relationship content and map reference retained."); var restoredImage=after.Data.MapReferenceImages.Single(); Check(restoredImage.ImageID!=image.ImageID && restoredImage.ImageData!.SequenceEqual(sourceImageBytes),"Embedded image ID remapped and exact bytes retained."); + Check(JsonDocument.Parse(restoredMap.ReferenceJson).RootElement.GetProperty("extension").GetProperty("source").GetString()=="café","Unknown reference-image placement properties survive copied image remapping."); Check(MapAppearanceJson.Read(restoredMap.ReferenceJson).ImageID==restoredImage.ImageID,"Map image placement references the new embedded asset."); Check((await maps.GetAsync(project,map,user))!.Map.Name=="Synthetic map 雨","Original project remains unchanged."); Check(after.Data.Books.Single().StoryEra=="Future era" && after.Data.Books.Single().PrimaryLocaleCode=="en-GB" && after.Data.Books.Single().UsesExplicitScenes,"Book era and locale preserved."); @@ -188,22 +209,22 @@ internal static class ProjectTransferDatabaseTests var importedPlan=after.Data.WritingPlans.Single();var importedTask=after.Data.WritingScheduleItems.Single(); Check(importedPlan.WritingPlanID!=plan && importedPlan.ProjectID==after.Project!.ProjectID && importedPlan.BookID==after.Data.Books.Single().BookID && importedPlan.UserID==importingUser,"Writing plan ownership and project/book remapping."); Check(importedPlan.PlanName=="Synthetic drafting plan" && importedPlan.AvailableDaysJson=="[1,3,5]" && importedPlan.SessionLengthMinutes==45 && importedPlan.DeadlineDate.Date==new DateTime(2026,12,1),"Writing plan settings and deadline retained."); - Check(importedTask.WritingPlanID==importedPlan.WritingPlanID && importedTask.SceneID==after.Data.Scenes.Single().SceneID && importedTask.Notes=="Synthetic task café" && importedTask.ScheduledDate.Date==new DateTime(2026,11,3),"Scheduled task content, date and scene references retained."); + Check(importedTask.WritingPlanID==importedPlan.WritingPlanID && importedTask.SceneID==after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID && importedTask.Notes=="Synthetic task café" && importedTask.ScheduledDate.Date==new DateTime(2026,11,3),"Scheduled task content, date and scene references retained."); Check(after.Data.CharacterAliases.Single().Alias=="N. Ω" && after.Data.CharacterAliases.Single().CharacterID==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID,"Character alias text and remapped identity retained."); - Check(after.Data.AssetAliases.Single().Alias=="Café notebook" && after.Data.AssetAliases.Single().StoryAssetID==after.Data.StoryAssets.Single().StoryAssetID,"Asset alias retained."); - Check(after.Data.LocationAliases.Single().Alias=="Room 雨" && after.Data.LocationAliases.Single().LocationID==after.Data.Locations.Single().LocationID,"Location alias retained."); + Check(after.Data.AssetAliases.Single().Alias=="Café notebook" && after.Data.AssetAliases.Single().StoryAssetID==after.Data.StoryAssets.Single(x=>x.AssetName=="Notebook 雨").StoryAssetID,"Asset alias retained."); + Check(after.Data.LocationAliases.Single().Alias=="Room 雨" && after.Data.LocationAliases.Single().LocationID==after.Data.Locations.Single(x=>x.LocationName=="Room Ω").LocationID,"Location alias retained."); Check(after.Data.AuthorPlotSeeds.Single().Description=="The author’s Unicode intention 雪" && after.Data.AuthorPlotSeeds.Single().MatchedPlotLineID==after.Data.PlotLines.Single(x=>x.PlotLineName=="Second arc 雨").PlotLineID,"Authored plot seed and target retained."); var acknowledgement=after.Data.ContinuityWarningAcknowledgements.Single(); - Check(acknowledgement.Notes=="Author acknowledgement café" && acknowledgement.SceneID==after.Data.Scenes.Single().SceneID && acknowledgement.CharacterID==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID && acknowledgement.AssetID==after.Data.StoryAssets.Single().StoryAssetID,"Acknowledged warning and all entity references retained."); + Check(acknowledgement.Notes=="Author acknowledgement café" && acknowledgement.SceneID==after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID && acknowledgement.CharacterID==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID && acknowledgement.AssetID==after.Data.StoryAssets.Single(x=>x.AssetName=="Notebook 雨").StoryAssetID,"Acknowledged warning and all entity references retained."); Check(after.Data.PlotEventTargetPlotLines.Single().PlotEventID==after.Data.ThreadEvents.Single().ThreadEventID && after.Data.PlotEventTargetPlotLines.Single().PlotLineID==after.Data.PlotLines.Single(x=>x.PlotLineName=="Second arc 雨").PlotLineID,"Additional plot-event target retained."); Check(after.Data.RelationshipEvents.Single().SourceReviewKey=="synthetic-review-source-key" && after.Data.RelationshipEvents.Single().CharacterRelationshipID==after.Data.CharacterRelationships.Single().CharacterRelationshipID,"Relationship review source key and relationship link retained."); Check(after.Data.Scenarios.Single().ArchivedReason=="Synthetic archive reason 雨" && after.Data.Scenarios.Single().ArchivedDate==new DateTime(2026,10,12),"Scenario archive reason and date retained."); - Check(after.Data.Books.Single().CreatedByUserID==importingUser && after.Data.Books.Single().CreatedDateUTC==new DateTime(2026,9,1) && after.Data.Scenes.Single().ModifiedDateUTC==new DateTime(2026,10,1),"Imported audit actors are rebound while stored audit timestamps are retained."); + Check(after.Data.Books.Single().CreatedByUserID==importingUser && after.Data.Books.Single().CreatedDateUTC==new DateTime(2026,9,1) && after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").ModifiedDateUTC==new DateTime(2026,10,1),"Imported audit actors are rebound while stored audit timestamps are retained."); var savedSource=after.Data.SceneManuscriptSources.Single();var structuralSource=after.Data.ManuscriptStructuralChapterSources.Single(); - Check(savedSource.SourceText==manuscriptText && savedSource.SceneID==after.Data.Scenes.Single().SceneID && savedSource.BookID==after.Data.Books.Single().BookID && savedSource.SourceStartParagraph==1 && savedSource.WordEndParagraphIndex==1,"Exact Unicode manuscript text, paragraph coordinates and scene/book mapping retained."); + Check(savedSource.SourceText==manuscriptText && savedSource.SceneID==after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID && savedSource.BookID==after.Data.Books.Single().BookID && savedSource.SourceStartParagraph==1 && savedSource.WordEndParagraphIndex==1,"Exact Unicode manuscript text, paragraph coordinates and scene/book mapping retained."); Check(structuralSource.SourceText==manuscriptText && structuralSource.ParagraphMapJson==before.Data.ManuscriptStructuralChapterSources.Single().ParagraphMapJson && structuralSource.DefaultPovName=="Synthetic narrator","Structural chapter source and parsing context retained."); var copiedDocument=after.Data.ManuscriptDocuments.Single(); - Check(copiedDocument.DocumentGuid!=before.Data.ManuscriptDocuments.Single().DocumentGuid && !copiedDocument.IsActive && !after.Data.Scenes.Single().IsLinkedToManuscript && after.Data.Scenes.Single().ManuscriptDocumentID==copiedDocument.ManuscriptDocumentID,"Copied Word binding is isolated and explicitly awaits reconnection."); + Check(copiedDocument.DocumentGuid!=before.Data.ManuscriptDocuments.Single().DocumentGuid && !copiedDocument.IsActive && !after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").IsLinkedToManuscript && after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").ManuscriptDocumentID==copiedDocument.ManuscriptDocumentID,"Copied Word binding is isolated and explicitly awaits reconnection."); Check((await db.QuerySingleAsync("SELECT * FROM dbo.ManuscriptDocuments WHERE ManuscriptDocumentID=@id",new{id=documentId})).IsActive,"Original manuscript binding remains active."); var activity=Proxy((name,args)=>name=="RecordAsync" ? Task.CompletedTask : throw new NotSupportedException(name)); var exportService=new ProjectExportService(backups,activity,userService,NullLogger.Instance); @@ -215,8 +236,10 @@ internal static class ProjectTransferDatabaseTests 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."); var sameProject=(await backups.GetProjectBackupAsync(project,user))!; + await VerifyStoredRoundTripAsync(db,before,sameProject,null); + Check(System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(before.Data.TimelineViewPresets.Single().FilterJson),System.Text.Json.Nodes.JsonNode.Parse(sameProject.Data.TimelineViewPresets.Single().FilterJson)),"In-place restore preserves every timeline filter property."); Check(sameProject.Data.SceneManuscriptSources.Single().SourceText==manuscriptText && sameProject.Data.WritingPlans.Single().PlanName=="Synthetic drafting plan" && sameProject.Data.CharacterAliases.Single().Alias=="N. Ω","Same-project restore recovers text, schedule and authored alias."); - Check(sameProject.Data.ManuscriptDocuments.Single().DocumentGuid==before.Data.ManuscriptDocuments.Single().DocumentGuid && sameProject.Data.ManuscriptDocuments.Single().IsActive && sameProject.Data.Scenes.Single().IsLinkedToManuscript,"Same-project restore preserves original Word binding."); + Check(sameProject.Data.ManuscriptDocuments.Single().DocumentGuid==before.Data.ManuscriptDocuments.Single().DocumentGuid && sameProject.Data.ManuscriptDocuments.Single().IsActive && sameProject.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").IsLinkedToManuscript,"Same-project restore preserves original Word binding."); var badRestore=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(sameProject))!.AsObject(); var duplicate=badRestore["Data"]!["MapReferenceImages"]![0]!.DeepClone();duplicate["ImageID"]=Guid.NewGuid().ToString();badRestore["Data"]!["MapReferenceImages"]!.AsArray().Add(duplicate); var badPoint=await pointRepository.CreateAsync(project,"Invalid synthetic duplicate image","Manual",badRestore.ToJsonString(),"Expected SQL rollback"); @@ -226,8 +249,112 @@ internal static class ProjectTransferDatabaseTests Check(JsonSerializer.Serialize(afterFailedRestore.Data)==JsonSerializer.Serialize(sameProject.Data),"Failed restore leaves every serialized source field unchanged."); var foreignRestore=await restoreService.RestoreAsync(result.ProjectID.Value,savedPoint.ProjectRestorePointID); Check(!foreignRestore.Succeeded && foreignRestore.SafetyBackup is null,"Restore point cannot cross project boundaries."); - Console.WriteLine("PASS isolated SQL maps/assets/hierarchy, sources, schedules, aliases, plot seeds/targets, acknowledgements and actual restore safety/rollback; other entity coverage remains pending."); + var coverage=new List{"Collection,SourceRows,CopyRows,InPlaceRows,Verification"}; + foreach(var property in typeof(ProjectBackupData).GetProperties()) + { + int Count(ProjectBackupExport value)=>((System.Collections.IEnumerable)property.GetValue(value.Data)!).Cast().Count(); + var diagnostic=property.Name is "ProjectAccess" or "UserFiles" or "GenreMetricPresets" or "GenreMetricPresetMetrics"; + 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; external file bytes excluded")}"); + } + await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv",coverage); + Console.WriteLine("PASS 62 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented tables and external file bytes remain pending."); } + private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser) + { + var aliases=new Dictionary { ["TimelineSettings"]="ProjectTimelineSettings", ["TimelineMetricSettings"]="ProjectTimelineMetricSettings", ["AssetCustodyCharacters"]="AssetCustodyEventCharacters", ["ProjectAccess"]="ProjectUserAccess", ["UserFiles"]="UserFile" }; + // Account access/file accounting and shared preset vocabularies are diagnostic sets, not portable author data. + var excluded=new HashSet{"ProjectAccess","UserFiles","GenreMetricPresets","GenreMetricPresetMetrics"}; + var collections=typeof(ProjectBackupData).GetProperties().Where(p=>!excluded.Contains(p.Name)).Select(p=>(Name:p.Name,Table:aliases.GetValueOrDefault(p.Name,p.Name),Before:((System.Collections.IEnumerable)p.GetValue(original.Data)!).Cast().ToArray(),After:((System.Collections.IEnumerable)p.GetValue(restored.Data)!).Cast().ToArray())).ToArray(); + var ids=new Dictionary<(string Table,object ID),object>(); + var identities=new Dictionary(); + ids[("Projects",original.Project!.ProjectID)]=restored.Project!.ProjectID; + object? Read(object row,string column)=>row.GetType().GetProperty(column,BindingFlags.Instance|BindingFlags.Public|BindingFlags.IgnoreCase)!.GetValue(row); + foreach(var collection in collections) + { + Check(collection.Before.Length==collection.After.Length,"Round-trip row count: "+collection.Name); + var identity=await db.QuerySingleOrDefaultAsync("SELECT name FROM sys.columns WHERE object_id=OBJECT_ID(@name) AND is_identity=1",new{name="dbo."+collection.Table}); + if(identity is null && collection.Name=="MapReferenceImages")identity="ImageID"; + if(identity is not null)identities[collection.Table]=identity; + if(identity is not null)for(var index=0;index("SELECT name FROM sys.columns WHERE object_id=OBJECT_ID(@name) AND is_computed=0 ORDER BY column_id",new{name="dbo."+collection.Table})).ToArray(); + var links=(await db.QueryAsync("SELECT c.name AS ColumnName,rt.name AS TargetTable FROM sys.foreign_key_columns fk JOIN sys.columns c ON c.object_id=fk.parent_object_id AND c.column_id=fk.parent_column_id JOIN sys.tables rt ON rt.object_id=fk.referenced_object_id WHERE fk.parent_object_id=OBJECT_ID(@name)",new{name="dbo."+collection.Table})).GroupBy(row=>(string)row.ColumnName).ToDictionary(group=>group.Key,group=>(string)group.First().TargetTable); + for(var index=0;index"Projects","BookID" or "InitialBookID"=>"Books","ChapterID" or "ProposedChapterID"=>"Chapters","SceneID" or "FromSceneID" or "ToSceneID" or "SourceSceneID" or "TargetSceneID" or "AgeReferenceSceneID"=>"Scenes","CharacterID" or "CharacterAID" or "CharacterBID" or "POVCharacterID"=>"Characters","StoryAssetID" or "AssetID" or "SourceAssetID" or "TargetAssetID"=>"StoryAssets","LocationID" or "FromLocationID" or "ToLocationID" or "EntryLocationID" or "ExitLocationID" or "ParentLocationID" or "CurrentLocationID" or "PrimaryLocationID"=>"Locations","MapID" or "ParentMapID"=>"StoryMaps","MetricTypeID"=>"SceneMetricTypes","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""}; + var sourceValue=Read(collection.Before[index],column)!; + if(ids.TryGetValue((semanticTarget,sourceValue),out mapped))expected=mapped; + if(column=="EntityID" || collection.Name=="TimelineViewPresets" && column=="FocusID") + { + var type=Read(collection.Before[index],column=="EntityID"?"EntityType":"FocusType") as string; + var entityTable=type switch {"Character"=>"Characters","Scene"=>"Scenes","Chapter"=>"Chapters","Book"=>"Books","StoryAsset" or "Asset"=>"StoryAssets","Location"=>"Locations","PlotThread"=>"PlotThreads","PlotLine"=>"PlotLines",_=>""}; + if(ids.TryGetValue((entityTable,expected),out mapped))expected=mapped; + } + } + var equal=expected is byte[] bytes ? actual is byte[] copy && bytes.SequenceEqual(copy):Equals(expected,actual); + Check(equal,"Stored round-trip mismatch: "+collection.Name+"."+column); + fields++; + } + } + Console.WriteLine($"PASS {(importingUser.HasValue?"copy with reference/actor remapping":"in-place restore")}: {populated} populated persistent collections / {fields} stored values compared."); + } + + private static async Task VerifyStoredProjectionAsync(SqlConnection db, ProjectBackupExport backup) + { + var aliases=new Dictionary { ["TimelineSettings"]="ProjectTimelineSettings", ["TimelineMetricSettings"]="ProjectTimelineMetricSettings", ["AssetCustodyCharacters"]="AssetCustodyEventCharacters", ["ProjectAccess"]="ProjectUserAccess", ["UserFiles"]="UserFile" }; + var collections=typeof(ProjectBackupData).GetProperties().Select(p=>(Name:p.Name,Rows:((System.Collections.IEnumerable)p.GetValue(backup.Data)!).Cast().ToArray())).ToList(); + collections.Add(("Project",new object[]{backup.Project!})); + var fields=0;var populated=0; + foreach(var collection in collections) + { + if(collection.Rows.Length==0) continue; + populated++; + var table=collection.Name=="Project"?"Projects":aliases.GetValueOrDefault(collection.Name,collection.Name); + var columns=(await db.QueryAsync("SELECT c.name AS ColumnName,c.is_computed AS IsComputed FROM sys.columns c WHERE c.object_id=OBJECT_ID(@table) ORDER BY c.column_id",new{table="dbo."+table})).ToArray(); + var keys=(await db.QueryAsync("SELECT c.name FROM sys.indexes i JOIN sys.index_columns ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id JOIN sys.columns c ON c.object_id=ic.object_id AND c.column_id=ic.column_id WHERE i.object_id=OBJECT_ID(@table) AND i.is_primary_key=1 ORDER BY ic.key_ordinal",new{table="dbo."+table})).ToArray(); + Check(keys.Length>0,"Projection census requires a primary key for "+table); + foreach(var row in collection.Rows) + { + var parameters=new DynamicParameters();foreach(var key in keys)parameters.Add(key,row.GetType().GetProperty(key)!.GetValue(row)); + var actual=(IDictionary)await db.QuerySingleAsync("SELECT * FROM dbo.["+table+"] WHERE "+string.Join(" AND ",keys.Select(key=>"["+key+"]=@"+key)),parameters); + foreach(var column in columns) + { + if((bool)column.IsComputed)continue; + string name=column.ColumnName;var expected=actual[name];var exported=row.GetType().GetProperty(name,BindingFlags.Public|BindingFlags.Instance|BindingFlags.IgnoreCase)!.GetValue(row); + var equal=expected is byte[] bytes ? exported is byte[] copy && bytes.SequenceEqual(copy) + : expected is DateTime date ? exported is DateTime other && date==other + : expected is null ? exported is null + : Equals(expected,exported) || Convert.ToString(expected,System.Globalization.CultureInfo.InvariantCulture)==Convert.ToString(exported,System.Globalization.CultureInfo.InvariantCulture); + Check(equal,"Stored projection mismatch: "+table+"."+name); + fields++; + } + } + } + Console.WriteLine($"PASS SQL-to-backup projection: {populated} populated entities / {fields} stored field values compared."); + } + private static async Task EmitFieldInventoryAsync(SqlConnection db) { var aliases=new Dictionary { ["TimelineSettings"]="ProjectTimelineSettings", ["TimelineMetricSettings"]="ProjectTimelineMetricSettings", ["AssetCustodyCharacters"]="AssetCustodyEventCharacters", ["ProjectAccess"]="ProjectUserAccess", ["UserFiles"]="UserFile" }; diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 2ca350ca..c9c87db4 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -341,6 +341,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService validation.Warnings.Add("This is a PlotDirector project backup. It will be imported as a new project, not restored over an existing project."); if (backup.Data.ManuscriptDocuments.Any() || backup.Data.Chapters.Any(x => x.IsLinkedToManuscript) || backup.Data.Scenes.Any(x => x.IsLinkedToManuscript)) validation.Warnings.Add("Word manuscript links in an imported copy must be reconnected. Saved manuscript text is retained when present in the backup."); + if (backup.Data.ThreadEvents.Any(x => x.SourceKey is not null || x.SourceReferenceID.HasValue)) + validation.Warnings.Add("Copied plot events receive new source identities and are detached from the original analysis review records."); if (duplicate) { validation.Warnings.Add($"A project with the same title already exists. If imported anyway, the new project will be named \"{duplicateTitle}\"."); @@ -1158,6 +1160,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService threadEvent.EventTypeID = ResolveLookupID(threadEventTypeIds, threadEvent.EventTypeID, threadEvent.EventTypeName, $"Thread event \"{threadEvent.EventTitle}\" type"); threadEvent.PlotEventTypeID = ResolveLookupID(plotEventTypeIds, threadEvent.PlotEventTypeID, threadEvent.PlotEventTypeName, $"Thread event \"{threadEvent.EventTitle}\" plot event type"); threadEvent.TargetPlotLineID = ExistingOrNewNullable("PlotLines", threadEvent.TargetPlotLineID); + if (threadEvent.SourceKey is not null) threadEvent.SourceKey = $"backup:{projectId}:{threadEvent.ThreadEventID}"; + threadEvent.SourceReferenceID = null; // Copied events cannot refer into the original analysis/review. } foreach (var asset in backup.Data.StoryAssets) @@ -1488,6 +1492,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService note.FromSceneID = ExistingOrNew("Scenes", note.FromSceneID); note.ToSceneID = ExistingOrNew("Scenes", note.ToSceneID); } + foreach (var preset in backup.Data.TimelineViewPresets) + ProjectBackupTimelineState.Remap(preset,projectId,ExistingOrNewNullable); } private static int? RemapPolymorphicEntityID(string? entityType, int? entityId, Func remap) diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 5a78b74a..70ac9723 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -98,6 +98,6 @@ internal static class ProjectBackupGraphValidation return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record."; } } - return null; + return ProjectBackupTimelineState.Validate(backup); } } diff --git a/PlotLine/Services/ProjectBackupTimelineState.cs b/PlotLine/Services/ProjectBackupTimelineState.cs new file mode 100644 index 00000000..427f1b11 --- /dev/null +++ b/PlotLine/Services/ProjectBackupTimelineState.cs @@ -0,0 +1,59 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using PlotLine.Models; + +namespace PlotLine.Services; + +internal static class ProjectBackupTimelineState +{ + private static readonly Dictionary References = new(StringComparer.OrdinalIgnoreCase) + { + ["ProjectID"]="Project", ["BookID"]="Books", ["SelectedSceneID"]="Scenes", + ["ChapterFromID"]="Chapters", ["ChapterToID"]="Chapters", ["SceneFromID"]="Scenes", ["SceneToID"]="Scenes", + ["PlotLineID"]="PlotLines", ["PlotThreadID"]="PlotThreads", ["StoryAssetID"]="StoryAssets", + ["CharacterID"]="Characters", ["LocationID"]="Locations", ["POVCharacterID"]="Characters" + }; + private static string? FocusCollection(string? type) => type?.Trim().ToLowerInvariant() switch + { + "character"=>"Characters", "asset"=>"StoryAssets", "plotline"=>"PlotLines", "plotthread"=>"PlotThreads", + "location"=>"Locations", "scene"=>"Scenes", _=>null + }; + private static JsonObject Read(string json) => JsonNode.Parse(json,new(){PropertyNameCaseInsensitive=true}) as JsonObject + ?? throw new JsonException("Timeline filter must be an object."); + public static string? Validate(ProjectBackupExport backup) + { + var ids=new Dictionary> { + ["Project"]=[backup.Project!.ProjectID], ["Books"]=backup.Data.Books.Select(x=>x.BookID).ToHashSet(), + ["Chapters"]=backup.Data.Chapters.Select(x=>x.ChapterID).ToHashSet(), ["Scenes"]=backup.Data.Scenes.Select(x=>x.SceneID).ToHashSet(), + ["Characters"]=backup.Data.Characters.Select(x=>x.CharacterID).ToHashSet(), ["Locations"]=backup.Data.Locations.Select(x=>x.LocationID).ToHashSet(), + ["StoryAssets"]=backup.Data.StoryAssets.Select(x=>x.StoryAssetID).ToHashSet(), ["PlotLines"]=backup.Data.PlotLines.Select(x=>x.PlotLineID).ToHashSet(), + ["PlotThreads"]=backup.Data.PlotThreads.Select(x=>x.PlotThreadID).ToHashSet() + }; + bool Invalid(string? collection,int? id)=>collection is not null && id.HasValue && !ids[collection].Contains(id.Value); + try + { + foreach(var preset in backup.Data.TimelineViewPresets) + { + if(Invalid(FocusCollection(preset.FocusType),preset.FocusID))return "Timeline preset focus references a missing or foreign record."; + var filter=Read(preset.FilterJson); + foreach(var reference in References) + if(filter[reference.Key] is JsonNode value && Invalid(reference.Value,value.GetValue()))return "Timeline preset filter references a missing or foreign record."; + if(Invalid(FocusCollection(filter["FocusType"]?.GetValue()),filter["FocusID"]?.GetValue()))return "Timeline preset filter focus references a missing or foreign record."; + } + } + catch(Exception ex) when(ex is JsonException or InvalidOperationException or FormatException or ArgumentException) + {return "Timeline preset contains invalid filter JSON.";} + return null; + } + public static void Remap(TimelineViewPreset preset,int projectId,Func remap) + { + int? Map(string collection,int? id)=>collection=="Project" ? projectId : remap(collection,id); + if(FocusCollection(preset.FocusType) is string focus)preset.FocusID=Map(focus,preset.FocusID); + var filter=Read(preset.FilterJson); + foreach(var reference in References) + if(filter[reference.Key] is JsonNode value)filter[reference.Key]=Map(reference.Value,value.GetValue()); + if(FocusCollection(filter["FocusType"]?.GetValue()) is string embeddedFocus && filter["FocusID"] is JsonNode focusId) + filter["FocusID"]=Map(embeddedFocus,focusId.GetValue()); + preset.FilterJson=filter.ToJsonString(); + } +} diff --git a/PlotLine/Services/ProjectRestoreService.cs b/PlotLine/Services/ProjectRestoreService.cs index 3b09998f..d7ab77c7 100644 --- a/PlotLine/Services/ProjectRestoreService.cs +++ b/PlotLine/Services/ProjectRestoreService.cs @@ -115,8 +115,6 @@ public sealed class ProjectRestoreService( var graphError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup); if (graphError is not null) return graphError + " No project data was changed."; - foreach(var map in backup.Data.StoryMaps){if(map is null||map.ProjectID!=projectId||MapValidation.Validate(new(){Map=map}) is not null)return "Restore point contains invalid map appearance or placement settings.";map.AppearanceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(map.AppearanceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));map.ReferenceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(map.ReferenceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));} - if(backup.Data.MapReferenceImages.Any(image=>image is null||image.ProjectID!=projectId||!MapReferenceImageService.ValidBackupImage(image)))return "Restore point contains invalid reference images. No project data was changed."; return null; } diff --git a/PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql b/PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql new file mode 100644 index 00000000..c2e5edff --- /dev/null +++ b/PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql @@ -0,0 +1,644 @@ +-- Preserve stored map metadata in the backup projection. Forward-only follow-up to 214. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.StoryMap_Backup @ProjectID int,@UserID int=NULL +AS +BEGIN + SET NOCOUNT ON; + -- Same internal/null-user convention as ProjectBackup_Export; public export checks ownership first. + IF @UserID IS NOT NULL EXEC dbo.StoryMap_Authorize @ProjectID,@UserID; + SELECT * FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY MapID; + SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID ORDER BY f.MapID,f.FeatureID; + SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID ORDER BY r.MapID,r.RelationshipID; + SELECT n.* FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; + SELECT ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,FileSizeBytes,ImageData FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID ORDER BY ImageID; +END; +GO + +-- Backup the authored metric order separately from the project display order. +CREATE OR ALTER PROCEDURE dbo.ProjectBackup_Export + @ProjectID int, + @UserID int = NULL +AS +BEGIN + SET NOCOUNT ON; + + IF @UserID IS NOT NULL + AND NOT EXISTS + ( + SELECT 1 + FROM dbo.ProjectUserAccess + WHERE ProjectID = @ProjectID + AND UserID = @UserID + AND AccessRole = N'Owner' + AND IsActive = 1 + ) + SET @ProjectID = -1; + + SELECT ProjectID, ProjectName, Description, CreatedDate, UpdatedDate, IsArchived, ArchivedDate, ArchivedReason, + CreatedByUserID, ModifiedByUserID, CreatedDateUTC, ModifiedDateUTC + FROM dbo.Projects + WHERE ProjectID = @ProjectID; + + SELECT * + FROM dbo.Books + WHERE ProjectID = @ProjectID + ORDER BY SortOrder, BookNumber, BookID; + + SELECT c.*, rs.StatusName AS RevisionStatusName + FROM dbo.Chapters c + INNER JOIN dbo.Books b ON b.BookID = c.BookID + INNER JOIN dbo.RevisionStatuses rs ON rs.RevisionStatusID = c.RevisionStatusID + WHERE b.ProjectID = @ProjectID + ORDER BY b.SortOrder, c.SortOrder, c.ChapterID; + + SELECT s.*, l.LocationName AS PrimaryLocationName, l.LocationName AS PrimaryLocationPath, + tm.TimeModeName, du.DurationUnitName, tc.TimeConfidenceName, rs.StatusName AS RevisionStatusName + FROM dbo.Scenes s + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + INNER JOIN dbo.TimeModes tm ON tm.TimeModeID = s.TimeModeID + INNER JOIN dbo.TimeConfidences tc ON tc.TimeConfidenceID = s.TimeConfidenceID + INNER JOIN dbo.RevisionStatuses rs ON rs.RevisionStatusID = s.RevisionStatusID + LEFT JOIN dbo.DurationUnits du ON du.DurationUnitID = s.DurationUnitID + LEFT JOIN dbo.Locations l ON l.LocationID = s.PrimaryLocationID + WHERE b.ProjectID = @ProjectID + ORDER BY b.SortOrder, c.SortOrder, s.SortOrder, s.SceneID; + + SELECT sp.SceneID, sp.ScenePurposeTypeID, spt.PurposeName, spt.SortOrder + FROM dbo.ScenePurposes sp + INNER JOIN dbo.ScenePurposeTypes spt ON spt.ScenePurposeTypeID = sp.ScenePurposeTypeID + 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 + ORDER BY sp.SceneID, spt.SortOrder; + + SELECT so.SceneOutcomeID, so.SceneID, so.OutcomeDescription, so.OutcomeTypeID, so.CreatedDate, so.UpdatedDate + 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 + ORDER BY so.SceneID, so.SceneOutcomeID; + + SELECT mt.MetricTypeID, mt.ProjectID, mt.MetricName, mt.Description, mt.MinValue, mt.MaxValue, + mt.DefaultValue, mt.SortOrder, mt.IsActive, + CAST(CASE WHEN mt.IsActive = 1 AND ptms.MetricTypeID IS NOT NULL THEN 1 ELSE 0 END AS bit) AS IsEnabledForProject, + CAST(CASE WHEN mt.ProjectID = @ProjectID THEN 1 ELSE 0 END AS bit) AS IsCustom, + STUFF(( + SELECT N',' + gmp.PresetKey + FROM dbo.GenreMetricPresetMetrics gpmm + INNER JOIN dbo.GenreMetricPresets gmp ON gmp.GenreMetricPresetID = gpmm.GenreMetricPresetID + WHERE gpmm.MetricTypeID = mt.MetricTypeID + ORDER BY gmp.SortOrder, gmp.PresetName + FOR XML PATH(N''), TYPE).value(N'.', N'nvarchar(max)'), 1, 1, N'') AS GenrePresetKeys, + STUFF(( + SELECT N', ' + gmp.PresetName + FROM dbo.GenreMetricPresetMetrics gpmm + INNER JOIN dbo.GenreMetricPresets gmp ON gmp.GenreMetricPresetID = gpmm.GenreMetricPresetID + WHERE gpmm.MetricTypeID = mt.MetricTypeID + ORDER BY gmp.SortOrder, gmp.PresetName + FOR XML PATH(N''), TYPE).value(N'.', N'nvarchar(max)'), 1, 2, N'') AS GenrePresetNames, + ( + SELECT COUNT(1) + 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 smv.MetricTypeID = mt.MetricTypeID AND b.ProjectID = @ProjectID + ) AS ValueCount + FROM dbo.SceneMetricTypes mt + LEFT JOIN dbo.ProjectTimelineMetricSettings ptms ON ptms.ProjectID = @ProjectID AND ptms.MetricTypeID = mt.MetricTypeID + WHERE mt.ProjectID IS NULL + OR mt.ProjectID = @ProjectID + OR EXISTS + ( + SELECT 1 + 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 smv.MetricTypeID = mt.MetricTypeID AND b.ProjectID = @ProjectID + ) + ORDER BY COALESCE(ptms.SortOrder, mt.SortOrder), mt.MetricName; + + SELECT smv.SceneID, smv.MetricTypeID, mt.MetricName, mt.Description, mt.MinValue, mt.MaxValue, + mt.DefaultValue, mt.SortOrder, mt.IsActive, smv.Value, smv.Notes + FROM dbo.SceneMetricValues smv + INNER JOIN dbo.SceneMetricTypes mt ON mt.MetricTypeID = smv.MetricTypeID + 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 + ORDER BY smv.SceneID, mt.SortOrder; + + SELECT ProjectTimelineSettingsID, ProjectID, ShowSceneCards, ShowMetricShape, ShowPlotLines, + ShowStoryAssets, ShowCharacterAppearances, ShowWarnings, CreatedDate, UpdatedDate + FROM dbo.ProjectTimelineSettings + WHERE ProjectID = @ProjectID; + + SELECT ptms.ProjectID, ptms.MetricTypeID, mt.MetricName, ptms.SortOrder, ptms.CreatedDate + FROM dbo.ProjectTimelineMetricSettings ptms + INNER JOIN dbo.SceneMetricTypes mt ON mt.MetricTypeID = ptms.MetricTypeID + WHERE ptms.ProjectID = @ProjectID + ORDER BY ptms.SortOrder; + + SELECT TimelineViewPresetID, ProjectID, BookID, PresetName, FilterJson, VisibilityJson, FocusType, FocusID, + CreatedDate, UpdatedDate, IsArchived + FROM dbo.TimelineViewPresets + WHERE ProjectID = @ProjectID + ORDER BY PresetName; + + SELECT pl.PlotLineID, pl.ProjectID, pl.BookID, b.BookTitle, pl.PlotLineName, pl.PlotLineTypeID, + plt.TypeName AS PlotLineTypeName, pl.PlotImportanceID, pi.ImportanceName AS PlotImportanceName, + pl.Description, pl.ParentPlotLineID, parent.PlotLineName AS ParentPlotLineName, + pl.EmergesFromPlotLineID, emerges.PlotLineName AS EmergesFromPlotLineName, + pl.SortOrder, pl.Colour, pl.IsVisibleOnTimeline, pl.CreatedDate, pl.UpdatedDate, + pl.IsArchived, pl.ArchivedDate, pl.ArchivedReason, + pl.CreatedByUserID, pl.ModifiedByUserID, pl.CreatedDateUTC, pl.ModifiedDateUTC + FROM dbo.PlotLines pl + INNER JOIN dbo.PlotLineTypes plt ON plt.PlotLineTypeID = pl.PlotLineTypeID + INNER JOIN dbo.PlotImportance pi ON pi.PlotImportanceID = pl.PlotImportanceID + LEFT JOIN dbo.Books b ON b.BookID = pl.BookID + LEFT JOIN dbo.PlotLines parent ON parent.PlotLineID = pl.ParentPlotLineID + LEFT JOIN dbo.PlotLines emerges ON emerges.PlotLineID = pl.EmergesFromPlotLineID + WHERE pl.ProjectID = @ProjectID + ORDER BY pl.SortOrder, pl.PlotLineName; + + SELECT pt.PlotThreadID, pt.PlotLineID, pl.ProjectID, pl.PlotLineName, pt.ThreadTitle, pt.ThreadTypeID, + tt.TypeName AS ThreadTypeName, pt.ThreadStatusID, ts.StatusName AS ThreadStatusName, pt.Importance, + pt.Summary, pt.IntroducedSceneID, pt.PlannedResolutionSceneID, pt.ActualResolutionSceneID, + pt.CreatedDate, pt.UpdatedDate, pt.IsArchived, pt.ArchivedDate, pt.ArchivedReason, + pt.CreatedByUserID, pt.ModifiedByUserID, pt.CreatedDateUTC, pt.ModifiedDateUTC + FROM dbo.PlotThreads pt + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID + INNER JOIN dbo.ThreadTypes tt ON tt.ThreadTypeID = pt.ThreadTypeID + INNER JOIN dbo.ThreadStatuses ts ON ts.ThreadStatusID = pt.ThreadStatusID + WHERE pl.ProjectID = @ProjectID + ORDER BY pl.SortOrder, pt.Importance DESC, pt.ThreadTitle; + + SELECT te.ThreadEventID, te.PlotThreadID, pt.ThreadTitle, pl.PlotLineID, pl.PlotLineName, pl.Colour, + te.SceneID, te.EventTypeID, tet.TypeName AS EventTypeName, tet.MarkerText, + te.PlotEventTypeID, pet.TypeName AS PlotEventTypeName, te.TargetPlotLineID, target.PlotLineName AS TargetPlotLineName, + te.EventTitle, te.EventDescription, te.CreatedDate, te.UpdatedDate, + te.CreatedByUserID, te.ModifiedByUserID, te.CreatedDateUTC, te.ModifiedDateUTC, + te.Source, te.SourceReferenceID, te.SourceKey, te.Confidence + FROM dbo.ThreadEvents te + INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID + INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID + INNER JOIN dbo.ThreadEventTypes tet ON tet.ThreadEventTypeID = te.EventTypeID + INNER JOIN dbo.PlotEventTypes pet ON pet.PlotEventTypeID = te.PlotEventTypeID + LEFT JOIN dbo.PlotLines target ON target.PlotLineID = te.TargetPlotLineID + WHERE pl.ProjectID = @ProjectID + ORDER BY te.SceneID, te.ThreadEventID; + + SELECT sa.StoryAssetID, sa.ProjectID, sa.AssetName, sa.AssetKindID, ak.KindName, sa.Description, + sa.Importance, sa.CurrentStateID, ast.StateName AS CurrentStateName, sa.CurrentLocationID, + l.LocationName AS CurrentLocationName, l.LocationName AS CurrentLocationPath, sa.IsResolved, + sa.ShowInQuickAddBar, sa.ImagePath, sa.ThumbnailPath, sa.CreatedDate, sa.UpdatedDate, sa.IsArchived, sa.ArchivedDate, sa.ArchivedReason, + sa.CreatedByUserID, sa.ModifiedByUserID, sa.CreatedDateUTC, sa.ModifiedDateUTC + FROM dbo.StoryAssets sa + INNER JOIN dbo.AssetKinds ak ON ak.AssetKindID = sa.AssetKindID + LEFT JOIN dbo.AssetStates ast ON ast.AssetStateID = sa.CurrentStateID + LEFT JOIN dbo.Locations l ON l.LocationID = sa.CurrentLocationID + WHERE sa.ProjectID = @ProjectID + ORDER BY sa.Importance DESC, sa.AssetName; + + SELECT ast.AssetStateID, ast.ProjectID, ast.AssetKindID, ak.KindName, ast.StateName, ast.SortOrder, ast.Description, + ast.IsResolvedState, ast.IsActive + FROM dbo.AssetStates ast + LEFT JOIN dbo.AssetKinds ak ON ak.AssetKindID = ast.AssetKindID + WHERE ast.ProjectID IS NULL + OR ast.ProjectID = @ProjectID + OR EXISTS (SELECT 1 FROM dbo.StoryAssets sa WHERE sa.ProjectID = @ProjectID AND sa.CurrentStateID = ast.AssetStateID) + OR EXISTS (SELECT 1 FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID AND (ae.FromStateID = ast.AssetStateID OR ae.ToStateID = ast.AssetStateID)) + OR EXISTS (SELECT 1 FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID AND (ad.SourceRequiredStateID = ast.AssetStateID OR ad.TargetBlockedStateID = ast.AssetStateID)) + ORDER BY ast.SortOrder, ast.StateName; + + SELECT ae.AssetEventID, ae.StoryAssetID, sa.ProjectID, sa.AssetName, sa.AssetKindID, ak.KindName, + ae.SceneID, ae.AssetEventTypeID, aet.TypeName AS AssetEventTypeName, aet.MarkerText, + ae.FromStateID, fs.StateName AS FromStateName, ae.ToStateID, ts.StateName AS ToStateName, + ae.EventTitle, ae.EventDescription, b.BookTitle, c.ChapterNumber, s.SceneNumber, s.SceneTitle, + ae.CreatedDate, ae.UpdatedDate, + ae.CreatedByUserID, ae.ModifiedByUserID, ae.CreatedDateUTC, ae.ModifiedDateUTC + FROM dbo.AssetEvents ae + INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID + INNER JOIN dbo.AssetKinds ak ON ak.AssetKindID = sa.AssetKindID + INNER JOIN dbo.AssetEventTypes aet ON aet.AssetEventTypeID = ae.AssetEventTypeID + INNER JOIN dbo.Scenes s ON s.SceneID = ae.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + LEFT JOIN dbo.AssetStates fs ON fs.AssetStateID = ae.FromStateID + LEFT JOIN dbo.AssetStates ts ON ts.AssetStateID = ae.ToStateID + WHERE sa.ProjectID = @ProjectID + ORDER BY b.SortOrder, c.SortOrder, s.SortOrder, ae.AssetEventID; + + SELECT ad.AssetDependencyID, ad.SourceAssetID, source.AssetName AS SourceAssetName, ad.TargetAssetID, + target.AssetName AS TargetAssetName, ad.AssetDependencyTypeID, adt.TypeName AS DependencyTypeName, + adt.IsValidatingDependency, ad.SourceRequiredStateID, srs.StateName AS SourceRequiredStateName, + ad.TargetBlockedStateID, tbs.StateName AS TargetBlockedStateName, ad.Description, + ad.CreatedDate, ad.UpdatedDate, ad.IsArchived + FROM dbo.AssetDependencies ad + INNER JOIN dbo.StoryAssets source ON source.StoryAssetID = ad.SourceAssetID + INNER JOIN dbo.StoryAssets target ON target.StoryAssetID = ad.TargetAssetID + INNER JOIN dbo.AssetDependencyTypes adt ON adt.AssetDependencyTypeID = ad.AssetDependencyTypeID + LEFT JOIN dbo.AssetStates srs ON srs.AssetStateID = ad.SourceRequiredStateID + LEFT JOIN dbo.AssetStates tbs ON tbs.AssetStateID = ad.TargetBlockedStateID + WHERE source.ProjectID = @ProjectID OR target.ProjectID = @ProjectID + ORDER BY source.AssetName, target.AssetName; + + SELECT ace.AssetCustodyEventID, ace.StoryAssetID, sa.AssetName, ace.SceneID, ace.AssetCustodyEventTypeID, + acet.TypeName AS CustodyEventTypeName, ace.Description, + STRING_AGG(COALESCE(ch.CharacterName, acec.CharacterNameText), ', ') AS CustodianSummary, + b.BookTitle, c.ChapterNumber, s.SceneNumber, s.SceneTitle, ace.CreatedDate, ace.UpdatedDate + FROM dbo.AssetCustodyEvents ace + INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID + INNER JOIN dbo.AssetCustodyEventTypes acet ON acet.AssetCustodyEventTypeID = ace.AssetCustodyEventTypeID + INNER JOIN dbo.Scenes s ON s.SceneID = ace.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + LEFT JOIN dbo.AssetCustodyEventCharacters acec ON acec.AssetCustodyEventID = ace.AssetCustodyEventID + LEFT JOIN dbo.Characters ch ON ch.CharacterID = acec.CharacterID + WHERE sa.ProjectID = @ProjectID + GROUP BY ace.AssetCustodyEventID, ace.StoryAssetID, sa.AssetName, ace.SceneID, ace.AssetCustodyEventTypeID, + acet.TypeName, ace.Description, b.BookTitle, c.ChapterNumber, s.SceneNumber, s.SceneTitle, ace.CreatedDate, ace.UpdatedDate + ORDER BY MIN(b.SortOrder), MIN(c.SortOrder), MIN(s.SortOrder), ace.AssetCustodyEventID; + + SELECT acec.AssetCustodyEventCharacterID, acec.AssetCustodyEventID, acec.CharacterID, ch.CharacterName, + acec.CharacterNameText, acec.CustodyRoleID, cr.RoleName AS CustodyRoleName + FROM dbo.AssetCustodyEventCharacters acec + INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID + INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID + INNER JOIN dbo.CustodyRoles cr ON cr.CustodyRoleID = acec.CustodyRoleID + LEFT JOIN dbo.Characters ch ON ch.CharacterID = acec.CharacterID + WHERE sa.ProjectID = @ProjectID + ORDER BY acec.AssetCustodyEventID, acec.AssetCustodyEventCharacterID; + + SELECT CharacterID, ProjectID, CharacterName, ShortName, Sex, BirthDate, AgeAtSeriesStart, + AgeReferenceSceneID, Height, EyeColour, CharacterImportance, ShowInQuickAddBar, + DefaultDescription, ImagePath, ThumbnailPath, CreatedDate, UpdatedDate, IsArchived, ArchivedDate, ArchivedReason, + CreatedByUserID, ModifiedByUserID, CreatedDateUTC, ModifiedDateUTC, + AvatarSourceCharacterImageID, AvatarImagePath, AvatarThumbnailPath, SexValueID + FROM dbo.Characters + WHERE ProjectID = @ProjectID + ORDER BY CharacterImportance DESC, CharacterName; + + SELECT sc.SceneCharacterID, sc.SceneID, sc.CharacterID, ch.ProjectID, ch.CharacterName, ch.ShortName, + ch.BirthDate, ch.AgeAtSeriesStart, sc.RoleInSceneTypeID, rist.TypeName AS RoleInSceneTypeName, + sc.PresenceTypeID, pt.TypeName AS PresenceTypeName, sc.LocationID, loc.LocationName, + loc.LocationName AS LocationPath, sc.EntryLocationID, entryLoc.LocationName AS EntryLocationName, + sc.ExitLocationID, exitLoc.LocationName AS ExitLocationName, sc.AppearanceNotes, sc.OutfitDescription, + sc.PhysicalCondition, sc.EmotionalState, sc.KnowledgeNotes, s.SceneNumber, s.SceneTitle, + c.ChapterNumber, b.BookTitle, sc.CreatedDate, sc.UpdatedDate, + sc.MatchSource, sc.MatchedText, sc.OccurrenceCount, sc.FirstOccurrenceIndex + FROM dbo.SceneCharacters sc + INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID + INNER JOIN dbo.Scenes s ON s.SceneID = sc.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + LEFT JOIN dbo.CharacterRoleInSceneTypes rist ON rist.CharacterRoleInSceneTypeID = sc.RoleInSceneTypeID + LEFT JOIN dbo.PresenceTypes pt ON pt.PresenceTypeID = sc.PresenceTypeID + LEFT JOIN dbo.Locations loc ON loc.LocationID = sc.LocationID + LEFT JOIN dbo.Locations entryLoc ON entryLoc.LocationID = sc.EntryLocationID + LEFT JOIN dbo.Locations exitLoc ON exitLoc.LocationID = sc.ExitLocationID + WHERE ch.ProjectID = @ProjectID + ORDER BY b.SortOrder, c.SortOrder, s.SortOrder, ch.CharacterName; + + SELECT cat.CharacterAttributeTypeID, cat.ProjectID, cat.AttributeName, cat.DataType, cat.IsNormallyStable, + cat.SortOrder, cat.IsActive + FROM dbo.CharacterAttributeTypes cat + WHERE cat.ProjectID IS NULL + OR cat.ProjectID = @ProjectID + OR EXISTS (SELECT 1 FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID AND cae.CharacterAttributeTypeID = cat.CharacterAttributeTypeID) + ORDER BY cat.SortOrder, cat.AttributeName; + + SELECT cae.CharacterAttributeEventID, cae.CharacterID, ch.CharacterName, cae.CharacterAttributeTypeID, + cat.AttributeName, cae.SceneID, s.SceneNumber, s.SceneTitle, c.ChapterNumber, b.BookTitle, + cae.AttributeValue, cae.Description, cae.CreatedDate, cae.UpdatedDate + FROM dbo.CharacterAttributeEvents cae + INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID + INNER JOIN dbo.CharacterAttributeTypes cat ON cat.CharacterAttributeTypeID = cae.CharacterAttributeTypeID + INNER JOIN dbo.Scenes s ON s.SceneID = cae.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE ch.ProjectID = @ProjectID + ORDER BY ch.CharacterName, b.SortOrder, c.SortOrder, s.SortOrder; + + SELECT ck.CharacterKnowledgeID, ck.CharacterID, ch.CharacterName, ck.StoryAssetID, sa.AssetName, + ck.PlotThreadID, pt.ThreadTitle, ck.SceneID, s.SceneNumber, s.SceneTitle, c.ChapterNumber, b.BookTitle, + ck.KnowledgeStateID, ks.StateName AS KnowledgeStateName, ck.SourceEventID, ck.Description, + ck.CreatedDate, ck.UpdatedDate, + ck.SourceReviewKey + FROM dbo.CharacterKnowledge ck + INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID + INNER JOIN dbo.KnowledgeStates ks ON ks.KnowledgeStateID = ck.KnowledgeStateID + INNER JOIN dbo.Scenes s ON s.SceneID = ck.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + LEFT JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ck.StoryAssetID + LEFT JOIN dbo.PlotThreads pt ON pt.PlotThreadID = ck.PlotThreadID + WHERE ch.ProjectID = @ProjectID + ORDER BY ch.CharacterName, b.SortOrder, c.SortOrder, s.SortOrder; + + SELECT cr.CharacterRelationshipID, cr.ProjectID, cr.CharacterAID, a.CharacterName AS CharacterAName, + cr.CharacterBID, bch.CharacterName AS CharacterBName, cr.RelationshipTypeID, rt.TypeName AS RelationshipTypeName, + rt.RelationshipCategoryID, rc.CategoryName AS RelationshipCategoryName, rc.SortOrder AS CategorySortOrder, + rt.SortOrder AS RelationshipTypeSortOrder, cr.IsPermanent, cr.StartSceneID, cr.EndSceneID, + cr.IsKnownToReader, cr.Notes, cr.IsInitialRelationship, cr.InitialBookID, ib.BookTitle AS InitialBookTitle, + cr.ReaderInitiallyKnows, cr.InitialRelationshipStateID, irs.StateName AS InitialRelationshipStateName, + cr.InitialIntensity, cr.IsReciprocal, cr.CreatedDate, cr.UpdatedDate, + cr.IsArchived, cr.ArchivedDate, cr.ArchivedReason, + cr.CreatedByUserID, cr.ModifiedByUserID, cr.CreatedDateUTC, cr.ModifiedDateUTC + FROM dbo.CharacterRelationships cr + INNER JOIN dbo.Characters a ON a.CharacterID = cr.CharacterAID + INNER JOIN dbo.Characters bch ON bch.CharacterID = cr.CharacterBID + INNER JOIN dbo.RelationshipTypes rt ON rt.RelationshipTypeID = cr.RelationshipTypeID + INNER JOIN dbo.RelationshipCategories rc ON rc.RelationshipCategoryID = rt.RelationshipCategoryID + LEFT JOIN dbo.Books ib ON ib.BookID = cr.InitialBookID + LEFT JOIN dbo.RelationshipStates irs ON irs.RelationshipStateID = cr.InitialRelationshipStateID + WHERE cr.ProjectID = @ProjectID + ORDER BY a.CharacterName, bch.CharacterName, cr.CharacterRelationshipID; + + SELECT re.RelationshipEventID, re.CharacterRelationshipID, cr.ProjectID, cr.CharacterAID, + a.CharacterName AS CharacterAName, cr.CharacterBID, bch.CharacterName AS CharacterBName, + rt.TypeName AS RelationshipTypeName, rt.RelationshipCategoryID, rc.CategoryName AS RelationshipCategoryName, + rc.SortOrder AS CategorySortOrder, rt.SortOrder AS RelationshipTypeSortOrder, cr.IsReciprocal, + re.SceneID, s.SceneNumber, s.SceneTitle, c.ChapterNumber, bk.BookTitle, re.RelationshipStateID, + rs.StateName AS RelationshipStateName, re.Intensity, re.IsKnownToOtherCharacter, re.Description, + re.CreatedDate, re.UpdatedDate, + re.CreatedByUserID, re.ModifiedByUserID, re.CreatedDateUTC, re.ModifiedDateUTC, re.SourceReviewKey + FROM dbo.RelationshipEvents re + INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID + INNER JOIN dbo.Characters a ON a.CharacterID = cr.CharacterAID + INNER JOIN dbo.Characters bch ON bch.CharacterID = cr.CharacterBID + INNER JOIN dbo.RelationshipTypes rt ON rt.RelationshipTypeID = cr.RelationshipTypeID + INNER JOIN dbo.RelationshipCategories rc ON rc.RelationshipCategoryID = rt.RelationshipCategoryID + INNER JOIN dbo.RelationshipStates rs ON rs.RelationshipStateID = re.RelationshipStateID + INNER JOIN dbo.Scenes s ON s.SceneID = re.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books bk ON bk.BookID = c.BookID + WHERE cr.ProjectID = @ProjectID + ORDER BY bk.SortOrder, c.SortOrder, s.SortOrder, re.RelationshipEventID; + + SELECT l.LocationID, l.ProjectID, l.ParentLocationID, parent.LocationName AS ParentLocationName, + l.LocationName, l.LocationTypeID, lt.TypeName AS LocationTypeName, l.Description, + l.LocationName AS LocationPath, CAST(0 AS int) AS Depth, l.ShowInQuickAddBar, + l.CreatedDate, l.UpdatedDate, l.IsArchived, l.ArchivedDate, l.ArchivedReason, + l.CreatedByUserID, l.ModifiedByUserID, l.CreatedDateUTC, l.ModifiedDateUTC, + l.ExcludeFromCompanionDetection, l.DetectionPriority + FROM dbo.Locations l + LEFT JOIN dbo.Locations parent ON parent.LocationID = l.ParentLocationID + LEFT JOIN dbo.LocationTypes lt ON lt.LocationTypeID = l.LocationTypeID + WHERE l.ProjectID = @ProjectID + ORDER BY l.LocationName; + + SELECT lr.LocationRelationshipID, lr.FromLocationID, fl.LocationName AS FromLocationName, + lr.ToLocationID, tl.LocationName AS ToLocationName, lr.LocationRelationshipTypeID, + lrt.TypeName AS RelationshipTypeName, lr.IsBidirectional, lr.Strength, + lr.CanHearNormalSpeech, lr.CanHearLoudNoise, lr.CanSeeMovement, lr.CanSeeClearly, + lr.CanTravelDirectly, lr.Notes, lr.CreatedDate, lr.UpdatedDate, lr.IsArchived + FROM dbo.LocationRelationships lr + INNER JOIN dbo.Locations fl ON fl.LocationID = lr.FromLocationID + INNER JOIN dbo.Locations tl ON tl.LocationID = lr.ToLocationID + INNER JOIN dbo.LocationRelationshipTypes lrt ON lrt.LocationRelationshipTypeID = lr.LocationRelationshipTypeID + WHERE fl.ProjectID = @ProjectID OR tl.ProjectID = @ProjectID + ORDER BY fl.LocationName, tl.LocationName; + + + SELECT fp.FloorPlanID, fp.ProjectID, fp.LocationID, lp.LocationName, COALESCE(NULLIF(lp.LocationPath, N''), lp.LocationName) AS LocationPath, + fp.Name, fp.Description, fp.CreatedDate, fp.ModifiedDate, + (SELECT COUNT(1) FROM dbo.FloorPlanFloors fpf WHERE fpf.FloorPlanID = fp.FloorPlanID) AS FloorCount, + (SELECT COUNT(1) FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID WHERE fpf.FloorPlanID = fp.FloorPlanID) AS BlockCount + FROM dbo.FloorPlans fp + LEFT JOIN dbo.LocationPaths lp ON lp.LocationID = fp.LocationID + WHERE fp.ProjectID = @ProjectID + ORDER BY fp.Name, fp.FloorPlanID; + + SELECT fpf.FloorPlanFloorID, fpf.FloorPlanID, fpf.LocationID, lp.LocationName, COALESCE(NULLIF(lp.LocationPath, N''), lp.LocationName) AS LocationPath, + fpf.Name, fpf.Description, fpf.SortOrder, fpf.GridWidth, fpf.GridHeight, + fpf.BackgroundImagePath, fpf.BackgroundImageOriginalFileName, fpf.BackgroundOpacity, fpf.BackgroundScale, + fpf.BackgroundOffsetX, fpf.BackgroundOffsetY, fpf.BackgroundLocked, fpf.CreatedDate, fpf.ModifiedDate + FROM dbo.FloorPlanFloors fpf + INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID + LEFT JOIN dbo.LocationPaths lp ON lp.LocationID = fpf.LocationID + WHERE fp.ProjectID = @ProjectID + ORDER BY fp.Name, fpf.SortOrder, fpf.Name, fpf.FloorPlanFloorID; + + SELECT fpb.FloorPlanBlockID, fpb.FloorPlanFloorID, fpb.LocationID, lp.LocationName, + COALESCE(NULLIF(lp.LocationPath, N''), lp.LocationName) AS LocationPath, + fpb.X, fpb.Y, fpb.WidthCells, fpb.HeightCells, fpb.BlockType, fpb.LabelOverride, fpb.Notes, + fpb.CreatedDate, fpb.ModifiedDate + FROM dbo.FloorPlanBlocks fpb + INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID + INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID + INNER JOIN dbo.LocationPaths lp ON lp.LocationID = fpb.LocationID + WHERE fp.ProjectID = @ProjectID + ORDER BY fp.Name, fpf.SortOrder, fpb.Y, fpb.X, lp.LocationName; + + SELECT fpt.FloorPlanTransitionID, fpt.FloorPlanFloorID, fpt.FromLocationID, + fromPath.LocationName AS FromLocationName, COALESCE(NULLIF(fromPath.LocationPath, N''), fromPath.LocationName) AS FromLocationPath, + fpt.ToLocationID, toPath.LocationName AS ToLocationName, COALESCE(NULLIF(toPath.LocationPath, N''), toPath.LocationName) AS ToLocationPath, + fpt.TransitionType, fpt.Notes, fpt.IsLocked, fpt.DisplayLabel, fpt.PositionWithinLocation, + fpt.CreatedDate, fpt.ModifiedDate + FROM dbo.FloorPlanTransitions fpt + INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID + INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID + INNER JOIN dbo.LocationPaths fromPath ON fromPath.LocationID = fpt.FromLocationID + INNER JOIN dbo.LocationPaths toPath ON toPath.LocationID = fpt.ToLocationID + WHERE fp.ProjectID = @ProjectID + ORDER BY fp.Name, fpf.SortOrder, fromPath.LocationName, toPath.LocationName, fpt.TransitionType; + + SELECT sal.SceneAssetLocationID, sal.SceneID, sal.StoryAssetID, sa.AssetName, sal.LocationID, + l.LocationName, l.LocationName AS LocationPath, sal.Description, sal.CreatedDate, sal.UpdatedDate + FROM dbo.SceneAssetLocations sal + INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID + INNER JOIN dbo.Locations l ON l.LocationID = sal.LocationID + WHERE sa.ProjectID = @ProjectID + ORDER BY sal.SceneID, sa.AssetName; + + + SELECT o.SceneFloorPlanOccupancyID, o.SceneID, o.FloorPlanID, o.FloorPlanFloorID, fpf.Name AS FloorName, + o.CharacterID, c.CharacterName, c.ShortName AS CharacterShortName, c.ImagePath AS CharacterImagePath, c.ThumbnailPath AS CharacterThumbnailPath, + o.StoryAssetID, sa.AssetName, sa.ImagePath AS AssetImagePath, sa.ThumbnailPath AS AssetThumbnailPath, + o.LocationID, lp.LocationName, COALESCE(NULLIF(lp.LocationPath, N''), lp.LocationName) AS LocationPath, + o.CreatedDate, o.ModifiedDate + FROM dbo.SceneFloorPlanOccupancy o + INNER JOIN dbo.Scenes s ON s.SceneID = o.SceneID + INNER JOIN dbo.Chapters chp ON chp.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = chp.BookID + INNER JOIN dbo.LocationPaths lp ON lp.LocationID = o.LocationID + LEFT JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = o.FloorPlanFloorID + LEFT JOIN dbo.Characters c ON c.CharacterID = o.CharacterID + LEFT JOIN dbo.StoryAssets sa ON sa.StoryAssetID = o.StoryAssetID + WHERE b.ProjectID = @ProjectID + ORDER BY b.SortOrder, chp.SortOrder, s.SortOrder, COALESCE(c.CharacterName, sa.AssetName); + + SELECT sd.SceneDependencyID, ISNULL(sd.ProjectID, @ProjectID) AS ProjectID, sd.SourceSceneID, sd.TargetSceneID, + sd.SceneDependencyTypeID, sdt.TypeName AS SceneDependencyTypeName, sd.Description, + sd.IsHardDependency, CAST(NULL AS nvarchar(50)) AS DependencyDirection, sb.BookID AS SourceBookID, sb.BookTitle AS SourceBookTitle, + sc.ChapterID AS SourceChapterID, sc.ChapterNumber AS SourceChapterNumber, ss.SceneNumber AS SourceSceneNumber, + ss.SceneTitle AS SourceSceneTitle, tb.BookID AS TargetBookID, tb.BookTitle AS TargetBookTitle, + tc.ChapterID AS TargetChapterID, tc.ChapterNumber AS TargetChapterNumber, ts.SceneNumber AS TargetSceneNumber, + ts.SceneTitle AS TargetSceneTitle, sd.CreatedDate, sd.UpdatedDate, sd.IsArchived + FROM dbo.SceneDependencies sd + INNER JOIN dbo.SceneDependencyTypes sdt ON sdt.SceneDependencyTypeID = sd.SceneDependencyTypeID + INNER JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + INNER JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + INNER JOIN dbo.Books sb ON sb.BookID = sc.BookID + INNER JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + INNER JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + INNER JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID + ORDER BY sb.SortOrder, sc.SortOrder, ss.SortOrder, sd.SceneDependencyID; + + SELECT ValidationRunID, ProjectID, BookID, StartedDate, CompletedDate, TriggeredBy, ScopeDescription + FROM dbo.ValidationRuns + WHERE ProjectID = @ProjectID + ORDER BY StartedDate DESC; + + SELECT cw.ContinuityWarningID, cw.ValidationRunID, cw.ProjectID, cw.BookID, b.BookTitle, cw.ChapterID, + c.ChapterNumber, c.ChapterTitle, cw.SceneID, s.SceneNumber, s.SceneTitle, cw.EntityType, cw.EntityID, + cw.WarningTypeID, wt.TypeName AS WarningTypeName, cw.WarningSeverityID, ws.SeverityName, + cw.Message, cw.Details, cw.IsDismissed, cw.IsIntentional, cw.CreatedDate, cw.LastDetectedDate + FROM dbo.ContinuityWarnings cw + INNER JOIN dbo.WarningTypes wt ON wt.WarningTypeID = cw.WarningTypeID + INNER JOIN dbo.WarningSeverities ws ON ws.WarningSeverityID = cw.WarningSeverityID + LEFT JOIN dbo.Books b ON b.BookID = cw.BookID + LEFT JOIN dbo.Chapters c ON c.ChapterID = cw.ChapterID + LEFT JOIN dbo.Scenes s ON s.SceneID = cw.SceneID + WHERE cw.ProjectID = @ProjectID + ORDER BY cw.LastDetectedDate DESC, cw.ContinuityWarningID; + + SELECT sn.SceneNoteID, sn.SceneID, sn.SceneNoteTypeID, snt.TypeName, sn.NoteTitle, sn.NoteText, + sn.SortOrder, sn.IsPinned, sn.IsResolved, sn.CreatedDate, sn.UpdatedDate, + sn.CreatedByUserID, sn.ModifiedByUserID, sn.CreatedDateUTC, sn.ModifiedDateUTC + FROM dbo.SceneNotes sn + INNER JOIN dbo.SceneNoteTypes snt ON snt.SceneNoteTypeID = sn.SceneNoteTypeID + 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 + ORDER BY sn.SceneID, sn.SortOrder, sn.SceneNoteID; + + SELECT sw.SceneWorkflowID, sw.SceneID, sw.DraftStatus, sw.EstimatedWordCount, sw.ActualWordCount, + sw.DraftedDate, sw.LastWorkedOn, sw.ReadyForDraft, sw.ReadyForRevision, sw.ReadyForPolish, + sw.IsBlocked, sw.BlockedReason, sw.Priority, sw.CreatedDate, sw.UpdatedDate, + sw.CreatedByUserID, sw.ModifiedByUserID, sw.CreatedDateUTC, sw.ModifiedDateUTC + 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 + ORDER BY sw.SceneID; + + SELECT sci.SceneChecklistItemID, sci.SceneID, sci.ItemText, sci.IsCompleted, sci.SortOrder, + sci.CreatedDate, sci.UpdatedDate, + sci.CreatedByUserID, sci.ModifiedByUserID, sci.CreatedDateUTC, sci.ModifiedDateUTC + 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 + ORDER BY sci.SceneID, sci.SortOrder, sci.SceneChecklistItemID; + + SELECT sa.SceneAttachmentID, sa.SceneID, sa.SceneAttachmentTypeID, sat.TypeName, sa.Title, + sa.FilePath, sa.ExternalUrl, sa.Notes, sa.CreatedDate, sa.UpdatedDate, + sa.CreatedByUserID, sa.ModifiedByUserID, sa.CreatedDateUTC, sa.ModifiedDateUTC + FROM dbo.SceneAttachments sa + INNER JOIN dbo.SceneAttachmentTypes sat ON sat.SceneAttachmentTypeID = sa.SceneAttachmentTypeID + 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 + ORDER BY sa.SceneID, sa.SceneAttachmentID; + + SELECT cg.ChapterGoalID, cg.ChapterID, cg.GoalSummary, cg.EmotionalGoal, cg.ReaderTakeaway, + cg.MustInclude, cg.RisksOrConcerns, cg.CreatedDate, cg.UpdatedDate, + cg.CreatedByUserID, cg.ModifiedByUserID, cg.CreatedDateUTC, cg.ModifiedDateUTC + 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 + ORDER BY b.SortOrder, c.SortOrder; + + SELECT sc.ScenarioID, sc.ProjectID, sc.BookID, sc.ScenarioName, sc.Description, sc.BaseCreatedDate, + sc.IsAppliedToMain, sc.IsArchived, sc.ArchivedDate, sc.ArchivedReason, + sc.CreatedDate, sc.UpdatedDate, p.ProjectName, b.BookTitle, + (SELECT COUNT(1) FROM dbo.ScenarioSceneOrder sso WHERE sso.ScenarioID = sc.ScenarioID) AS SceneCount, + (SELECT COUNT(1) FROM dbo.ScenarioWarnings sw WHERE sw.ScenarioID = sc.ScenarioID) AS WarningCount + FROM dbo.Scenarios sc + INNER JOIN dbo.Projects p ON p.ProjectID = sc.ProjectID + LEFT JOIN dbo.Books b ON b.BookID = sc.BookID + WHERE sc.ProjectID = @ProjectID + ORDER BY sc.IsArchived, sc.UpdatedDate DESC; + + SELECT sso.ScenarioSceneOrderID, sso.ScenarioID, sso.SceneID, sso.ProposedChapterID, sso.ProposedSortOrder, + sso.Notes, sso.CreatedDate, sso.UpdatedDate + FROM dbo.ScenarioSceneOrder sso + INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID + WHERE sc.ProjectID = @ProjectID + ORDER BY sso.ScenarioID, sso.ProposedSortOrder; + + SELECT svr.ScenarioValidationRunID, svr.ScenarioID, svr.StartedDate, svr.CompletedDate, svr.WarningCount + FROM dbo.ScenarioValidationRuns svr + INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID + WHERE sc.ProjectID = @ProjectID + ORDER BY svr.StartedDate DESC; + + SELECT sw.ScenarioWarningID, sw.ScenarioValidationRunID, sw.ScenarioID, sw.SceneID, sw.EntityType, + sw.EntityID, sw.WarningTypeName, sw.SeverityName, sw.Message, sw.Details, sw.CreatedDate + FROM dbo.ScenarioWarnings sw + INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID + WHERE sc.ProjectID = @ProjectID + ORDER BY sw.CreatedDate DESC, sw.ScenarioWarningID; + + SELECT GenreMetricPresetID, PresetKey, PresetName, Description, SortOrder, IsActive + FROM dbo.GenreMetricPresets + ORDER BY SortOrder, PresetName; + + SELECT gpmm.GenreMetricPresetID, gmp.PresetKey, gmp.PresetName, + gpmm.MetricTypeID, mt.MetricName, gpmm.SortOrder + FROM dbo.GenreMetricPresetMetrics gpmm + INNER JOIN dbo.GenreMetricPresets gmp ON gmp.GenreMetricPresetID = gpmm.GenreMetricPresetID + INNER JOIN dbo.SceneMetricTypes mt ON mt.MetricTypeID = gpmm.MetricTypeID + WHERE EXISTS + ( + SELECT 1 + FROM dbo.SceneMetricTypes projectMetric + WHERE projectMetric.MetricTypeID = gpmm.MetricTypeID + AND + ( + projectMetric.ProjectID IS NULL + OR projectMetric.ProjectID = @ProjectID + OR EXISTS + ( + SELECT 1 + FROM dbo.ProjectTimelineMetricSettings ptms + WHERE ptms.ProjectID = @ProjectID + AND ptms.MetricTypeID = projectMetric.MetricTypeID + ) + ) + ) + ORDER BY gmp.SortOrder, gpmm.SortOrder, mt.MetricName; + + SELECT pua.ProjectUserAccessID, pua.ProjectID, pua.UserID, u.Email, u.DisplayName, + pua.AccessRole, pua.InvitedByUserID, invitedBy.Email AS InvitedByEmail, + pua.InvitedDateUTC, pua.AcceptedDateUTC, pua.IsActive + FROM dbo.ProjectUserAccess pua + INNER JOIN dbo.AppUser u ON u.UserID = pua.UserID + LEFT JOIN dbo.AppUser invitedBy ON invitedBy.UserID = pua.InvitedByUserID + WHERE pua.ProjectID = @ProjectID + AND pua.IsActive = 1 + ORDER BY CASE WHEN pua.AccessRole = N'Owner' THEN 0 ELSE 1 END, u.Email; + + SELECT UserFileID, UserID, ProjectID, EntityType, EntityID, FileName, OriginalFileName, ContentType, + FileSizeBytes, StoragePath, UploadedDateUTC, DeletedDateUTC, IsDeleted + FROM dbo.UserFile + WHERE ProjectID = @ProjectID + ORDER BY IsDeleted, UploadedDateUTC, UserFileID; +END; +GO + +