Repair Word structure import for current chapters and safe retry responses

This commit is contained in:
Nick Beckley 2026-11-04 02:37:35 +00:00
parent 6332522568
commit 168ff4d8e0
9 changed files with 542 additions and 15 deletions

View File

@ -10,7 +10,7 @@ Search,Export,html; markdown/md; text/txt,Project-scoped search results,ExportsC
Project backup download/import-as-new,Export + import,PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2,Portable serialized project data and active uploaded files,ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson,65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download,Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply
Saved restore point create/download/restore,Export + restore,Same versioned project backup JSON,Recover a prior state inside the same project,ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController,Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership,Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care
Legacy structured JSON package,Import,PackageVersion 1.0 JSON,Create planning entities from explicitly structured external data,ImportsController; ImportService; ImportRepository,Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing,One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
Word manuscript structure API,Import + sync,Word Companion JSON structure/binding protocol,Create or sync Word-linked chapters/scenes and word counts,WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs,Pending focused isolated SQL verification; existing harness checks are separate,Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
Word manuscript structure API,Import + sync,Word Companion JSON structure/binding protocol,Create or sync Word-linked chapters/scenes and word counts,WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs,Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions,Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
Core Import from current Word document,Import,Chunked paragraph scan + approved structure/marker protocol,Retain source paragraphs and materialize approved canonical book structure,WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository,Existing 405-check parser/review/source coverage; isolated SQL workflow verification pending,External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
Story Intelligence reviewed Characters,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Locations,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work

1 Workflow Direction Formats IntendedPurpose Implementation Verification Limits
10 Project backup download/import-as-new Export + import PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2 Portable serialized project data and active uploaded files ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson 65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply
11 Saved restore point create/download/restore Export + restore Same versioned project backup JSON Recover a prior state inside the same project ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care
12 Legacy structured JSON package Import PackageVersion 1.0 JSON Create planning entities from explicitly structured external data ImportsController; ImportService; ImportRepository Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
13 Word manuscript structure API Import + sync Word Companion JSON structure/binding protocol Create or sync Word-linked chapters/scenes and word counts WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs Pending focused isolated SQL verification; existing harness checks are separate Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
14 Core Import from current Word document Import Chunked paragraph scan + approved structure/marker protocol Retain source paragraphs and materialize approved canonical book structure WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository Existing 405-check parser/review/source coverage; isolated SQL workflow verification pending External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
15 Story Intelligence reviewed Characters Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
16 Story Intelligence reviewed Locations Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work

View File

@ -208,3 +208,13 @@ Workflow inventory: `2026-11-03-phase2-transfer-workflows.csv` records 28 export
### Legacy repair verification checkpoint
Final legacy SQL run passed (`/tmp/plotdirector-phase2-legacy-after.log`), including optional version and case-insensitive detection, BOM decoding, edited-text precedence, all top-level planning entity groups and the real downloadable sample. The portable-backup matrix was rerun with shared reference states and uppercase root keys: 1,021 source values, 982 copied values and 985 in-place values across 65 persistent collections; twelve files, storage limits/ownership, safety backups and SQL failure cleanup still pass (`/tmp/plotdirector-phase2-transfer-files-final-legacy.log`). Broad harness passed again: 405 checks, exit 0 (`/tmp/plotdirector-phase2-tests-legacy-final.log`). Build zero warnings/errors. Migration 218 only exists in the synthetic database; no Development changes/deployment. Remaining Word/core-import and unrepresented persisted SI scope remain explicit, not treated as completed.
### Current Word structure API repair group (uncommitted)
Real HTTP/SQL reproduction found the older Word structure import unusable under the current scene model: its first-scene branch assumed chapter insertion created a placeholder, then attempted SceneWorkflow with a null SceneID. Forward-only migration 219 now creates a scene when none exists, resets the scene variable per iteration, and marks a successful explicit-scene import accordingly. No historical migration was edited.
Replacement confirmation returned HTTP 500 because the procedure deliberately returns only its result header, while the repository unconditionally read a second result set. It now reads the document only when another result remains. After the SQL repair, 201-character titles were demonstrably accepted/truncated and changed book structure; service validation now rejects them before SQL. Null chapter/scene records also returned 500; import and sync now guard malformed nested collections/records. Document-binding conflicts already rolled back replacement changes but surfaced as 500; the expected SQL business error now returns a clear 400 message.
Expanded HTTP/SQL verification passed valid Unicode/order/word counts including an empty scene, canonical document links, read-back, unconfirmed replacement protection, preservation of archived planning records on confirmed replacement, repeated import/sync without duplicate identities, and real binding-conflict rollback. The fixture runs actual controllers/access/subscription filters/services/repositories/SQL, with synthetic identity and entitlement decisions and unused external-service boundaries; no application workers, paid providers, or desktop Word run. Final denied-entitlement case and broad harness are being completed before commit. Evidence: `/tmp/plotdirector-phase2-word-transfer-before.log`, `...-word-transfer-sql-repair.log`, `...-word-transfer-conflict-before.log`, `...-word-transfer-after.log`. Development remains unchanged.
Word structure checkpoint verified: final HTTP/SQL run passed, including a denied fixture entitlement returning 403 without changing the book, other-author/anonymous rejection, repeated sync retaining scene IDs and updated word counts, and confirmed replacement preserving the original archived planning text. The complete 405-check harness passed (exit 0) at `/tmp/plotdirector-phase2-tests-word-transfer.log`; solution build zero warnings/errors. Migration 219 only applied in the synthetic database. Desktop Word and full prose/Core Import remain distinct next work, and no Development deployment has occurred.

View File

@ -73,7 +73,7 @@ if (args.Contains("--maps-story-dev-fixture"))
if(args.Contains("--project-transfer-database"))
{
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only")); }
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only")); }
catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; }
return;
}

View File

@ -18,7 +18,7 @@ internal static class ProjectTransferDatabaseTests
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
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(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false)
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false)
{
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
@ -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"})
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"})
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.");
@ -158,6 +158,11 @@ internal static class ProjectTransferDatabaseTests
await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported.");
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(wordOnly)
{
await WordTransferDatabaseTests.RunAsync(factory,user,importingUser,project);
return;
}
if(legacyOnly)
{
await LegacyImportDatabaseTests.RunAsync(factory,assetFiles,importingUser,user,project);

View File

@ -0,0 +1,150 @@
using System.Collections.Concurrent;
using System.Net;
using System.Reflection;
using System.Security.Claims;
using System.Text.Json;
using Dapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class WordTransferDatabaseTests
{
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,int owner,int other,int project)
{
using var db=factory.CreateConnection();
if(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)throw new InvalidOperationException("Word 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);IF NOT EXISTS(SELECT 1 FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Unknown') INSERT dbo.TimeConfidences(TimeConfidenceName,SortOrder) VALUES(N'Unknown',0);");
var bookNumber=10;
async Task<int> Book(string name)=>await db.QuerySingleAsync<int>("dbo.Book_Save",new{BookID=0,ProjectID=project,BookTitle=name,BookNumber=bookNumber++},commandType:System.Data.CommandType.StoredProcedure);
var featureAllowed=true;
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.WebHost.UseUrls("http://127.0.0.1:0");builder.Logging.ClearProviders();
builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();
builder.Services.AddAuthentication("WordFixture").AddCookie("WordFixture",options=>options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;return Task.CompletedTask;});
builder.Services.AddAuthorization();builder.Services.AddHttpContextAccessor();builder.Services.AddSignalR();
builder.Services.AddSingleton(factory);builder.Services.AddScoped<ICurrentUserService,CurrentUserService>();
builder.Services.AddScoped<IWordCompanionRepository,WordCompanionRepository>();builder.Services.AddScoped<IManuscriptDocumentRepository,ManuscriptDocumentRepository>();builder.Services.AddScoped<IWordCompanionService,WordCompanionService>();
builder.Services.AddSingleton(Proxy<IWordCompanionPresenceService>((name,args)=>throw new NotSupportedException(name)));
builder.Services.AddSingleton(Proxy<INameIntelligenceService>((name,args)=>throw new NotSupportedException(name)));
builder.Services.AddSingleton(Proxy<ISubscriptionService>((name,args)=>name switch {"CanUseFeatureAsync"=>Task.FromResult(new EntitlementDecision{Allowed=featureAllowed,Message="Synthetic entitlement decision"}),"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),_=>throw new NotSupportedException(name)}));
builder.Services.AddScoped<IProjectAccessRepository,ProjectAccessRepository>();builder.Services.AddScoped<IProjectAccessService,ProjectAccessService>();builder.Services.AddScoped<ProjectAccessFilter>();builder.Services.AddScoped<SubscriptionEnforcementFilter>();
builder.Services.AddControllersWithViews(options=>{options.Filters.Add<ProjectAccessFilter>();options.Filters.Add<SubscriptionEnforcementFilter>();}).AddApplicationPart(typeof(WordCompanionController).Assembly);
await using var app=builder.Build();var errors=new ConcurrentQueue<string>();
app.Use(async(context,next)=>{if(int.TryParse(context.Request.Headers["X-Synthetic-Actor"],out var actor)&&(actor==owner||actor==other))context.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,actor.ToString())],"WordFixture"));try{await next();}catch(Exception ex){errors.Enqueue(ex.Message);context.Response.StatusCode=500;await context.Response.WriteAsync("Synthetic Word request failed.");}});
app.UseAuthorization();app.MapControllers();await app.StartAsync();
using var client=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single())};
async Task<HttpResponseMessage> Send(string path,object? payload,int? actor)
{using var request=new HttpRequestMessage(payload is null?HttpMethod.Get:HttpMethod.Post,path);if(actor.HasValue)request.Headers.Add("X-Synthetic-Actor",actor.Value.ToString());if(payload is not null)request.Content=new StringContent(JsonSerializer.Serialize(payload),System.Text.Encoding.UTF8,"application/json");return await client.SendAsync(request);}
WordCompanionManuscriptImportRequest Input(int book)=>new(){ProjectId=project,BookId=book,DocumentGuid=Guid.NewGuid(),BindingVersion=1,Chapters=[new(){Title="Chapter 雨",SortOrder=1,WordCount=400,Scenes=[new(){Title="Scene café 🖋",SortOrder=1,WordCount=400},new(){Title="Empty scene Ω",SortOrder=2,WordCount=0}]},new(){Title="Second chapter Ω",SortOrder=2,WordCount=25,Scenes=[new(){Title="Second chapter scene 雪",SortOrder=1,WordCount=25}]}]};
var failures=new List<string>();
foreach(var item in new (string Label,Action<WordCompanionManuscriptImportRequest> Mutate)[]{
("null chapters",request=>request.Chapters=null!),
("null chapter record",request=>request.Chapters=[null!]),
("null scenes",request=>request.Chapters[0].Scenes=null!),
("null scene record",request=>request.Chapters[0].Scenes=[null!]),
("oversized chapter title",request=>request.Chapters[0].Title=new string('Ω',201)),
("oversized scene title",request=>request.Chapters[0].Scenes[0].Title=new string('雪',201)),
("negative words",request=>request.Chapters[0].Scenes[0].WordCount=-1)})
{
var book=await Book("Invalid Word input fixture");var input=Input(book);item.Mutate(input);
using var response=await Send("/api/word-companion/manuscript/import",input,owner);
if(response.StatusCode!=HttpStatusCode.BadRequest)failures.Add(item.Label+$": HTTP {(int)response.StatusCode}; {errors.LastOrDefault()}");
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@book",new{book})!=0)failures.Add(item.Label+": invalid request changed book structure");
}
var plannedBook=await Book("Planned Word replacement Ω");
var revision=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName=N'Planned'");
var manualChapter=await db.ExecuteScalarAsync<int>("INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,Summary,SortOrder,RevisionStatusID) VALUES(@plannedBook,1,N'Original planned chapter',N'Keep original planning 雨',1,@revision);SELECT CONVERT(int,SCOPE_IDENTITY());",new{plannedBook,revision});
await db.ExecuteAsync("INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,Summary,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) SELECT @manualChapter,1,N'Original planned scene',N'Keep original scene café',1,@revision,(SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY TimeModeID),(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY TimeConfidenceID)",new{manualChapter,revision});
using(var response=await Send("/api/word-companion/manuscript/import",Input(plannedBook),owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Replacement confirmation HTTP "+(int)response.StatusCode+": "+errors.LastOrDefault());
else if(JsonSerializer.Deserialize<WordCompanionManuscriptImportResponse>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})?.RequiresReplaceConfirmation!=true)failures.Add("Existing planning does not require confirmation");
}
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@plannedBook AND IsArchived=0",new{plannedBook})!=1)failures.Add("Unconfirmed replacement changed existing planning");
var validBook=await Book("Valid Word import Ω");var valid=Input(validBook);
featureAllowed=false;
using(var deniedFeature=await Send("/api/word-companion/manuscript/import",valid,owner))if(deniedFeature.StatusCode!=HttpStatusCode.Forbidden)failures.Add("Production subscription filter did not reject a denied fixture entitlement");
featureAllowed=true;
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@validBook",new{validBook})!=0)failures.Add("Denied entitlement changed book data");
using(var denied=await Send("/api/word-companion/manuscript/import",valid,other))if(denied.StatusCode!=HttpStatusCode.NotFound)failures.Add("Other author not rejected");
using(var anonymous=await Send("/api/word-companion/manuscript/import",valid,null))if(anonymous.StatusCode!=HttpStatusCode.Unauthorized)failures.Add("Anonymous import not rejected");
using(var response=await Send("/api/word-companion/manuscript/import",valid,owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add($"Valid Word structure import HTTP {(int)response.StatusCode}: {errors.LastOrDefault()}");
else if(JsonSerializer.Deserialize<WordCompanionManuscriptImportResponse>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})?.Imported!=true)failures.Add("Valid structure import did not report imported");
}
var chapters=(await db.QueryAsync<Chapter>("SELECT * FROM dbo.Chapters WHERE BookID=@validBook AND IsArchived=0 ORDER BY SortOrder,ChapterID",new{validBook})).ToArray();
var scenes=(await db.QueryAsync<Scene>("SELECT s.* FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@validBook AND c.IsArchived=0 AND s.IsArchived=0 ORDER BY c.SortOrder,s.SortOrder,s.SceneID",new{validBook})).ToArray();
if(chapters.Length!=2||scenes.Length!=3)failures.Add($"Word structure differs: {chapters.Length} chapters / {scenes.Length} scenes");
else
{
if(chapters[0].ChapterTitle!="Chapter 雨"||scenes[0].SceneTitle!="Scene café 🖋"||scenes[1].SceneTitle!="Empty scene Ω"||scenes[2].SceneTitle!="Second chapter scene 雪")failures.Add("Word title/order/Unicode differs");
if(scenes.Any(scene=>!scene.IsLinkedToManuscript||scene.ManuscriptDocumentID is null))failures.Add("Word explicit scene binding/default state differs");
var counts=(await db.QueryAsync<int>("SELECT sw.ActualWordCount FROM dbo.SceneWorkflow sw JOIN dbo.Scenes s ON s.SceneID=sw.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@validBook ORDER BY c.SortOrder,s.SortOrder",new{validBook})).ToArray();
if(!counts.SequenceEqual(new[]{400,0,25}))failures.Add("Word counts differ");
}
if(!await db.ExecuteScalarAsync<bool>("SELECT UsesExplicitScenes FROM dbo.Books WHERE BookID=@validBook",new{validBook}))failures.Add("Word imported book is not marked as explicit scenes");
using(var response=await Send("/api/word-companion/manuscript/import",valid,owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Repeated import HTTP "+(int)response.StatusCode+": "+errors.LastOrDefault());
else if(JsonSerializer.Deserialize<WordCompanionManuscriptImportResponse>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})?.Imported!=false)failures.Add("Repeated import duplicated the linked structure");
}
var sync=new WordCompanionSyncManuscriptRequest{DocumentId=valid.DocumentGuid!.Value.ToString("D"),Chapters=valid.Chapters.Select(chapter=>new WordCompanionSyncChapterRequest{Title=chapter.Title,SortOrder=chapter.SortOrder,WordCount=chapter.WordCount,Scenes=chapter.Scenes.Select(scene=>new WordCompanionSyncManuscriptSceneRequest{Title=scene.Title,SortOrder=scene.SortOrder,WordCount=scene.WordCount+(scene.SortOrder==1&&chapter.SortOrder==1?10:0)}).ToArray()}).ToArray()};
foreach(var item in new (string Label,Action<WordCompanionSyncManuscriptRequest> Mutate)[]{
("sync null chapters",request=>request.Chapters=null!),
("sync null chapter",request=>request.Chapters=[null!]),
("sync null scene",request=>request.Chapters[0].Scenes=[null!]),
("sync long title",request=>request.Chapters[0].Scenes[0].Title=new string('雪',201))})
{
var invalid=JsonSerializer.Deserialize<WordCompanionSyncManuscriptRequest>(JsonSerializer.Serialize(sync))!;item.Mutate(invalid);
using var response=await Send($"/api/word-companion/books/{validBook}/sync-manuscript",invalid,owner);
if(response.StatusCode!=HttpStatusCode.BadRequest)failures.Add(item.Label+": not rejected");
}
for(var cycle=0;cycle<2;cycle++)
{
using var response=await Send($"/api/word-companion/books/{validBook}/sync-manuscript",sync,owner);
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Valid/repeated sync failed: "+errors.LastOrDefault());
}
var syncedIds=(await db.QueryAsync<int>("SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@validBook AND c.IsArchived=0 AND s.IsArchived=0 ORDER BY c.SortOrder,s.SortOrder,s.SceneID",new{validBook})).ToArray();
if(!syncedIds.SequenceEqual(scenes.Select(scene=>scene.SceneID)))failures.Add("Repeated sync duplicated or reassigned scene identities");
if(scenes.Length>0 && await db.ExecuteScalarAsync<int>("SELECT ActualWordCount FROM dbo.SceneWorkflow WHERE SceneID=@scene",new{scene=scenes[0].SceneID})!=410)failures.Add("Sync did not retain updated word count");
using(var response=await Send($"/api/word-companion/books/{validBook}/structure",null,owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Read-back structure HTTP failed");
else
{
var read=JsonSerializer.Deserialize<WordCompanionBookStructureResponse>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
if(read.Chapters.Count!=2 || read.Chapters.Sum(chapter=>chapter.Scenes.Count)!=3 || read.Chapters[0].Scenes[0].ActualWords!=410)failures.Add("Structure read-back omitted counts/content");
}
}
var conflict=Input(plannedBook);conflict.ReplacePlanned=true;
conflict.DocumentGuid=await db.ExecuteScalarAsync<Guid>("SELECT TOP(1) DocumentGuid FROM dbo.ManuscriptDocuments WHERE ProjectID=@project AND BookID<>@plannedBook AND IsActive=1 ORDER BY ManuscriptDocumentID",new{project,plannedBook});
using(var response=await Send("/api/word-companion/manuscript/import",conflict,owner))
if(response.StatusCode!=HttpStatusCode.BadRequest)failures.Add("Document binding conflict HTTP "+(int)response.StatusCode+": "+errors.LastOrDefault());
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@plannedBook AND IsArchived=0 AND Summary=N'Keep original planning 雨'",new{plannedBook})!=1 || await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Scenes WHERE ChapterID=@manualChapter AND IsArchived=0 AND Summary=N'Keep original scene café'",new{manualChapter})!=1)failures.Add("Binding conflict did not roll back planned archive changes");
var replacement=Input(plannedBook);replacement.ReplacePlanned=true;
using(var response=await Send("/api/word-companion/manuscript/import",replacement,owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Confirmed replacement failed: "+errors.LastOrDefault());
else
{
var replaced=JsonSerializer.Deserialize<WordCompanionManuscriptImportResponse>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
if(!replaced.Imported||replaced.ArchivedChapters!=1||replaced.ArchivedScenes!=1)failures.Add("Confirmed replacement counts differ");
}
}
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Chapters WHERE ChapterID=@manualChapter AND IsArchived=1 AND Summary=N'Keep original planning 雨'",new{manualChapter})!=1)failures.Add("Replacement lost the archived planning record");
await app.StopAsync();
if(failures.Count>0)throw new InvalidOperationException(string.Join(Environment.NewLine,failures.Distinct()));
Console.WriteLine("PASS Word structure API over real HTTP/SQL: malformed input rejection, author/subscription boundaries, Unicode/order/word counts, empty text, explicit document bindings, confirmation/archive safety, repeated imports/sync and binding-conflict rollback. Desktop Word/prose transfer is separate.");
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.Data.SqlClient;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
@ -242,8 +243,15 @@ public sealed class WordCompanionController(
[HttpPost("manuscript/import")]
public async Task<IActionResult> ImportManuscript(WordCompanionManuscriptImportRequest request)
{
var response = await wordCompanion.ImportManuscriptAsync(request);
return response is null ? BadRequest() : Ok(response);
try
{
var response = await wordCompanion.ImportManuscriptAsync(request);
return response is null ? BadRequest() : Ok(response);
}
catch (SqlException ex) when (ex.Number == 51000)
{
return BadRequest(new { message = ex.Message });
}
}
[HttpPost("manuscript/discover-characters")]

View File

@ -406,7 +406,7 @@ public sealed class WordCompanionRepository(ISqlConnectionFactory connectionFact
return null;
}
var document = await result.ReadSingleOrDefaultAsync<WordCompanionManuscriptDocumentDto>();
var document = result.IsConsumed ? null : await result.ReadSingleOrDefaultAsync<WordCompanionManuscriptDocumentDto>();
return new WordCompanionManuscriptImportResponse
{
Imported = response.Imported,

View File

@ -257,11 +257,12 @@ public sealed class WordCompanionService(
public async Task<WordCompanionSyncManuscriptResponse?> SyncManuscriptAsync(int bookId, WordCompanionSyncManuscriptRequest request)
{
if (bookId <= 0 || request.Chapters.Any(chapter =>
string.IsNullOrWhiteSpace(chapter.Title)
if (bookId <= 0 || request.Chapters is null || request.Chapters.Any(chapter =>
chapter is null || !ValidStructureTitle(chapter.Title)
|| chapter.WordCount < 0
|| chapter.SortOrder is <= 0
|| chapter.Scenes.Any(scene => string.IsNullOrWhiteSpace(scene.Title) || scene.WordCount < 0 || scene.SortOrder is <= 0)))
|| chapter.Scenes is null
|| chapter.Scenes.Any(scene => scene is null || !ValidStructureTitle(scene.Title) || scene.WordCount < 0 || scene.SortOrder is <= 0)))
{
return null;
}
@ -539,18 +540,20 @@ public sealed class WordCompanionService(
return repository.AnalyseManuscriptAsync(RequireUserId(), request);
}
private static bool ValidStructureTitle(string? title)=>!string.IsNullOrWhiteSpace(title) && title.Trim().Length<=200;
public Task<WordCompanionManuscriptImportResponse?> ImportManuscriptAsync(WordCompanionManuscriptImportRequest request)
{
if (request.ProjectId <= 0
|| request.BookId <= 0
|| request.BindingVersion <= 0
|| request.Chapters.Count == 0
|| request.Chapters is null || request.Chapters.Count == 0
|| request.Chapters.Any(chapter =>
string.IsNullOrWhiteSpace(chapter.Title)
|| chapter.SortOrder is <= 0
chapter is null || !ValidStructureTitle(chapter.Title)
|| chapter.SortOrder is null or <= 0
|| chapter.WordCount < 0
|| chapter.Scenes.Count == 0
|| chapter.Scenes.Any(scene => string.IsNullOrWhiteSpace(scene.Title) || scene.SortOrder is <= 0 || scene.WordCount < 0)))
|| chapter.Scenes is null || chapter.Scenes.Count == 0
|| chapter.Scenes.Any(scene => scene is null || !ValidStructureTitle(scene.Title) || scene.SortOrder is null or <= 0 || scene.WordCount < 0)))
{
return Task.FromResult<WordCompanionManuscriptImportResponse?>(null);
}

View File

@ -0,0 +1,351 @@
-- Word structure import must create the first scene when chapters no longer create a placeholder.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WordCompanion_Manuscript_Import
@UserID int,
@ProjectID int,
@BookID int,
@DocumentGuid uniqueidentifier,
@BindingVersion int = 1,
@ReplacePlanned bit = 0,
@StructureJson nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @DocumentGuid IS NULL OR @DocumentGuid = '00000000-0000-0000-0000-000000000000'
SET @DocumentGuid = NEWID();
DECLARE @BookTitle nvarchar(200);
DECLARE @AccessProjectID int;
SELECT @AccessProjectID = b.ProjectID,
@BookTitle = b.BookTitle
FROM dbo.Books b
INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
WHERE b.BookID = @BookID
AND b.ProjectID = @ProjectID
AND b.IsArchived = 0
AND p.IsArchived = 0
AND pua.UserID = @UserID
AND pua.IsActive = 1;
IF @BookTitle IS NULL
RETURN;
DECLARE @LinkedChapterCount int =
(
SELECT COUNT(*)
FROM dbo.Chapters
WHERE BookID = @BookID
AND IsArchived = 0
AND IsLinkedToManuscript = 1
);
IF @LinkedChapterCount > 0
BEGIN
SELECT CAST(0 AS bit) AS Imported,
CAST(0 AS bit) AS RequiresReplaceConfirmation,
N'This Book already contains a linked manuscript.' AS Message,
@ProjectID AS ProjectId,
@BookID AS BookId,
0 AS ChaptersCreated,
0 AS ScenesCreated,
0 AS ArchivedChapters,
0 AS ArchivedScenes;
RETURN;
END;
DECLARE @ChapterCount int = (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID = @BookID AND IsArchived = 0);
IF @ChapterCount > 0 AND @ReplacePlanned = 0
BEGIN
SELECT CAST(0 AS bit) AS Imported,
CAST(1 AS bit) AS RequiresReplaceConfirmation,
N'This Book already contains planned chapters and scenes.' AS Message,
@ProjectID AS ProjectId,
@BookID AS BookId,
0 AS ChaptersCreated,
0 AS ScenesCreated,
0 AS ArchivedChapters,
0 AS ArchivedScenes;
RETURN;
END;
DECLARE @Chapters table
(
ImportChapterIndex int NOT NULL PRIMARY KEY,
Title nvarchar(200) NOT NULL,
SortOrder int NOT NULL,
WordCount int NOT NULL
);
DECLARE @Scenes table
(
ImportChapterIndex int NOT NULL,
ImportSceneIndex int NOT NULL,
Title nvarchar(200) NOT NULL,
SortOrder int NOT NULL,
WordCount int NOT NULL,
PRIMARY KEY (ImportChapterIndex, ImportSceneIndex)
);
INSERT @Chapters (ImportChapterIndex, Title, SortOrder, WordCount)
SELECT CONVERT(int, chapter.[key]) + 1,
LEFT(LTRIM(RTRIM(JSON_VALUE(chapter.value, '$.Title'))), 200),
TRY_CONVERT(int, JSON_VALUE(chapter.value, '$.SortOrder')),
COALESCE(TRY_CONVERT(int, JSON_VALUE(chapter.value, '$.WordCount')), 0)
FROM OPENJSON(@StructureJson) chapter
WHERE NULLIF(LTRIM(RTRIM(JSON_VALUE(chapter.value, '$.Title'))), N'') IS NOT NULL;
INSERT @Scenes (ImportChapterIndex, ImportSceneIndex, Title, SortOrder, WordCount)
SELECT c.ImportChapterIndex,
CONVERT(int, scene.[key]) + 1,
LEFT(LTRIM(RTRIM(JSON_VALUE(scene.value, '$.Title'))), 200),
TRY_CONVERT(int, JSON_VALUE(scene.value, '$.SortOrder')),
COALESCE(TRY_CONVERT(int, JSON_VALUE(scene.value, '$.WordCount')), 0)
FROM @Chapters c
INNER JOIN OPENJSON(@StructureJson) chapter ON CONVERT(int, chapter.[key]) + 1 = c.ImportChapterIndex
CROSS APPLY OPENJSON(chapter.value, '$.Scenes') scene
WHERE NULLIF(LTRIM(RTRIM(JSON_VALUE(scene.value, '$.Title'))), N'') IS NOT NULL;
IF NOT EXISTS (SELECT 1 FROM @Chapters)
RETURN;
IF EXISTS (SELECT 1 FROM @Chapters WHERE SortOrder IS NULL OR SortOrder <= 0 OR WordCount < 0)
RETURN;
IF EXISTS (SELECT 1 FROM @Scenes WHERE SortOrder IS NULL OR SortOrder <= 0 OR WordCount < 0)
RETURN;
IF EXISTS (SELECT 1 FROM @Chapters c WHERE NOT EXISTS (SELECT 1 FROM @Scenes s WHERE s.ImportChapterIndex = c.ImportChapterIndex))
RETURN;
DECLARE @PlannedRevisionStatusID int = (SELECT TOP (1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName = N'Planned' ORDER BY SortOrder);
DECLARE @DefaultTimeModeID int = (SELECT TOP (1) TimeModeID FROM dbo.TimeModes ORDER BY CASE WHEN TimeModeName = N'Unknown' THEN 0 ELSE 1 END, SortOrder, TimeModeID);
DECLARE @DefaultTimeConfidenceID int = (SELECT TOP (1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY CASE WHEN TimeConfidenceName = N'Unknown' THEN 0 ELSE 1 END, SortOrder, TimeConfidenceID);
IF @PlannedRevisionStatusID IS NULL OR @DefaultTimeModeID IS NULL OR @DefaultTimeConfidenceID IS NULL
RETURN;
DECLARE @ImportChapterMap table
(
ImportChapterIndex int NOT NULL PRIMARY KEY,
ChapterID int NOT NULL
);
DECLARE @ImportSceneMap table
(
ImportChapterIndex int NOT NULL,
ImportSceneIndex int NOT NULL,
SceneID int NOT NULL,
PRIMARY KEY (ImportChapterIndex, ImportSceneIndex)
);
DECLARE @ArchivedChapters int = 0;
DECLARE @ArchivedScenes int = 0;
DECLARE @ManuscriptDocumentID int;
DECLARE @LinkedUtc datetime2 = SYSUTCDATETIME();
BEGIN TRANSACTION;
UPDATE dbo.Books SET UsesExplicitScenes=1,UpdatedDate=SYSUTCDATETIME() WHERE BookID=@BookID;
IF @ChapterCount > 0
BEGIN
UPDATE s
SET IsArchived = 1,
ArchivedDate = SYSUTCDATETIME(),
ArchivedReason = N'Replaced by Word Companion manuscript import',
UpdatedDate = SYSUTCDATETIME()
FROM dbo.Scenes s
INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID
WHERE c.BookID = @BookID
AND c.IsArchived = 0
AND s.IsArchived = 0
AND c.IsLinkedToManuscript = 0
AND s.IsLinkedToManuscript = 0;
SET @ArchivedScenes = @@ROWCOUNT;
UPDATE dbo.Chapters
SET IsArchived = 1,
ArchivedDate = SYSUTCDATETIME(),
ArchivedReason = N'Replaced by Word Companion manuscript import',
UpdatedDate = SYSUTCDATETIME()
WHERE BookID = @BookID
AND IsArchived = 0
AND IsLinkedToManuscript = 0;
SET @ArchivedChapters = @@ROWCOUNT;
END;
IF EXISTS
(
SELECT 1
FROM dbo.ManuscriptDocuments
WHERE DocumentGuid = @DocumentGuid
AND IsActive = 1
AND BookID <> @BookID
)
THROW 51000, 'This manuscript document is already linked to another book.', 1;
SELECT @ManuscriptDocumentID = ManuscriptDocumentID
FROM dbo.ManuscriptDocuments
WHERE BookID = @BookID
AND IsActive = 1;
IF @ManuscriptDocumentID IS NULL
BEGIN
INSERT dbo.ManuscriptDocuments (BookID, ProjectID, DocumentGuid, BindingVersion, CreatedByUserID, LastOpenedUtc, LastSyncUtc)
VALUES (@BookID, @ProjectID, @DocumentGuid, @BindingVersion, @UserID, @LinkedUtc, @LinkedUtc);
SET @ManuscriptDocumentID = CAST(SCOPE_IDENTITY() AS int);
END
ELSE
BEGIN
UPDATE dbo.ManuscriptDocuments
SET DocumentGuid = @DocumentGuid,
ProjectID = @ProjectID,
BindingVersion = @BindingVersion,
LastOpenedUtc = @LinkedUtc,
LastSyncUtc = @LinkedUtc
WHERE ManuscriptDocumentID = @ManuscriptDocumentID;
END;
DECLARE @ImportChapterIndex int;
DECLARE @ChapterTitle nvarchar(200);
DECLARE @ChapterSortOrder int;
DECLARE @ChapterID int;
DECLARE @ChapterNumber decimal(9,2);
DECLARE chapter_cursor CURSOR LOCAL FAST_FORWARD FOR
SELECT ImportChapterIndex, Title, SortOrder
FROM @Chapters
ORDER BY SortOrder, ImportChapterIndex;
OPEN chapter_cursor;
FETCH NEXT FROM chapter_cursor INTO @ImportChapterIndex, @ChapterTitle, @ChapterSortOrder;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @ChapterNumber = @ImportChapterIndex;
INSERT dbo.Chapters
(
BookID, ChapterNumber, ChapterTitle, Summary, SortOrder, RevisionStatusID,
IsLinkedToManuscript, ManuscriptDocumentID, ExternalReference, LinkedUtc
)
VALUES
(
@BookID, @ChapterNumber, @ChapterTitle, NULL, @ChapterSortOrder, @PlannedRevisionStatusID,
1, @ManuscriptDocumentID, CONCAT(N'PD_CHAPTER_IMPORT_', @ImportChapterIndex), @LinkedUtc
);
SET @ChapterID = CAST(SCOPE_IDENTITY() AS int);
INSERT @ImportChapterMap (ImportChapterIndex, ChapterID) VALUES (@ImportChapterIndex, @ChapterID);
FETCH NEXT FROM chapter_cursor INTO @ImportChapterIndex, @ChapterTitle, @ChapterSortOrder;
END;
CLOSE chapter_cursor;
DEALLOCATE chapter_cursor;
DECLARE @ImportSceneIndex int;
DECLARE @SceneTitle nvarchar(200);
DECLARE @SceneSortOrder int;
DECLARE @SceneWordCount int;
DECLARE @SceneID int;
DECLARE scene_cursor CURSOR LOCAL FAST_FORWARD FOR
SELECT s.ImportChapterIndex, s.ImportSceneIndex, s.Title, s.SortOrder, s.WordCount, m.ChapterID
FROM @Scenes s
INNER JOIN @ImportChapterMap m ON m.ImportChapterIndex = s.ImportChapterIndex
ORDER BY s.ImportChapterIndex, s.SortOrder, s.ImportSceneIndex;
OPEN scene_cursor;
FETCH NEXT FROM scene_cursor INTO @ImportChapterIndex, @ImportSceneIndex, @SceneTitle, @SceneSortOrder, @SceneWordCount, @ChapterID;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SceneID=NULL;
IF @ImportSceneIndex=1
SELECT TOP(1) @SceneID=SceneID FROM dbo.Scenes WHERE ChapterID=@ChapterID AND IsArchived=0 ORDER BY SortOrder,SceneID;
IF @SceneID IS NOT NULL
BEGIN
UPDATE dbo.Scenes
SET SceneNumber = @ImportSceneIndex,
SceneTitle = @SceneTitle,
SortOrder = @SceneSortOrder,
IsLinkedToManuscript = 1,
ManuscriptDocumentID = @ManuscriptDocumentID,
ExternalReference = CONCAT(N'PD_SCENE_IMPORT_', @ImportChapterIndex, N'_', @ImportSceneIndex),
LinkedUtc = @LinkedUtc,
UpdatedDate = SYSUTCDATETIME()
WHERE SceneID = @SceneID;
END
ELSE
BEGIN
INSERT dbo.Scenes
(
ChapterID, SceneNumber, SceneTitle, Summary, SortOrder, TimeModeID, TimeConfidenceID, RevisionStatusID,
IsLinkedToManuscript, ManuscriptDocumentID, ExternalReference, LinkedUtc
)
VALUES
(
@ChapterID, @ImportSceneIndex, @SceneTitle, NULL, @SceneSortOrder, @DefaultTimeModeID, @DefaultTimeConfidenceID, @PlannedRevisionStatusID,
1, @ManuscriptDocumentID, CONCAT(N'PD_SCENE_IMPORT_', @ImportChapterIndex, N'_', @ImportSceneIndex), @LinkedUtc
);
SET @SceneID = CAST(SCOPE_IDENTITY() AS int);
END;
IF EXISTS (SELECT 1 FROM dbo.SceneWorkflow WHERE SceneID = @SceneID)
BEGIN
UPDATE dbo.SceneWorkflow
SET ActualWordCount = @SceneWordCount,
UpdatedDate = SYSUTCDATETIME()
WHERE SceneID = @SceneID;
END
ELSE
BEGIN
INSERT dbo.SceneWorkflow (SceneID, ActualWordCount)
VALUES (@SceneID, @SceneWordCount);
END;
INSERT @ImportSceneMap (ImportChapterIndex, ImportSceneIndex, SceneID)
VALUES (@ImportChapterIndex, @ImportSceneIndex, @SceneID);
FETCH NEXT FROM scene_cursor INTO @ImportChapterIndex, @ImportSceneIndex, @SceneTitle, @SceneSortOrder, @SceneWordCount, @ChapterID;
END;
CLOSE scene_cursor;
DEALLOCATE scene_cursor;
COMMIT TRANSACTION;
SELECT CAST(1 AS bit) AS Imported,
CAST(0 AS bit) AS RequiresReplaceConfirmation,
N'Manuscript structure imported.' AS Message,
@ProjectID AS ProjectId,
@BookID AS BookId,
(SELECT COUNT(*) FROM @ImportChapterMap) AS ChaptersCreated,
(SELECT COUNT(*) FROM @ImportSceneMap) AS ScenesCreated,
@ArchivedChapters AS ArchivedChapters,
@ArchivedScenes AS ArchivedScenes;
SELECT md.ManuscriptDocumentID AS ManuscriptDocumentId,
md.BookID AS BookId,
md.ProjectID AS ProjectId,
md.DocumentGuid,
md.BindingVersion,
md.CreatedUtc,
md.LastSyncUtc,
md.LastOpenedUtc,
md.IsActive
FROM dbo.ManuscriptDocuments md
WHERE md.ManuscriptDocumentID = @ManuscriptDocumentID;
END;
GO