diff --git a/Docs/Codex/CharacterAttributes.md b/Docs/Codex/CharacterAttributes.md index 2a7fe61b..24c0c1b9 100644 --- a/Docs/Codex/CharacterAttributes.md +++ b/Docs/Codex/CharacterAttributes.md @@ -63,3 +63,5 @@ Migration 324 adds canonical `CharacterTypeCode` (`person`, `animal`, `supernatu The editor explicitly supplies classification with an original timestamp. Existing callers that do not opt in preserve Type/species; existing editor forms reject concurrent classification changes. Get/list/reference projections and project exports include the new fields; the existing schema-driven restore accepts them and supplies Unclassified for old backups. There is no type-dependent exclusion from appearances, relationships, life status, sex, importance, archival or Quick Add. `PlotLine.Tests/Sql/CharacterTypes.sql` runs on a disposable qualification copy and covers no-inference migration, bulk/individual updates, species retention, independent attributes, Undo, editor persistence, old caller preservation and invalid codes. The normal harness checks the vocabulary, snapshot and server-side validation. Character browser fixtures now include Type assignment/Undo through the common UI. + +The Character Editor concurrency version is sent explicitly as Dapper `DbType.DateTime2`, preserving the `Characters.UpdatedDate datetime2(7)` precision. SQL `datetime` rounding can otherwise produce a false stale-version failure after quick assignment. The isolated real-repository `--character-editor-precision-database` check covers a seven-digit fractional timestamp, a successful ordinary editor save, stale-version rejection and preservation of a newer concurrent biography. Legacy save callers retain the existing opt-in classification behaviour. diff --git a/PlotLine.Tests/CharacterEditorPrecisionDatabaseTests.cs b/PlotLine.Tests/CharacterEditorPrecisionDatabaseTests.cs new file mode 100644 index 00000000..b3aba957 --- /dev/null +++ b/PlotLine.Tests/CharacterEditorPrecisionDatabaseTests.cs @@ -0,0 +1,41 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using Microsoft.Data.SqlClient; +using PlotLine.Data; +internal static class CharacterEditorPrecisionDatabaseTests +{ + public static async Task Run(string path) + { + var settings=JsonSerializer.Deserialize(await File.ReadAllTextAsync(path),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!; + if(!settings.Database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal))throw new Exception("Disposable database required"); + var cs=new SqlConnectionStringBuilder{DataSource=settings.Server,InitialCatalog=settings.Database,UserID="sa",Password=settings.Password,Encrypt=true,TrustServerCertificate=true}.ConnectionString; + await using var db=new SqlConnection(cs);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!=settings.Database)throw new Exception("Wrong database"); + var factory=new Factory(cs);var projects=new ProjectRepository(factory);var characters=new CharacterRepository(factory);int user=0,project=0; + try + { + user=await db.QuerySingleAsync("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(@Email,N'Editor precision fixture',N'not-an-authenticatable-password-hash');SELECT CONVERT(int,SCOPE_IDENTITY());",new{Email=$"precision-{Guid.NewGuid():N}@example.invalid"}); + project=await projects.SaveAsync(new(){ProjectName="Isolated editor precision fixture"},user,null); + var id=await characters.SaveCharacterAsync(new(){ProjectID=project,CharacterName="Synthetic cat",CharacterTypeCode="animal",Species="Cat",DefaultDescription="Complete fixture biography",UpdateClassification=true},userId:user); + await db.ExecuteAsync("UPDATE dbo.Characters SET UpdatedDate=CONVERT(datetime2(7),'2026-11-26T12:34:56.1234567') WHERE CharacterID=@ID",new{ID=id}); + var original=(await characters.GetCharacterAsync(id))!;original.UpdateClassification=true;original.ExpectedClassificationVersion=original.UpdatedDate;original.Species="Fictional cat"; + await characters.SaveCharacterAsync(original,userId:user); + var saved=(await characters.GetCharacterAsync(id))!; + if(saved.Species!="Fictional cat"||saved.CharacterTypeCode!="animal"||saved.DefaultDescription!="Complete fixture biography")throw new Exception("Editor changed unrelated fields"); + Console.WriteLine("PASS Character editor datetime2(7) version survives Dapper and permits an ordinary save"); + try{await characters.SaveCharacterAsync(original,userId:user);throw new Exception("Stale version accepted");}catch(InvalidOperationException error)when(error.Message.Contains("changed in another window")){} + saved.UpdateClassification=true;saved.ExpectedClassificationVersion=saved.UpdatedDate; + await db.ExecuteAsync("UPDATE dbo.Characters SET DefaultDescription=N'Concurrent fixture biography',UpdatedDate=DATEADD(microsecond,1,UpdatedDate) WHERE CharacterID=@ID",new{ID=id}); + try{await characters.SaveCharacterAsync(saved,userId:user);throw new Exception("Concurrent biography overwritten");}catch(InvalidOperationException error)when(error.Message.Contains("changed in another window")){} + if((await characters.GetCharacterAsync(id))!.DefaultDescription!="Concurrent fixture biography")throw new Exception("Concurrent biography lost"); + Console.WriteLine("PASS Character editor rejects genuine stale/concurrent versions and preserves the newer biography"); + } + finally + { + if(project>0){await projects.ArchiveForOwnerAsync(project,user);await projects.HardDeleteForOwnerAsync(project,user);} + if(user>0&&!await new UserRepository(factory).HardDeleteAccountDataAsync(user))throw new Exception("Fixture cleanup failed"); + } + } + private sealed record Settings(string Server,string Database,string Password); + private sealed class Factory(string cs):ISqlConnectionFactory{public IDbConnection CreateConnection()=>new SqlConnection(cs);} +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 35b35051..77150f07 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -191,6 +191,7 @@ if(args.Contains("--character-workspace-database")){await CharacterWorkspaceData if(args.Contains("--character-workspace")){await CharacterWorkspaceTests.Run();return;} if(args.Contains("--context-family")){ContextFamilyTests.Run();return;} if(args.Contains("--context-lenses")){await ContextRelationshipLensTests.Run();return;} +if(args.Contains("--character-editor-precision-database")){await CharacterEditorPrecisionDatabaseTests.Run(args.Last());return;} if(args.Contains("--name-verification-database")){await NameVerificationDatabaseTests.Run(args.Last());return;} if(args.Contains("--name-verification")){await NameVerificationTests.Run();return;} if(args.Contains("--discretionary-ai-database")){await DiscretionaryAiDatabaseTests.Run(args.Last());return;} diff --git a/PlotLine/Data/Repositories.cs b/PlotLine/Data/Repositories.cs index 9719c6cd..5e58ec4b 100644 --- a/PlotLine/Data/Repositories.cs +++ b/PlotLine/Data/Repositories.cs @@ -3751,15 +3751,13 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory, public async Task SaveCharacterAsync(Character character,bool updateLifeStatus=false,bool? expectedIsDeceased=null,int? userId=null) { using var connection = connectionFactory.CreateConnection(); - try { return await connection.QuerySingleAsync( - "dbo.Character_Save", - new + var parameters = new DynamicParameters(new { character.CharacterID, character.ProjectID, character.CharacterName, character.CharacterTypeCode, character.Species, - UpdateClassification = character.UpdateClassification, ExpectedClassificationVersion = character.ExpectedClassificationVersion, + UpdateClassification = character.UpdateClassification, character.ShortName, character.SexValueID, character.Sex, @@ -3774,7 +3772,10 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory, character.ImagePath, character.ThumbnailPath, character.IsDeceased,UpdateLifeStatus=updateLifeStatus,ExpectedIsDeceased=expectedIsDeceased,UserID=userId - }, + }); + // Preserve the full datetime2(7) version used by the editor concurrency guard. + parameters.Add("ExpectedClassificationVersion", character.ExpectedClassificationVersion, DbType.DateTime2); + try { return await connection.QuerySingleAsync("dbo.Character_Save", parameters, commandType: CommandType.StoredProcedure); } catch (Microsoft.Data.SqlClient.SqlException e) when(e.Number==51011) { throw new InvalidOperationException("This character changed in another window. Reload before saving.",e); } catch (Microsoft.Data.SqlClient.SqlException e) when(e.Number==51010) { throw new UnauthorizedAccessException("Character editing unavailable.",e); }