From a37f1c89ad5184918bdfa2c09e75d1ab0a036342 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 4 Nov 2026 03:05:37 +0000 Subject: [PATCH] Preserve Core Import location decisions and evidence across restores --- .../2026-11-03-phase2-data-coverage.csv | 114 ++--- .../2026-11-03-phase2-field-coverage.csv | 41 ++ .../2026-11-03-phase2-roundtrip-coverage.csv | 3 + Docs/Sprints/2026-11-03-phase2.md | 10 +- .../Fixtures/ProjectTransferPlanning.sql | 10 + .../ProjectTransferDatabaseTests.cs | 24 +- PlotLine/Data/ProjectBackupRepository.cs | 7 + PlotLine/Models/ProjectBackupModels.cs | 57 +++ PlotLine/Services/ImportServices.cs | 35 +- .../Services/ProjectBackupGraphValidation.cs | 3 + .../222_ProjectBackupCoreLocationReview.sql | 393 ++++++++++++++++++ 11 files changed, 630 insertions(+), 67 deletions(-) create mode 100644 PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql diff --git a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv index ce24f0e8..f619083e 100644 --- a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv @@ -1,19 +1,19 @@ Table,ProjectOwnershipEvidence,BackupCollection,Classification,RestoreVerified,AssetsVerified -AppUser,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +AppUser,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON 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 +AssetCustodyEventTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +AssetDependencyTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +AssetEventTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +AssetKinds,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" 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 +ChapterPurposeTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 @@ -25,67 +25,67 @@ CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,,Pending classifi CharacterIntelligenceProfiles,ProjectID or FK descendant,,Pending classification,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 +CharacterRoleInSceneTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" -CharacterSexValues,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +CharacterSexValues,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 -CustodyRoles,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -DurationUnits,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending -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 +CoreImportBasicLocationCandidates,ProjectID or FK descendant,CoreImportBasicLocationCandidates,Persistent Core Import author location choices and evidence; serialized,Pass: populated stored fields; canonical and build links remapped; shared new preview; in-place; old-snapshot refusal,Name aliases/evidence JSON retained exactly; no file bytes or paid analysis +CoreImportBasicLocationEvidence,ProjectID or FK descendant,CoreImportBasicLocationEvidence,Persistent Core Import author location choices and evidence; serialized,Pass: populated stored fields; canonical and build links remapped; shared new preview; in-place; old-snapshot refusal,Name aliases/evidence JSON retained exactly; no file bytes or paid analysis +CoreImportBasicLocationReviews,ProjectID or FK descendant,CoreImportBasicLocationReviews,Persistent Core Import author location choices and evidence; serialized,Pass: populated stored fields; canonical and build links remapped; shared new preview; in-place; old-snapshot refusal,Name aliases/evidence JSON retained exactly; no file bytes or paid analysis +CustodyRoles,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +DurationUnits,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +EmailQueue,Global/user/independent,,Account support/notification workflow; not manuscript or project planning data,Excluded from project restoration,Queued notifications must not be replayed by restoring author content +FeatureRequestMessages,Global/user/independent,,Account support/notification workflow; not manuscript or project planning data,Excluded from project restoration,Queued notifications must not be replayed by restoring author content +FeatureRequests,Global/user/independent,,Account support/notification workflow; not manuscript or project planning data,Excluded from project restoration,Queued notifications must not be replayed by restoring author content 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,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" 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 +GivenNames,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections IllustrationLibraryItems,SourceProjectID/SourceBookID soft references; shared and project-derived items,,Persistent generated asset catalogue and provenance; not included; separate scope/remapping needed,Pending,Not covered by current project backup file manifest -KnowledgeStates,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +KnowledgeStates,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +LocationRelationshipTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +LocationTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 -NameUsages,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +NameLocales,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections +NameReferenceImports,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections +NameRelationships,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections +NameUsages,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections OnboardingManuscriptBuildChapterMap,ProjectID or FK descendant,OnboardingManuscriptBuildChapterMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled OnboardingManuscriptBuildCharacterMap,ProjectID or FK descendant,OnboardingManuscriptBuildCharacterMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled OnboardingManuscriptBuilds,ProjectID or FK descendant,OnboardingManuscriptBuilds,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled OnboardingManuscriptBuildSceneMap,ProjectID or FK descendant,OnboardingManuscriptBuildSceneMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled 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 +PlotEventTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +PlotImportance,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +PlotLineTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +PresenceTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +ProjectInvitation,ProjectID or FK descendant,,Project security invitation/token ledger,Deliberately excluded from portable copy,Do not recreate sharing invitations or tokens on import +ProjectRestoreHistory,ProjectID or FK descendant,,Separate project recovery snapshots/history; recursive inclusion intentionally avoided,Excluded from backup Data; restore workflow creates independent safety backup/history,Saved restore-point download separately verified through actual HTTP/SQL +ProjectRestorePoints,ProjectID or FK descendant,,Separate project recovery snapshots/history; recursive inclusion intentionally avoided,Excluded from backup Data; restore workflow creates independent safety backup/history,Saved restore-point download separately verified through actual HTTP/SQL Projects,ProjectID or FK descendant,Project,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 +RelationshipCategories,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +RelationshipStates,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +RelationshipTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +RevisionStatuses,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 @@ -93,22 +93,22 @@ ScenarioWarnings,ProjectID or FK descendant,ScenarioWarnings,Serialized persiste 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,SceneAssetSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneAttachments,ProjectID or FK descendant,SceneAttachments,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files" -SceneAttachmentTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SceneAttachmentTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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,SceneCharacterSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneChecklistItems,ProjectID or FK descendant,SceneChecklistItems,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneDependencies,ProjectID or FK descendant,SceneDependencies,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated -SceneDependencyTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SceneDependencyTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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,SceneLocationSuggestions,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneManuscriptSources,ProjectID or FK descendant,SceneManuscriptSources,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneMetricTypes,ProjectID or FK descendant,SceneMetricTypes,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated SceneMetricValues,ProjectID or FK descendant,SceneMetricValues,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated 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 +SceneNoteTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +ScenePurposeTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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,SceneTextStatistics,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated @@ -138,31 +138,31 @@ StoryMemoryImportPreferences,ProjectID or FK descendant,,Pending classification, StoryMemoryLocations,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryMemoryProcessedSceneResults,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryMemoryRelationships,ProjectID or FK descendant,,Pending classification,Pending,Pending -StripeWebhookEvent,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending -SubscriptionAdministrationAudit,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending -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 +StripeWebhookEvent,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +SubscriptionAdministrationAudit,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +SubscriptionBookSlotReservation,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +SubscriptionLevel,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +SubscriptionOverride,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON 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 +ThreadEventTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +ThreadStatuses,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +ThreadTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +TimeConfidences,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee 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 +TimeModes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +UserEmailVerificationToken,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON UserFile,ProjectID or FK descendant,UserFiles,Serialized; field completeness unverified,Pending,Pending -UserLoginAudit,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +UserLoginAudit,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON UserOnboardingState,ProjectID or FK descendant,,Pending classification,Pending,Pending -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 +UserPasswordResetToken,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +UserSubscription,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON +UserTwoFactor,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON 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 +WarningSeverities,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee +WarningTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee WholeBookPlotSynthesisRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending WordCompanionSceneAssets,ProjectID or FK descendant,WordCompanionSceneAssets,Version 1.2 additive explicit Word associations; populated SQL stored-value round trip passed,Copy/in-place/safety/SQL rollback passed,Entity associations; file bytes not applicable WordCompanionSceneLocations,ProjectID or FK descendant,WordCompanionSceneLocations,Version 1.2 additive explicit Word associations; populated SQL stored-value round trip passed,Copy/in-place/safety/SQL rollback passed,Entity associations; file bytes not applicable 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 +WritingSolverVersions,Global/user/independent,,Shared published solver graph/version configuration,Excluded from project backup; not author-owned project content,Solver diagnostic export is a separate workflow diff --git a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv index 894c116a..a56bd547 100644 --- a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv @@ -246,6 +246,47 @@ ContinuityWarnings,ContinuityWarnings,IsDismissed,bit,False,False,True,Represent ContinuityWarnings,ContinuityWarnings,IsIntentional,bit,False,False,True,Represented; projection and semantic comparison still required ContinuityWarnings,ContinuityWarnings,CreatedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required ContinuityWarnings,ContinuityWarnings,LastDetectedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidateID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,CoreImportBasicLocationReviewID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,StableKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ProposedName,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,PreferredName,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,KnownNamesJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ParentLocationID,int,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ParentCandidateKey,nvarchar,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ExistingLocationID,int,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,Action,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,SameAsLocationID,int,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,SameAsCandidateKey,nvarchar,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ResultLocationID,int,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,FirstChapterNumber,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,FirstSceneNumber,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,FirstOccurrenceIndex,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,ObservationCount,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,SortOrder,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationCandidates,CoreImportBasicLocationCandidates,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidenceID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,CoreImportBasicLocationCandidateID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,ChapterID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,ChapterNumber,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,SceneNumber,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,OccurrenceIndex,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,EvidenceText,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationEvidence,CoreImportBasicLocationEvidence,SortOrder,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,CoreImportBasicLocationReviewID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,PreviewID,uniqueidentifier,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,UserID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,BookID,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,BuildID,int,True,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,RawObservationCount,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,CandidateCount,int,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +CoreImportBasicLocationReviews,CoreImportBasicLocationReviews,CompletedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required FloorPlanBlocks,FloorPlanBlocks,FloorPlanBlockID,int,False,False,True,Represented; projection and semantic comparison still required FloorPlanBlocks,FloorPlanBlocks,FloorPlanFloorID,int,False,False,True,Represented; projection and semantic comparison still required FloorPlanBlocks,FloorPlanBlocks,LocationID,int,False,False,True,Represented; projection and semantic comparison still required diff --git a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv index 688856fe..895c1650 100644 --- a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv @@ -1,4 +1,7 @@ Collection,SourceRows,CopyRows,InPlaceRows,Verification +CoreImportBasicLocationReviews,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +CoreImportBasicLocationCandidates,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +CoreImportBasicLocationEvidence,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present SceneAssetSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present SceneCharacterSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present SceneLocationSuggestions,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 07db539d..27d522c8 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -16,7 +16,7 @@ 2. COMPLETE: Writer/shared surface spacing, requested icon changes, Locations conventional commands/grips, mobile Chapter table repair and rendered coverage inventory (9d78a63, 016b58f, 869e305). 3. DEFERRED ACCEPTANCE: authenticated live Writer/PWA testing; no session is available. Real full-layout browser/Hub fixture results are recorded separately. 4. DEFERRED DEPLOYMENT: two illustration records were Generating at restart preflight. No interruption authorised; expanded gate b523a86 refuses restart. Recheck only at the next meaningful deployment checkpoint. -5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 77 collections (73 persistent plus 4 diagnostic/shared vocabulary), 78 SQL entities / 907 columns with no missing non-computed model properties. All 73 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff. +5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 80 collections (76 persistent plus 4 diagnostic/shared vocabulary), 81 SQL entities / 948 columns with no missing non-computed model properties. All 76 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff. 6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Eight HTTP/SQL export packets and five formats/aliases passed; expanded legacy JSON verification passed. Word structure API and Core Import SQL/source/provenance workflows now pass; next: remaining persistent project review data. 7. PENDING: remaining persistent table classification and historical fixture discovery. Unrepresented SI review/audit/provenance is persistent under its runtime contract, not an expendable cache; project-derived illustration catalogue/files also remain outside verified backup coverage. Do not claim a complete 167-table audit. 8. PENDING: finish independently safe data gaps and meaningful format round trips; record concrete limits/deferred work. No historical compatibility claim without actual fixtures. @@ -234,3 +234,11 @@ Populated all three scene suggestion tables and reproduced both omissions from b Real isolated SQL matrix passed: 77 serialized collections, all 73 persistent collections populated, source 1,192 stored values across 76 populated entities; copy 1,152 and in-place 1,156 values. Schema census 78 entities / 907 columns / zero missing non-computed model properties. Full solution build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-scene-review-before.log` (restore failure), `scene-review-projection-before.log` (explicit missing collection), `scene-review-after.log`, `scene-review-guards.log`, `census-scene-review.log` (each with the same `/tmp/plotdirector-phase2-` prefix). Still no Development writes/deployment. SI candidate JSON/audit graph and illustration catalogue/files remain outside the verified portable graph; no full 167-table coverage claim. Scene review checkpoint: full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-scene-review.log`). Migration 221 and all three old-snapshot refusal cases passed in the synthetic database only. + +## Core Import location-review history — 4 November + +Confirmed another three omitted persistent sets: Core Import location reviews, author candidate decisions and scene-backed evidence. Migration 222 and DTOs now preserve every stored field, result/existing/same-location/parent references, known-name JSON and completed history. Copies remap ownership and canonical/build references and reuse one fresh preview GUID for the matching build and review. The first combined comparison caught a new implementation ordering error (review BuildID assigned before build remapping); moving review remapping after build remapping resolved it. This failed fixture is retained as evidence rather than counted as a product regression. + +The final isolated SQL matrix passed all 76 populated persistent collections (80 serialized collections total): source 1,233 stored values in 79 populated entities; copy 1,192; in-place 1,197. Tests independently removed each of the three review collections from an old-shaped snapshot and confirmed refusal without removing evidence. Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-basic-review-before.log` (missing set), `basic-review-after.log` (new ordering error), `basic-review-order.log` (pass), `build-basic-review-order.log`, `census-basic-review.log` (all with `/tmp/plotdirector-phase2-` prefix). + +Inventory classification now explicitly separates shared vocabularies/name datasets and account/auth/billing/support/notification data from project content. Invitations/security tokens are deliberately not recreated; restore-point snapshots/history are separately managed to avoid recursive backup embedding. Unrepresented project-owned SI/audit/illustration data remains marked as a gap. No Development migration or deployment. diff --git a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql index 1ac0f3bb..c62acde4 100644 --- a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql +++ b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql @@ -104,3 +104,13 @@ INSERT dbo.SceneTextStatistics(SceneID,TotalWordCount,DialogueWordCount,ProseWor INSERT dbo.SceneAssetSuggestions(SceneID,AssetID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@asset,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x WHERE x.SceneID=@scene AND x.AssetID=@asset AND x.Status=v.Status); INSERT dbo.SceneCharacterSuggestions(SceneID,CharacterID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@character,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x WHERE x.SceneID=@scene AND x.CharacterID=@character AND x.Status=v.Status); INSERT dbo.SceneLocationSuggestions(SceneID,LocationID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@location,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x WHERE x.SceneID=@scene AND x.LocationID=@location AND x.Status=v.Status); + +DECLARE @locationReview int,@locationCandidate int; +INSERT dbo.CoreImportBasicLocationReviews(PreviewID,UserID,ProjectID,BookID,BuildID,Status,RawObservationCount,CandidateCount,CompletedUtc) +SELECT PreviewID,@user,@project,@book,@completedBuild,N'Completed',1,1,'2026-11-03' FROM dbo.OnboardingManuscriptBuilds WHERE OnboardingManuscriptBuildID=@completedBuild; +SET @locationReview=SCOPE_IDENTITY(); +INSERT dbo.CoreImportBasicLocationCandidates(CoreImportBasicLocationReviewID,StableKey,ProposedName,PreferredName,KnownNamesJson,ParentLocationID,ExistingLocationID,Action,SameAsLocationID,ResultLocationID,FirstChapterNumber,FirstSceneNumber,FirstOccurrenceIndex,ObservationCount,SortOrder) +VALUES(@locationReview,N'synthetic-location-Ω',N'Room detected 雨',N'Room approved Ω',N'["Room Ω","Chamber café"]',@otherLocation,@location,N'SameLocation',@location,@location,1,1,3,1,1); +SET @locationCandidate=SCOPE_IDENTITY(); +INSERT dbo.CoreImportBasicLocationEvidence(CoreImportBasicLocationCandidateID,SceneID,ChapterID,ChapterNumber,SceneNumber,OccurrenceIndex,EvidenceText,SortOrder) +VALUES(@locationCandidate,@scene,@chapter,1,1,3,N'“Entered the room”—exact evidence 雨',1); diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs index fb29dcee..a750ef26 100644 --- a/PlotLine.Tests/ProjectTransferDatabaseTests.cs +++ b/PlotLine.Tests/ProjectTransferDatabaseTests.cs @@ -43,7 +43,7 @@ internal static class ProjectTransferDatabaseTests } if(applyMigrations) { - foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql"}) + foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql","PlotLine/Sql/222_ProjectBackupCoreLocationReview.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."); @@ -157,8 +157,8 @@ internal static class ProjectTransferDatabaseTests var before=(await backups.GetProjectBackupAsync(project,user))!; await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported."); using(var encoded=JsonDocument.Parse(JsonSerializer.Serialize(before))) - foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics"}) - Check(encoded.RootElement.GetProperty("Data").TryGetProperty(required,out var rows) && rows.GetArrayLength()>0,"Backup must retain populated scene review/statistics set: "+required); + foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics","CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence"}) + Check(encoded.RootElement.GetProperty("Data").TryGetProperty(required,out var rows) && rows.GetArrayLength()>0,"Backup must retain populated review/statistics set: "+required); await VerifyStoredProjectionAsync(db,before); Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").Summary=="“Hello”—雪 🖋","Core Unicode export content."); if(coreOnly) @@ -277,6 +277,8 @@ internal static class ProjectTransferDatabaseTests var restoredPlans=await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.WritingPlans WHERE ProjectID=@id",new{id=result.ProjectID}); Console.WriteLine($"Writing plan coverage: source=1, imported={restoredPlans}; separate coverage gate."); if(before.FormatVersion=="1.2" || requireWritingPlans) Check(restoredPlans==1,"Persistent writing plan restored."); + var copiedReview=after.Data.CoreImportBasicLocationReviews.Single(); + Check(copiedReview.PreviewID==after.Data.OnboardingManuscriptBuilds.Single(b=>b.OnboardingManuscriptBuildID==copiedReview.BuildID).PreviewID,"Copied review and build share the same new preview identity."); 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."); @@ -309,6 +311,14 @@ internal static class ProjectTransferDatabaseTests var pointService=new ProjectRestorePointService(new ProjectRepository(factory),exportService,pointRepository,NullLogger.Instance); var restoreService=new ProjectRestoreService(pointRepository,pointService,NullLogger.Instance,assetFiles); var savedPoint=(await pointService.CreateManualAsync(project,"Synthetic baseline","Round-trip fixture"))!; + foreach(var omitted in new[]{"CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence"}) + { + var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!; + older["Data"]!.AsObject().Remove(omitted); + try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing Core Import location history."); } + catch(SqlException error) when(error.Number==51010) { } + Check((await backups.GetProjectBackupAsync(project,user))!.Data.CoreImportBasicLocationEvidence.Count==1,"Older snapshot refusal retains location evidence."); + } foreach(var omitted in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions"}) { var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!; @@ -356,7 +366,7 @@ internal static class ProjectTransferDatabaseTests coverage.Add($"{property.Name},{Count(before)},{Count(after)},{Count(sameProject)},{(diagnostic?"Diagnostic/shared vocabulary; excluded from portable restoration comparison":"Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present")}"); } await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv",coverage); - Console.WriteLine("PASS 73 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending."); + Console.WriteLine("PASS 76 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending."); } private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser) { @@ -396,11 +406,11 @@ internal static class ProjectTransferDatabaseTests if(collection.Name=="StoryMaps" && column=="Revision")continue; // Restore increments the optimistic concurrency token. if(importingUser.HasValue) { - if(collection.Name=="OnboardingManuscriptBuilds" && column=="PreviewID") {Check(!Equals(expected,actual),"Copied build preview identity must change");continue;} + if(collection.Name is "OnboardingManuscriptBuilds" or "CoreImportBasicLocationReviews" && column=="PreviewID") {Check(!Equals(expected,actual),"Copied build preview identity must change");continue;} if(collection.Name=="ManuscriptDocuments" && column=="DocumentGuid") {Check(!Equals(expected,actual),"Copy document GUID must change");continue;} if(collection.Name=="ManuscriptDocuments" && column=="IsActive" || collection.Name is "Scenes" or "Chapters" && column=="IsLinkedToManuscript")expected=false; if(collection.Name is "Scenes" or "Chapters" && column=="LinkedUtc" || collection.Name=="Scenes" && column=="ImportRunID")expected=null; - if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || column=="ReviewedByUserID" && expected is not null || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" && column=="UserID")expected=importingUser.Value; + if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || column=="ReviewedByUserID" && expected is not null || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" or "CoreImportBasicLocationReviews" && column=="UserID")expected=importingUser.Value; if(collection.Name=="ThreadEvents" && column=="SourceKey" && expected is not null)expected=$"backup:{restored.Project.ProjectID}:{Read(collection.After[index],"ThreadEventID")}"; if(collection.Name=="ThreadEvents" && column=="SourceReferenceID")expected=null; if(collection.Name=="StoryMaps" && column=="ReferenceJson")continue; // Exact placement/image identity asserted separately. @@ -409,7 +419,7 @@ internal static class ProjectTransferDatabaseTests { if(links.TryGetValue(column,out var target) && ids.TryGetValue((target,expected),out var mapped))expected=mapped; else if(identities.GetValueOrDefault(collection.Table)==column && ids.TryGetValue((collection.Table,expected),out mapped))expected=mapped; - var semanticTarget=column switch {"ProjectID"=>"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","AvatarSourceCharacterImageID"=>"CharacterImages","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""}; + var semanticTarget=column switch {"BuildID"=>"OnboardingManuscriptBuilds","ProjectID"=>"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","AvatarSourceCharacterImageID"=>"CharacterImages","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") diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index 10ea1567..e218499e 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -113,6 +113,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact data.SceneCharacterSuggestions = (await state.ReadAsync()).ToList(); data.SceneLocationSuggestions = (await state.ReadAsync()).ToList(); data.SceneTextStatistics = (await state.ReadAsync()).ToList(); + data.CoreImportBasicLocationReviews = (await state.ReadAsync()).ToList(); + data.CoreImportBasicLocationCandidates = (await state.ReadAsync()).ToList(); + data.CoreImportBasicLocationEvidence = (await state.ReadAsync()).ToList(); + } @@ -153,6 +157,9 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact ProjectId = projectId, IncludedEntitySets = [ + nameof(data.CoreImportBasicLocationReviews), + nameof(data.CoreImportBasicLocationCandidates), + nameof(data.CoreImportBasicLocationEvidence), nameof(data.SceneAssetSuggestions), nameof(data.SceneCharacterSuggestions), nameof(data.SceneLocationSuggestions), diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index eae01543..5afca0b3 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -14,6 +14,10 @@ public sealed class ProjectBackupExport public sealed class ProjectBackupData { + public IReadOnlyList CoreImportBasicLocationReviews { get; set; } = []; + public IReadOnlyList CoreImportBasicLocationCandidates { get; set; } = []; + public IReadOnlyList CoreImportBasicLocationEvidence { get; set; } = []; + public IReadOnlyList SceneAssetSuggestions { get; set; } = []; public IReadOnlyList SceneCharacterSuggestions { get; set; } = []; public IReadOnlyList SceneLocationSuggestions { get; set; } = []; @@ -372,3 +376,56 @@ public sealed class ProjectBackupSceneTextStatistics public DateTime CalculatedUtc { get; set; } public DateTime UpdatedUtc { get; set; } } + +public sealed class ProjectBackupCoreImportBasicLocationReviews +{ + public int CoreImportBasicLocationReviewID { get; set; } + public Guid PreviewID { get; set; } + public int UserID { get; set; } + public int ProjectID { get; set; } + public int BookID { get; set; } + public int? BuildID { get; set; } + public string Status { get; set; } = ""; + public int RawObservationCount { get; set; } + public int CandidateCount { get; set; } + public DateTime CreatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } + public DateTime? CompletedUtc { get; set; } +} + +public sealed class ProjectBackupCoreImportBasicLocationCandidates +{ + public int CoreImportBasicLocationCandidateID { get; set; } + public int CoreImportBasicLocationReviewID { get; set; } + public string StableKey { get; set; } = ""; + public string ProposedName { get; set; } = ""; + public string PreferredName { get; set; } = ""; + public string KnownNamesJson { get; set; } = ""; + public int? ParentLocationID { get; set; } + public string? ParentCandidateKey { get; set; } + public int? ExistingLocationID { get; set; } + public string Action { get; set; } = ""; + public int? SameAsLocationID { get; set; } + public string? SameAsCandidateKey { get; set; } + public int? ResultLocationID { get; set; } + public int FirstChapterNumber { get; set; } + public int FirstSceneNumber { get; set; } + public int FirstOccurrenceIndex { get; set; } + public int ObservationCount { get; set; } + public int SortOrder { get; set; } + public DateTime CreatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } +} + +public sealed class ProjectBackupCoreImportBasicLocationEvidence +{ + public int CoreImportBasicLocationEvidenceID { get; set; } + public int CoreImportBasicLocationCandidateID { get; set; } + public int SceneID { get; set; } + public int ChapterID { get; set; } + public int ChapterNumber { get; set; } + public int SceneNumber { get; set; } + public int OccurrenceIndex { get; set; } + public string EvidenceText { get; set; } = ""; + public int SortOrder { get; set; } +} diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 16062f31..18c9094a 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -839,7 +839,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService private static readonly string[] ProjectBackupIdentityTables = [ "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps", - "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", + "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements", "SceneOutcomes", "PlotLines", "PlotThreads", "ThreadEvents", "AssetStates", "StoryAssets", "AssetEvents", "AssetDependencies", "AssetCustodyEvents", "AssetCustodyEventCharacters", "Characters", "SceneCharacters", "CharacterAttributeTypes", "CharacterAttributeEvents", "CharacterKnowledge", "CharacterRelationships", @@ -1524,6 +1524,12 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService note.FromSceneID = ExistingOrNew("Scenes", note.FromSceneID); note.ToSceneID = ExistingOrNew("Scenes", note.ToSceneID); } + var copiedPreviewIds=new Dictionary(); + Guid CopyPreview(Guid old) + { + if(!copiedPreviewIds.TryGetValue(old,out var copied)) copiedPreviewIds[old]=copied=Guid.NewGuid(); + return copied; + } foreach(var row in backup.Data.SceneAssetSuggestions) { row.SceneAssetSuggestionID=NewId("SceneAssetSuggestions",row.SceneAssetSuggestionID); @@ -1552,7 +1558,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService foreach(var build in backup.Data.OnboardingManuscriptBuilds) { build.OnboardingManuscriptBuildID=NewId("OnboardingManuscriptBuilds",build.OnboardingManuscriptBuildID); - build.PreviewID=Guid.NewGuid(); + build.PreviewID=CopyPreview(build.PreviewID); if(build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled") || build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete")) { @@ -1580,6 +1586,31 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService map.OnboardingManuscriptBuildID=ExistingOrNew("OnboardingManuscriptBuilds",map.OnboardingManuscriptBuildID); map.CharacterID=ExistingOrNew("Characters",map.CharacterID); } + foreach(var row in backup.Data.CoreImportBasicLocationReviews) + { + row.CoreImportBasicLocationReviewID=NewId("CoreImportBasicLocationReviews",row.CoreImportBasicLocationReviewID); + row.PreviewID=CopyPreview(row.PreviewID); + row.UserID=importingUserId; + row.ProjectID=projectId; + row.BookID=ExistingOrNew("Books",row.BookID); + row.BuildID=ExistingOrNewNullable("OnboardingManuscriptBuilds",row.BuildID); + } + foreach(var row in backup.Data.CoreImportBasicLocationCandidates) + { + row.CoreImportBasicLocationCandidateID=NewId("CoreImportBasicLocationCandidates",row.CoreImportBasicLocationCandidateID); + row.CoreImportBasicLocationReviewID=ExistingOrNew("CoreImportBasicLocationReviews",row.CoreImportBasicLocationReviewID); + row.ParentLocationID=ExistingOrNewNullable("Locations",row.ParentLocationID); + row.ExistingLocationID=ExistingOrNewNullable("Locations",row.ExistingLocationID); + row.SameAsLocationID=ExistingOrNewNullable("Locations",row.SameAsLocationID); + row.ResultLocationID=ExistingOrNewNullable("Locations",row.ResultLocationID); + } + foreach(var row in backup.Data.CoreImportBasicLocationEvidence) + { + row.CoreImportBasicLocationEvidenceID=NewId("CoreImportBasicLocationEvidence",row.CoreImportBasicLocationEvidenceID); + row.CoreImportBasicLocationCandidateID=ExistingOrNew("CoreImportBasicLocationCandidates",row.CoreImportBasicLocationCandidateID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + row.ChapterID=ExistingOrNew("Chapters",row.ChapterID); + } foreach (var image in backup.Data.CharacterImages) { image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID); diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index f7976665..ac068fa0 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -8,6 +8,9 @@ internal static class ProjectBackupGraphValidation private sealed record Link(string Column, string TargetCollection, string TargetColumn); private sealed record Entity(string Collection, string? Identity, params Link[] Links); private static readonly Entity[] Entities = [ + new("CoreImportBasicLocationReviews","CoreImportBasicLocationReviewID",new Link("BookID","Books","BookID"),new Link("ProjectID","Project","ProjectID"),new Link("BuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID")), + new("CoreImportBasicLocationCandidates","CoreImportBasicLocationCandidateID",new Link("ExistingLocationID","Locations","LocationID"),new Link("ParentLocationID","Locations","LocationID"),new Link("ResultLocationID","Locations","LocationID"),new Link("CoreImportBasicLocationReviewID","CoreImportBasicLocationReviews","CoreImportBasicLocationReviewID"),new Link("SameAsLocationID","Locations","LocationID")), + new("CoreImportBasicLocationEvidence","CoreImportBasicLocationEvidenceID",new Link("CoreImportBasicLocationCandidateID","CoreImportBasicLocationCandidates","CoreImportBasicLocationCandidateID"),new Link("SceneID","Scenes","SceneID"),new Link("ChapterID","Chapters","ChapterID")), new("SceneAssetSuggestions","SceneAssetSuggestionID",new Link("SceneID","Scenes","SceneID"),new Link("AssetID","StoryAssets","StoryAssetID")), new("SceneCharacterSuggestions","SceneCharacterSuggestionID",new Link("CharacterID","Characters","CharacterID"),new Link("SceneID","Scenes","SceneID")), new("SceneLocationSuggestions","SceneLocationSuggestionID",new Link("LocationID","Locations","LocationID"),new Link("SceneID","Scenes","SceneID")), diff --git a/PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql b/PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql new file mode 100644 index 00000000..418a2def --- /dev/null +++ b/PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql @@ -0,0 +1,393 @@ +-- Version 1.3 additive retained Core Import location review choices and evidence. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.ProjectBackup_PersistentState_List @ProjectID int +AS +BEGIN + SET NOCOUNT ON; + SELECT * FROM dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID ORDER BY ManuscriptDocumentID; + SELECT * FROM dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID ORDER BY SceneID; + SELECT * FROM dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID ORDER BY ChapterID; + SELECT * FROM dbo.WritingPlans WHERE ProjectID=@ProjectID ORDER BY WritingPlanID; + SELECT i.* FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID ORDER BY i.WritingScheduleItemID; + SELECT a.* FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY a.CharacterAliasID; + SELECT a.* FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID ORDER BY a.AssetAliasID; + SELECT a.* FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID ORDER BY a.LocationAliasID; + SELECT * FROM dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID ORDER BY AuthorPlotSeedID; + SELECT * FROM dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID ORDER BY ContinuityWarningAcknowledgementID; + SELECT x.* FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID ORDER BY x.PlotEventID,x.PlotLineID; + SELECT x.* FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneAssetID; + SELECT x.* FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneLocationID; + + SELECT * FROM dbo.CharacterImages WHERE ProjectID=@ProjectID ORDER BY CharacterImageID; + SELECT * FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID ORDER BY OnboardingManuscriptBuildID; + SELECT m.* FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryChapterKey; + SELECT m.* FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporarySceneKey; + SELECT m.* FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryCharacterKey; + + SELECT x.* FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneAssetSuggestionID; + SELECT x.* FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneCharacterSuggestionID; + SELECT x.* FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneLocationSuggestionID; + SELECT x.* FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneID; + SELECT * FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID ORDER BY CoreImportBasicLocationReviewID; + SELECT c.* FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID ORDER BY c.CoreImportBasicLocationCandidateID; + SELECT e.* FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID ORDER BY e.CoreImportBasicLocationEvidenceID; +END; +GO + +CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson + @ProjectID int, + @SourceRestorePointID int = NULL, + @SafetyRestorePointID int = NULL, + @JsonData nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF ISNULL(ISJSON(@JsonData), 0) <> 1 + THROW 51001, 'Restore JSON is invalid.', 1; + + IF ISNULL(JSON_VALUE(@JsonData, '$.Format'), N'') <> N'PlotDirector.ProjectBackup' + THROW 51002, 'Restore JSON format is not recognised.', 1; + + IF ISNULL(JSON_VALUE(@JsonData, '$.FormatVersion'), N'') NOT IN (N'1.0', N'1.1', N'1.2', N'1.3') + THROW 51003, 'Restore JSON format version is not supported.', 1; + + IF ISNULL(@ProjectID,0)<=0 OR ISNULL(TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')),-1) <> @ProjectID + THROW 51004, 'Restore point does not belong to this project.', 1; + + DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY); + INSERT INTO @RestoreTables (TableName) + VALUES + (N'CoreImportBasicLocationReviews'), + (N'CoreImportBasicLocationCandidates'), + (N'CoreImportBasicLocationEvidence'), + (N'SceneAssetSuggestions'), + (N'SceneCharacterSuggestions'), + (N'SceneLocationSuggestions'), + (N'SceneTextStatistics'), + (N'OnboardingManuscriptBuilds'), + (N'OnboardingManuscriptBuildChapterMap'), + (N'OnboardingManuscriptBuildSceneMap'), + (N'OnboardingManuscriptBuildCharacterMap'), + (N'CharacterImages'), (N'WordCompanionSceneAssets'), (N'WordCompanionSceneLocations'), (N'ManuscriptDocuments'), (N'SceneManuscriptSources'), (N'ManuscriptStructuralChapterSources'), (N'WritingPlans'), (N'WritingScheduleItems'), (N'CharacterAliases'), (N'AssetAliases'), (N'LocationAliases'), (N'AuthorPlotSeeds'), (N'ContinuityWarningAcknowledgements'), (N'PlotEventTargetPlotLines'), + (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'), + (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'), + (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'), + (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'), + (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'), + (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'), + (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'), + (N'MapReferenceImages'), (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'), + (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'), + (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'), + (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'), + (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'), + (N'ScenarioWarnings'); + + IF JSON_VALUE(@JsonData,'$.FormatVersion')<>N'1.3' AND EXISTS(SELECT 1 FROM dbo.CharacterImages WHERE ProjectID=@ProjectID) + THROW 51006,'This older restore point does not include the existing character gallery. Restore was aborted without changing it.',1; + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID) + AND JSON_QUERY(@JsonData,'$.Data.OnboardingManuscriptBuilds') IS NULL + THROW 51007,'This older restore point does not include existing Core Import build history. Restore was aborted without changing it.',1; + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID + AND (Status NOT IN (N'Built',N'Complete',N'Completed',N'Failed',N'Cancelled') + OR (Status=N'Built' AND ISNULL(MarkerStatus,N'') NOT IN (N'UserConfirmedSave',N'Completed',N'Complete')))) + THROW 51008,'Core Import is unfinished for this project. Complete or cancel it before restoring.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneAssetSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneCharacterSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.SceneLocationSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID) + THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationReviews') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID) + THROW 51010,'This older restore point omits existing Core Import location review history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationCandidates') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID) + THROW 51010,'This older restore point omits existing Core Import location choices. Restore was aborted without changing them.',1; + IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationEvidence') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID) + THROW 51010,'This older restore point omits existing Core Import location evidence. Restore was aborted without changing it.',1; + BEGIN TRANSACTION; + DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0); + + + DECLARE @TableName sysname; + DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN DisableCursor; + FETCH NEXT FROM DisableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;'; + EXEC (@DisableSql); + FETCH NEXT FROM DisableCursor INTO @TableName; + END + CLOSE DisableCursor; + DEALLOCATE DisableCursor; + + DELETE e FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID; + DELETE c FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID; + DELETE FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID; + DELETE x FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE m FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID; + DELETE FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID; + DELETE FROM dbo.CharacterImages WHERE ProjectID=@ProjectID; + DELETE x FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE x FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID; + DELETE i FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID; + DELETE dbo.WritingPlans WHERE ProjectID=@ProjectID; + DELETE dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID; + DELETE dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID; + DELETE a FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID; + DELETE a FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID; + DELETE a FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID; + DELETE x FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID; + DELETE dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID; + DELETE dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID; + DELETE dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID; + + DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID; + DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID; + DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID; + DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID; + DELETE dbo.MapReferenceImages WHERE ProjectID=@ProjectID; + UPDATE dbo.UserFile SET IsDeleted=1,DeletedDateUTC=SYSUTCDATETIME() WHERE ProjectID=@ProjectID AND EntityType=N'MapReferenceImage'; + + DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID; + DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID; + + DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + + DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo + INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID + INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID + INNER JOIN dbo.Books b ON b.BookID = c.BookID + WHERE b.ProjectID = @ProjectID; + + DELETE sd FROM dbo.SceneDependencies sd + LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID + LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID + LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID + LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID + LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID + LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID + WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID; + + DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID; + DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID; + DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID; + DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID; + + DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID; + DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID; + DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID; + + DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID; + DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID; + + DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID; + DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID; + + DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID; + DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID; + + DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID; + DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID; + + DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID; + DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID; + + DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID; + DELETE FROM dbo.Books WHERE ProjectID = @ProjectID; + DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID; + + UPDATE p + SET ProjectName = src.ProjectName, + Description = src.Description, + CreatedDate = src.CreatedDate, + UpdatedDate = SYSUTCDATETIME(), + CreatedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedByUserID ELSE p.CreatedByUserID END, + ModifiedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedByUserID ELSE p.ModifiedByUserID END, + CreatedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedDateUTC ELSE p.CreatedDateUTC END, + ModifiedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedDateUTC ELSE p.ModifiedDateUTC END, + IsArchived = src.IsArchived, + ArchivedDate = src.ArchivedDate, + ArchivedReason = src.ArchivedReason + FROM dbo.Projects p + CROSS APPLY OPENJSON(@JsonData, '$.Project') + WITH + ( + ProjectID int '$.ProjectID', + ProjectName nvarchar(200) '$.ProjectName', + Description nvarchar(max) '$.Description', + CreatedDate datetime2 '$.CreatedDate', + CreatedByUserID int '$.CreatedByUserID', + ModifiedByUserID int '$.ModifiedByUserID', + CreatedDateUTC datetime2 '$.CreatedDateUTC', + ModifiedDateUTC datetime2 '$.ModifiedDateUTC', + IsArchived bit '$.IsArchived', + ArchivedDate datetime2 '$.ArchivedDate', + ArchivedReason nvarchar(1000) '$.ArchivedReason' + ) src + WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1; + EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterImages',N'$.Data.CharacterImages',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0; + + -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography. + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ProjectID int '$.ProjectID') WHERE ProjectID IS NULL OR ProjectID<>@ProjectID) THROW 51005,'Reference images cross project boundaries.',1; + INSERT dbo.MapReferenceImages(ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,ImageData) + SELECT x.ImageID,@ProjectID,x.OriginalFileName,x.ContentType,x.Width,x.Height,CAST(N'' AS xml).value('xs:base64Binary(sql:column("x.ImageData"))','varbinary(max)') + FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ImageID uniqueidentifier '$.ImageID',OriginalFileName nvarchar(200) '$.OriginalFileName',ContentType nvarchar(40) '$.ContentType',Width int '$.Width',Height int '$.Height',ImageData nvarchar(max) '$.ImageData') x; + DECLARE @ImageOwner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID); + INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath) + SELECT @ImageOwner,@ProjectID,N'MapReferenceImage',@ProjectID,CONVERT(nvarchar(36),ImageID)+N'.webp',OriginalFileName,ContentType,FileSizeBytes,N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),ImageID) FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID)) + THROW 51005,'Map backup contains features outside this project.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID) + OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID) + THROW 51005,'Map hierarchy or Location links cross projects.',1; + IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n + WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID) + OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID) + OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@ProjectID AND s.SceneID IN(n.FromSceneID,n.ToSceneID))<>2 + OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path'))) + THROW 51005,'Journey annotations cross project or map boundaries.',1; + EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0; + IF EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND (ISJSON(m.AppearanceJson)<>1 OR ISJSON(m.ReferenceJson)<>1 OR (JSON_VALUE(m.ReferenceJson,'$.imageID') IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages i WHERE i.ProjectID=@ProjectID AND i.ImageID=TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.ReferenceJson,'$.imageID')))))) THROW 51005,'Invalid map appearance or foreign reference image.',1; + UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID; + + EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptDocuments',N'$.Data.ManuscriptDocuments',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneManuscriptSources',N'$.Data.SceneManuscriptSources',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptStructuralChapterSources',N'$.Data.ManuscriptStructuralChapterSources',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'WritingPlans',N'$.Data.WritingPlans',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'WritingScheduleItems',N'$.Data.WritingScheduleItems',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAliases',N'$.Data.CharacterAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AssetAliases',N'$.Data.AssetAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'LocationAliases',N'$.Data.LocationAliases',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'AuthorPlotSeeds',N'$.Data.AuthorPlotSeeds',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarningAcknowledgements',N'$.Data.ContinuityWarningAcknowledgements',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'PlotEventTargetPlotLines',N'$.Data.PlotEventTargetPlotLines',@JsonData,@ProjectID,0; + + EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneAssets',N'$.Data.WordCompanionSceneAssets',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneLocations',N'$.Data.WordCompanionSceneLocations',@JsonData,@ProjectID,0; + + INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath) + SELECT @ImageOwner,@ProjectID,x.EntityType,x.EntityID,x.RestoredFileName,x.OriginalFileName,x.ContentType,x.FileSizeBytes,x.RestoredPath + FROM OPENJSON(@JsonData,'$.Files') WITH( + EntityType nvarchar(80) '$.EntityType',EntityID int '$.EntityID',RestoredFileName nvarchar(260) '$.RestoredFileName', + OriginalFileName nvarchar(260) '$.OriginalFileName',ContentType nvarchar(200) '$.ContentType', + FileSizeBytes bigint '$.FileSizeBytes',RestoredPath nvarchar(1000) '$.RestoredPath') x + WHERE x.RestoredPath LIKE N'/uploads/%'; + + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuilds',N'$.Data.OnboardingManuscriptBuilds',@JsonData,@ProjectID,1; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildChapterMap',N'$.Data.OnboardingManuscriptBuildChapterMap',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildSceneMap',N'$.Data.OnboardingManuscriptBuildSceneMap',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildCharacterMap',N'$.Data.OnboardingManuscriptBuildCharacterMap',@JsonData,@ProjectID,0; + + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetSuggestions',N'$.Data.SceneAssetSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacterSuggestions',N'$.Data.SceneCharacterSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneLocationSuggestions',N'$.Data.SceneLocationSuggestions',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'SceneTextStatistics',N'$.Data.SceneTextStatistics',@JsonData,@ProjectID,0; + + EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationReviews',N'$.Data.CoreImportBasicLocationReviews',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationCandidates',N'$.Data.CoreImportBasicLocationCandidates',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationEvidence',N'$.Data.CoreImportBasicLocationEvidence',@JsonData,@ProjectID,0; + + DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables; + OPEN EnableCursor; + FETCH NEXT FROM EnableCursor INTO @TableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;'; + EXEC (@EnableSql); + FETCH NEXT FROM EnableCursor INTO @TableName; + END + CLOSE EnableCursor; + DEALLOCATE EnableCursor; + + IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL + BEGIN + INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes) + VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.'); + END; + + COMMIT TRANSACTION; +END; +GO