using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; internal static class ImportProgressNavigationTests { private sealed class Capture : IManuscriptCaptureRepository { public ManuscriptScanPreview? Saved;public int Clears; public Task Save(ManuscriptScanPreview p){Saved=p;return Task.CompletedTask;} public Task Get(int user,Guid? preview=null,int? onboarding=null)=>Task.FromResult(Saved?.UserID==user&&(!preview.HasValue||Saved.PreviewID==preview)&&(!onboarding.HasValue||Saved.OnboardingID==onboarding)?Saved:null); public Task Clear(int user,int onboarding){Clears++;throw new Exception("Navigation must not clear a capture");} public Task CompleteBuild(int user,Guid preview)=>Task.CompletedTask; public Task GetAnalysis(int user,Guid preview,string hash)=>Task.FromResult(null); public Task SaveAnalysis(int user,Guid preview,string hash,string result)=>Task.CompletedTask; } public static async Task Run() { var state=new UserOnboardingState{UserID=7,UserOnboardingStateID=8,ProjectID=9,BookID=10,WritingJourney=WritingJourneyValues.ManuscriptMostlyComplete,WritingSoftware=WritingSoftwareValues.MicrosoftWord,CurrentStep=OnboardingSteps.NextPathPreview}; var calls=new List();var onboarding=NativeWorkflowTests.Proxy((n,a)=>{calls.Add(n);return n=="GetAsync"?Task.FromResult(state):throw new Exception("Unexpected onboarding mutation: "+n);}); var user=NativeWorkflowTests.Proxy((n,a)=>n=="get_UserId"?(int?)7:throw new Exception(n)); bool optional=false,locationsDone=false,owner=true; var runs=NativeWorkflowTests.Proxy((n,a)=>n switch{ "ListActiveBookRunSummariesForUserAsync"=>(object)Task.FromResult>(optional?[new(){UserID=7,ProjectID=9,BookID=10,BookTitle="Fixture",PendingRunCount=1,Status="Pending"}]:[]), "ListRunsByBookForUserAsync"=>Task.FromResult>([]),_=>throw new Exception(n)}); var books=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){BookID=10,ProjectID=9,BookTitle="Fixture"})); var projects=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(owner?new(){ProjectID=9,AccessRole="Owner"}:null)); OnboardingManuscriptBuildResult? built=null; var builds=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(built)); var locations=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(locationsDone)); var capture=new Capture();using var provider=new ServiceCollection().AddSingleton(capture).BuildServiceProvider(); ManuscriptScanPreviewStore Store()=>new(provider.GetRequiredService(),NullLogger.Instance); var scans=Store();StoryIntelligenceGlobalProgressService Progress()=>new(user,runs,onboarding,scans,builds,books,locations,projects); var started=await scans.StartAsync(7,8,9,10);await scans.ProgressAsync(7,new(){OnboardingID=8,Message="Reading paragraphs",PercentComplete=42}); var first=await Progress().GetForCurrentUserAsync();var second=await Progress().GetForCurrentUserAsync(); Check(first.HasActiveWork&&first.CoreImport?.Stage=="Scanning Word"&&second.CoreImport?.PercentComplete==42&&(await scans.GetStateAsync(7,8)).ScanID==started.ScanID,"navigation away and refresh keep the same running Word scan and expose it through existing global progress"); var ctor=typeof(OnboardingService).GetConstructors().Single();var deps=new Dictionary{{typeof(IOnboardingRepository),onboarding},{typeof(ICurrentUserService),user},{typeof(IManuscriptScanPreviewStore),scans},{typeof(IProjectRepository),projects},{typeof(IBookRepository),books}}; var service=(OnboardingService)ctor.Invoke(ctor.GetParameters().Select(p=>deps.GetValueOrDefault(p.ParameterType)).ToArray()); await service.StartManuscriptImportSetupAsync();await service.BeginManuscriptImportForBookAsync(9,10);Check(calls.All(c=>c=="GetAsync")&&capture.Clears==0&&(await scans.GetStateAsync(7,8)).ScanID==started.ScanID,"global and book Import actions resume unfinished book without resetting preferences, scan ID or capture"); var preview=new ManuscriptScanPreview{UserID=7,OnboardingID=8,ProjectID=9,BookID=10,Source="NativeWordCompanion",ChapterCount=2};await scans.CompleteAsync(7,preview); Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl=="/onboarding/scan-review?previewId="+preview.PreviewID.ToString("D"),"capture completion keeps global indicator visible and returns to exact chapter-review preview"); scans=Store();Check((await Progress().GetForCurrentUserAsync()).CoreImport?.Stage=="Review chapters","reopening restores accepted capture navigation from existing durable repository"); var review=await scans.GetReviewAsync(7,preview.PreviewID);await scans.SaveReviewAsync(7,new(){PreviewID=preview.PreviewID,Status=ManuscriptScanReviewStatuses.ReadyToImport}); await scans.BuildProgressAsync(7,preview.PreviewID,"Detecting chapter scenes",38); Check((await Progress().GetForCurrentUserAsync()).CoreImport is {Stage:"Detecting scenes",PercentComplete:38},"existing in-flight scene detection progress survives page navigation without starting another build"); await scans.BuildProgressAsync(7,preview.PreviewID,"Built",100,new(){BookID=10});built=new(){BookID=10,ProjectID=9}; Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl.Contains("scan-locations")==true,"core import returns to required location review after structure build");locationsDone=true; Check((await Progress().GetForCurrentUserAsync()).CoreImport?.ResumeUrl.Contains("scan-characters")==true,"core import remains visible until character review and durable completion"); state.OnboardingCompletedUtc=DateTime.UtcNow; Check(!(await Progress().GetForCurrentUserAsync()).HasActiveWork,"genuine core completion removes core indicator independently of optional analysis");optional=true; var ai=await Progress().GetForCurrentUserAsync();Check(ai.HasActiveWork&&ai.CoreImport==null&&ai.Books.Count==1,"optional Story Intelligence retains existing global strip and book navigation after core completion"); state.OnboardingCompletedUtc=null;owner=false;Check((await Progress().GetForCurrentUserAsync()).CoreImport==null,"revoked project permission does not expose a stale core import"); } private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);} }