PlotDirector/PlotLine.Tests/CoreImportDatabaseTests.cs

91 lines
12 KiB
C#

using System.Reflection;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class CoreImportDatabaseTests
{
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class {var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy;}
public static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int owner,int other,int project)
{
using var db=factory.CreateConnection();
Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Core fixtures require the verified synthetic database.");
await db.ExecuteAsync("IF NOT EXISTS(SELECT 1 FROM dbo.RevisionStatuses WHERE StatusName=N'Planned') INSERT dbo.RevisionStatuses(StatusName,SortOrder) VALUES(N'Planned',0);");
var book=await db.QuerySingleAsync<int>("dbo.Book_Save",new{BookID=0,ProjectID=project,BookTitle="Core source text Ω",BookNumber=20,UsesExplicitScenes=true},commandType:System.Data.CommandType.StoredProcedure);
var existingCharacter=await db.ExecuteScalarAsync<int>("SELECT TOP(1) CharacterID FROM dbo.Characters WHERE ProjectID=@project ORDER BY CharacterID",new{project});
var source=string.Concat(Enumerable.Repeat("“Hello”—雪 café 🖋. Dialogue and plain source text.\r\n\r\n",10000));
var sourceWords=source.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
var request=new OnboardingManuscriptBuildRequest {
PreviewID=Guid.NewGuid(),ProjectID=project,BookID=book,DocumentGuid=Guid.NewGuid(),
Chapters=[new(){TemporaryChapterKey="chapter-2",Title="Second core chapter 雨",SortOrder=2,WordCount=0},new(){TemporaryChapterKey="chapter-1",Title="First core chapter Ω",SortOrder=1,WordCount=sourceWords}],
Scenes=[new(){TemporarySceneKey="scene-2",TemporaryChapterKey="chapter-1",Title="Second core scene 雪",SortOrder=2,WordCount=0},new(){TemporarySceneKey="scene-1",TemporaryChapterKey="chapter-1",Title="First core scene Ω",SortOrder=1,WordCount=sourceWords},new(){TemporarySceneKey="scene-3",TemporaryChapterKey="chapter-2",Title="Empty core scene café",SortOrder=1,WordCount=0}],
Characters=[new(){TemporaryCharacterKey="known",Name="Existing synthetic narrator",ExistingCharacterID=existingCharacter},new(){TemporaryCharacterKey="new",Name="New core character 雨"}]
};
var builds=new OnboardingBuildRepository(factory);
Check(await builds.BuildAsync(other,request) is null,"Another author cannot build into this project.");
var result=await builds.BuildAsync(owner,request) ?? throw new InvalidOperationException("Core materialization returned no result.");
Check(result.ChapterMappings.Count==2 && result.SceneMappings.Count==3 && result.CharacterMappings.Count==2,"Core materialization returns every canonical mapping.");
var again=(await builds.BuildAsync(owner,request))!;
Check(again.AlreadyBuilt && again.BuildID==result.BuildID && again.SceneMappings.Select(item=>item.SceneID).SequenceEqual(result.SceneMappings.Select(item=>item.SceneID)),"Repeated preview build is idempotent and preserves scene identities.");
Check(await builds.GetByPreviewAsync(other,request.PreviewID) is null,"Build provenance does not cross authors.");
var chapter=result.ChapterMappings.Single(item=>item.TemporaryChapterKey=="chapter-1").ChapterID;
var first=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-1").SceneID;
var second=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-2").SceneID;
var third=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-3").SceneID;
var secondChapter=result.ChapterMappings.Single(item=>item.TemporaryChapterKey=="chapter-2").ChapterID;
const string paragraphMap="[{\"paragraphIndex\":0,\"start\":0,\"length\":50},{\"paragraphIndex\":1,\"start\":50,\"length\":0}]";
await builds.SaveStructuralChapterSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SourceText=source,SourceWordCount=sourceWords,SourceCharacterCount=source.Length,ParagraphMapJson=paragraphMap,StructuralParsedJson="{\"summary\":\"Structural intent Ω\"}",DefaultPovName="New core character 雨",ExplicitNarratorName="New core character 雨"});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SceneID=first,SourceText=source,SourceWordCount=sourceWords,SourceCharacterCount=source.Length,SourceStartParagraph=1,SourceEndParagraph=20000,WordStartParagraphIndex=0,WordEndParagraphIndex=19999});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SceneID=second,SourceText="",SourceWordCount=0,SourceCharacterCount=0,SourceStartParagraph=20001,SourceEndParagraph=20001,WordStartParagraphIndex=20000,WordEndParagraphIndex=20000});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=secondChapter,SceneID=third,SourceText="Empty chapter source 雨",SourceWordCount=4,SourceCharacterCount=22,SourceStartParagraph=1,SourceEndParagraph=1,WordStartParagraphIndex=20001,WordEndParagraphIndex=20001});
var saved=await builds.ListSceneManuscriptSourcesByBookAsync(book);
Check(saved.Count==3 && saved.Single(item=>item.SceneID==first).SourceText==source && saved.Single(item=>item.SceneID==second).SourceText=="","Core source persistence retains exact long Unicode/CRLF and empty text.");
await builds.MarkMarkerSyncCompletedAsync(result.BuildID,"UserConfirmedSave","Synthetic marker completion; no desktop Word used.");
var current=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)owner,"get_IsAuthenticated"=>true,_=>null});
var activity=Proxy<IProjectActivityService>((name,args)=>name=="RecordAsync"?Task.CompletedTask:throw new NotSupportedException(name));
var backups=new ProjectBackupRepository(factory);var export=new ProjectExportService(backups,activity,current,NullLogger<ProjectExportService>.Instance,files);
var points=new ProjectRestorePointRepository(factory);var pointService=new ProjectRestorePointService(new ProjectRepository(factory),export,points,NullLogger<ProjectRestorePointService>.Instance);
var point=(await pointService.CreateManualAsync(project,"Core source baseline","Synthetic core workflow"))!;
await db.ExecuteAsync("UPDATE dbo.SceneManuscriptSources SET SourceText=N'Changed synthetic source' WHERE SceneID=@first",new{first});
var restore=new ProjectRestoreService(points,pointService,NullLogger<ProjectRestoreService>.Instance,files);
var restored=await restore.RestoreAsync(project,point.ProjectRestorePointID);
Check(restored.Succeeded,"A project with completed Core Import provenance must restore, not fail against retained build-map foreign keys.");
Check((await builds.ListSceneManuscriptSourcesByBookAsync(book)).Single(item=>item.SceneID==first).SourceText==source,"Same-project restore recovers long manuscript source text.");
Check((await builds.GetByPreviewAsync(owner,request.PreviewID))?.BuildID==result.BuildID,"Same-project restore preserves completed build provenance.");
var portable=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(portable);
var coreBuild=portable.Data.OnboardingManuscriptBuilds.Single(build=>build.PreviewID==request.PreviewID);
Check(coreBuild.MarkerStatus=="UserConfirmedSave" && portable.Data.OnboardingManuscriptBuildSceneMap.Count(map=>map.OnboardingManuscriptBuildID==coreBuild.OnboardingManuscriptBuildID)==3,"Backup includes completed build state and all scene mappings.");
async Task ExpectRestoreRefusal(string json,int number)
{
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=json},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Unsafe restore unexpectedly succeeded."); }
catch(Microsoft.Data.SqlClient.SqlException ex) when(ex.Number==number) { }
Check((await builds.ListSceneManuscriptSourcesByBookAsync(book)).Single(item=>item.SceneID==first).SourceText==source,"Refused restore must retain source text.");
}
var oldShape=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(portable))!;
oldShape["Data"]!.AsObject().Remove("OnboardingManuscriptBuilds");
await ExpectRestoreRefusal(oldShape.ToJsonString(),51007);
await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET MarkerStatus=N'Pending' WHERE OnboardingManuscriptBuildID=@id",new{id=result.BuildID});
await ExpectRestoreRefusal(JsonSerializer.Serialize(portable),51008);
await builds.MarkMarkerSyncCompletedAsync(result.BuildID,"UserConfirmedSave","Synthetic marker completion after refusal test.");
coreBuild.MarkerStatus="Pending"; // Deliberately import an unfinished snapshot; the original DB remains completed.
var importing=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)other,"get_IsAuthenticated"=>true,_=>null});
var subscription=Proxy<ISubscriptionService>((name,args)=>name switch {"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),"ReserveBookSlotsAsync"=>Task.FromResult(new BookSlotReservation{Allowed=true}),"CanUploadFileAsync"=>Task.FromResult(StorageLimitResult.AllowedResult(0,long.MaxValue)),_=>throw new NotSupportedException(name)});
var importer=new ImportService(new ImportRepository(factory),importing,subscription,NullLogger<ImportService>.Instance,files);
var imported=await importer.ImportAsync(new(){JsonText=JsonSerializer.Serialize(portable),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(imported.Succeeded,"Copy of Core Import provenance must import: "+imported.TechnicalDetail);
var copied=(await backups.GetProjectBackupAsync(imported.ProjectID!.Value,other))!;
var copiedBook=copied.Data.Books.Single(item=>item.BookTitle=="Core source text Ω");
var copiedBuild=copied.Data.OnboardingManuscriptBuilds.Single(item=>item.BookID==copiedBook.BookID);
Check(copiedBuild.PreviewID!=request.PreviewID && copiedBuild.UserID==other && copiedBuild.Status=="Cancelled" && copiedBuild.MarkerStatus=="Cancelled","Copied workflow has a new preview/actor and unfinished operations become cancelled history.");
var copiedScene=copied.Data.Scenes.Single(item=>item.SceneTitle=="First core scene Ω");
Check(copied.Data.OnboardingManuscriptBuildSceneMap.Any(map=>map.OnboardingManuscriptBuildID==copiedBuild.OnboardingManuscriptBuildID&&map.SceneID==copiedScene.SceneID) && copied.Data.SceneManuscriptSources.Single(item=>item.SceneID==copiedScene.SceneID).SourceText==source,"Copied canonical mappings and exact manuscript text retained.");
Check(copied.Data.ManuscriptDocuments.Single(item=>item.BookID==copiedBook.BookID).IsActive==false,"Copied Core Import cannot activate the original Word binding.");
Check((await builds.GetByPreviewAsync(owner,request.PreviewID))?.MarkerStatus=="UserConfirmedSave","Copy did not alter the original completed marker history.");
Console.WriteLine("PASS Core Import SQL build/source protocol: canonical mapping, preview retry, author isolation, long Unicode/CRLF/empty source persistence and completed provenance restore. Parser, model calls and desktop marker sync are separate boundaries.");
}
}