diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 756cab12..37046f65 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -71,8 +71,9 @@ public static class BookMapping Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, - UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, - UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null, }; } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs index adbce645..40e63a13 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs @@ -34,12 +34,12 @@ public static class UpdateBookCommandMapping public static Result ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook) { IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); - List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []]; + List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainEntities(); - errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []]; + errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count > 0) return errors; @@ -57,7 +57,7 @@ public static class UpdateBookCommandMapping // Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played. IEnumerable> domainContributorsResult = command.Contributors!.ToBookDomainEntities(); - errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []]; + errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors)]; if (errors.Count > 0) return errors; diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs index 784c77f8..931e66c5 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs @@ -30,12 +30,12 @@ public static class WrittenContentMetadataDtoMapping return domainReleaseInfoResult.Value.Errors; IEnumerable> domainGenresResult = dto.Genres!.ToDomainEntities(); - List errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors) ?? []]; + List errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; if (errors.Count > 0) return errors; IEnumerable> domainTagsResult = dto.Tags!.ToDomainEntities(); - errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors) ?? []]; + errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; if (errors.Count > 0) return errors; diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index 67db1876..0209e6e5 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Specifications; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; @@ -100,7 +101,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.ISBNs) .Include(book => book.Ratings) .Include(book => book.Contributors) - .Include(book => book.Artwork); + .Include(book => book.Artwork) + .AsSplitQuery(); } return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } @@ -130,7 +132,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.ISBNs) .Include(book => book.Ratings) .Include(book => book.Contributors) - .Include(book => book.Artwork); + .Include(book => book.Artwork) + .AsSplitQuery(); } // Books should always be retrieved only per owning libraries. @@ -283,6 +286,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.ISBNs) .Include(book => book.Contributors) .Include(book => book.Artwork) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -301,6 +305,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Artwork) + .AsSplitQuery() .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } @@ -320,6 +325,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Contributors) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) @@ -356,6 +362,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Artwork) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) @@ -483,7 +490,7 @@ internal sealed class BookRepository : IBookRepository } /// - /// Updates a book, replacing its editable data while preserving its identity, enrichment and audit columns. + /// Updates a book, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, its enrichment columns and its audit columns. /// /// The book whose editable data is applied to the stored book. /// Cancellation token that can be used to stop the execution. @@ -500,49 +507,90 @@ internal sealed class BookRepository : IBookRepository if (foundBook is null) return Errors.WrittenContent.BookNotFound; - // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. + // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. The audit columns are + // only ever written by the auditing interceptor, which is why the copier restores them after copying the editable values. Guid libraryId = foundBook.LibraryId; string path = foundBook.Path; MetadataStatus metadataStatus = foundBook.MetadataStatus; DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc; string? metadataProvider = foundBook.MetadataProvider; - DateTime createdOnUtc = foundBook.CreatedOnUtc; - Guid createdBy = foundBook.CreatedBy; - - // Copy the editable scalar properties of the book, ignoring the unchanged collection and enrichment columns. - _luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data); + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data); foundBook.LibraryId = libraryId; foundBook.Path = path; foundBook.MetadataStatus = metadataStatus; foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc; foundBook.MetadataProvider = metadataProvider; - foundBook.CreatedOnUtc = createdOnUtc; - foundBook.CreatedBy = createdBy; - // Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated. - List existingTags = await _luminaDbContext.Set() - .Where(tag => data.Tags.Select(bookTag => bookTag.Name).Contains(tag.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .Where(genre => data.Genres.Select(bookGenre => bookGenre.Name).Contains(genre.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); + await ReconcileTagsAndGenresAsync(foundBook, data, cancellationToken).ConfigureAwait(false); - foundBook.Tags.Clear(); - foundBook.Tags.UnionWith(data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); - foundBook.Genres.Clear(); - foundBook.Genres.UnionWith(data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + // ISBNs are owned value objects with no identity anyone could reference, so an ISBN whose format changed is replaced as a whole, while the ones that did not + // change are left exactly as they are stored. Matching by the ISBN value keeps an update in place instead of recreating every ISBN of the book. + CollectionReconciler.Reconcile( + foundBook.ISBNs, + data.ISBNs, + existingIsbn => existingIsbn.Value ?? string.Empty, + incomingIsbn => incomingIsbn.Value ?? string.Empty, + shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn), + createNew: incomingIsbn => incomingIsbn); - // Replace the owned collections of the book, so that removed entries are deleted and new entries are inserted. - foundBook.ISBNs.Clear(); - foundBook.ISBNs.AddRange(data.ISBNs); - foundBook.Ratings.Clear(); - foundBook.Ratings.AddRange(data.Ratings); - foundBook.Contributors.Clear(); - foundBook.Contributors.AddRange(data.Contributors); + // Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change + // are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the book. + CollectionReconciler.Reconcile( + foundBook.Ratings, + data.Ratings, + existingRating => existingRating.Source?.ToString() ?? string.Empty, + incomingRating => incomingRating.Source?.ToString() ?? string.Empty, + shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating), + createNew: incomingRating => incomingRating); + + // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a + // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the book was edited. + CollectionReconciler.Reconcile( + foundBook.Contributors, + data.Contributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); return Result.Updated; } + /// + /// Reconciles the tags and genres of against the ones carried by , reusing the stored tags and genres whose names already exist. + /// + /// The tracked book whose tags and genres are reconciled. + /// The book carrying the desired tags and genres. + /// Cancellation token that can be used to stop the execution. + private async Task ReconcileTagsAndGenresAsync(BookEntity foundBook, BookEntity data, CancellationToken cancellationToken) + { + // Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted. + List tagNames = [.. data.Tags.Select(tag => tag.Name!)]; + List genreNames = [.. data.Genres.Select(genre => genre.Name!)]; + List existingTags = await _luminaDbContext.Set() + .Where(tag => tagNames.Contains(tag.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => genreNames.Contains(genre.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + CollectionReconciler.Reconcile( + foundBook.Tags, + data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag), + existingTag => existingTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (existingTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + CollectionReconciler.Reconcile( + foundBook.Genres, + data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre), + existingGenre => existingGenre.Name!, + incomingGenre => incomingGenre.Name!, + shouldReplace: (existingGenre, incomingGenre) => false, + createNew: incomingGenre => incomingGenre); + } + /// /// Sorts a books query by the given field name, defaulting to . /// diff --git a/src/Lumina.Domain/Common/Errors/Errors.Reading.cs b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs index 271bfe9d..ebe6790b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Reading.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs @@ -11,7 +11,6 @@ public static partial class Errors { public static class Reading { - public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty)); public static Error LocationRefCannotBeEmpty => Error.Validation(description: nameof(LocationRefCannotBeEmpty)); public static Error ResourceKeyCannotBeEmpty => Error.Validation(description: nameof(ResourceKeyCannotBeEmpty)); public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound)); diff --git a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs index a31b8da5..ad7eff46 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs @@ -37,6 +37,8 @@ public static partial class Errors public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero)); public static Error BookLibraryCannotBeNull => Error.Validation(description: nameof(BookLibraryCannotBeNull)); public static Error BookPathCannotBeEmpty => Error.Validation(description: nameof(BookPathCannotBeEmpty)); + public static Error BookPathMustBeMaximum2048CharactersLong => Error.Validation(description: nameof(BookPathMustBeMaximum2048CharactersLong)); + public static Error BookPathMustBeWithinLibraryContentLocations => Error.Validation(description: nameof(BookPathMustBeWithinLibraryContentLocations)); public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty)); public static Error BookCoverCannotBeNull => Error.Validation(description: nameof(BookCoverCannotBeNull)); public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound)); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs index 9cd8830c..dd2e28b9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs @@ -28,7 +28,7 @@ public class UpdateBookEndpointSummary : Summary r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index a6f0ff83..5cf330b0 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -1,6 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; @@ -9,7 +12,9 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -26,6 +31,9 @@ public class BookRepositoryTests { private readonly BookEntityFixture _bookEntityFixture = new(); private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); [Fact] public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() @@ -190,4 +198,180 @@ public class BookRepositoryTests Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid contributorId = book.Contributors[0].Id; + DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Null(storedBook!.UpdatedOnUtc); + BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheBookAndKeepTheChildRowsUntouched() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-metadata-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid contributorId = book.Contributors[0].Id; + DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + incoming.Title = "A brand new title"; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Equal("A brand new title", storedBook!.Title); + Assert.Equal(utcNow, storedBook.UpdatedOnUtc); + Assert.Equal(userId, storedBook.UpdatedBy); + BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + Guid keptMediaContributorId = Guid.NewGuid(); + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); + BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()); + book.Contributors = [keptContributor, removedContributor]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync(); + BookContributorEntity storedContributor = Assert.Single(storedContributors); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-addcontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + Guid keptMediaContributorId = Guid.NewGuid(); + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); + book.Contributors = [keptContributor]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + Guid addedMediaContributorId = Guid.NewGuid(); + incoming.Contributors.Add(_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: addedMediaContributorId)); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync(); + Assert.Equal(2, storedContributors.Count); + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Loads a detached copy of a stored book, with its children, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored book. + /// The Id of the book to load. + /// The detached copy of the book. + private static async Task LoadDetachedBookAsync(LuminaDbContext context, Guid bookId) + { + return await context.Books + .AsNoTracking() + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .FirstAsync(book => book.Id == bookId); + } }