Uses contributor references on the book page

This commit is contained in:
BinaryAlley committed 2026-11-27 18:23:20 +02:00
1 parent dab6bac9a7
commit ad072eeffc
28 files changed
+217 -199

No files matched your search

+22
View File
@@ -179,6 +179,7 @@ Known page keys:
| `shared/audio-player/queue-item` | The queue item of the audio player bar. |
| `shared/audio-player/playlist-item` | The playlist item of the audio player bar. |
| `library/written-content-library/book-library/books/index` | The books browsing page. |
| `library/written-content-library/book-library/books/item` | The details and editing page of a book. |
| `library/written-content-library/book-library/books/deleted-items` | The deleted items page of a book library, which restores deleted books. |
| `library/audio-library/music-library/deleted-items` | The deleted items page of a music library, which restores deleted artists, albums and tracks. |
| `playlists/index` | The page that lists and deletes the playlists of the current user. |
@@ -590,6 +591,27 @@ The page script renders the cards into `books-container` and drives these hooks:
| `.media-card`, `.card-actions-trigger` and `.card-actions-menu` | Render a book card and its actions menu. |
| `.card-action-delete` | Deletes the book of the card. |
#### The Book Details and Editing Page
`library/written-content-library/book-library/books/item` renders the details and editing page of a book. Its fallback is `Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml`. Both bundled themes ship `templates/library/written-content-library/book-library/books/item.html`.
Page data:
| Field | Content |
| --- | --- |
| `bookId` | The Id of the book shown. |
| `libraryId` | The Id of the library the book belongs to. |
| `antiforgeryToken` | The anti-forgery request token for the save, delete and cover upload requests. |
| `saveUrl` | The route that saves the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. |
| `deleteUrl` | The route that deletes the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book, and `libraryId` is appended as a query parameter. |
| `coverUrl` | The route that uploads the cover of the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. |
| `backUrl` | The route of the books page of the library. |
| `bookJson` | The full details of the book, serialized as JSON. It carries the same fields as the book details response, including `metadata`, identifiers, ISBNs, `contributors`, `ratings` and `coverPath`. |
| `strings` | The localized strings of the page, keyed by their resource names. |
| `stringsJson` | The same localized strings serialized as JSON, with camel case keys, for the page script. |
The `contributors` of `bookJson` are references to the contributors table, each with the shape `{ contributorId, role }`, where `contributorId` is the Id of the contributor. A theme that needs a contributor's name resolves it from the contributors table using that Id.
#### The Deleted Items Page
`library/written-content-library/book-library/books/deleted-items` lists the books that were deleted from a book library and lets the user restore them. Its fallback is `Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml`. The bundled themes ship their own `templates/library/written-content-library/book-library/books/deleted-items.html`; when a theme has no template for the page, the application renders the fallback view.
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System.Diagnostics;
#endregion
namespace Nemera.Presentation.Web.Common.DTO.MediaContributors;
/// <summary>
/// Data transfer object for a media contributor.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MediaContributorDto
{
/// <summary>
/// Gets the name of the contributor.
/// </summary>
public MediaContributorNameDto? Name { get; set; }
/// <summary>
/// Gets the canonical role of the contributor, used as the key of its localized display string.
/// </summary>
public MediaContributorRole? Role { get; set; }
}
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Nemera.Presentation.Web.Common.DTO.MediaContributors;
/// <summary>
/// Data transfer object for a media contributor name.
/// </summary>
[DebuggerDisplay("DisplayName: {DisplayName}")]
public class MediaContributorNameDto
{
/// <summary>
/// Gets the name by which the contributor is popularly known.
/// </summary>
public string? DisplayName { get; set; }
/// <summary>
/// Gets the legal name of the contributor.
/// </summary>
public string? LegalName { get; set; }
}
@@ -102,9 +102,9 @@ public class BookDetailsDto
public List<IsbnDto>? ISBNs { get; set; }
/// <summary>
/// Gets or sets the list of media contributors of the book.
/// Gets or sets the list of references to the media contributors of the book, each with the role they played.
/// </summary>
public List<MediaContributorDto>? Contributors { get; set; }
public List<MediaContributorReferenceDto>? Contributors { get; set; }
/// <summary>
/// Gets or sets the list of ratings of the book.
@@ -30,7 +30,7 @@ namespace Nemera.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.
/// <param name="BarnesAndNobleId">The Barnes &amp; Noble Id of the book. Optional.</param>
/// <param name="AppleBooksId">The Apple Books Id of the book. Optional.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book. Required.</param>
/// <param name="Contributors">The list of media contributors of the book. Required.</param>
/// <param name="Contributors">The list of references to the media contributors of the book, each with the role they played. Required.</param>
/// <param name="Ratings">The list of ratings of the book. Required.</param>
[DebuggerDisplay("Title: {Metadata?.Title}")]
public record UpdateBookRequest(
@@ -51,6 +51,6 @@ public record UpdateBookRequest(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
);
@@ -69,7 +69,7 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional.");
RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional.");
RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required.");
RequestParam(r => r.Contributors, "The list of media contributors of the book. Required.");
RequestParam(r => r.Contributors, "The list of references to the media contributors of the book, each with the role they played. Required.");
RequestParam(r => r.Ratings, "The list of ratings of the book. Required.");
ExampleRequest = new UpdateBookRequest(
@@ -139,14 +139,14 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
],
Contributors:
[
new MediaContributorDto
new MediaContributorReferenceDto
{
Name = new MediaContributorNameDto { DisplayName = "J.R.R. Tolkien", LegalName = "John Ronald Reuel Tolkien" },
ContributorId = Guid.NewGuid(),
Role = MediaContributorRole.Author
},
new MediaContributorDto
new MediaContributorReferenceDto
{
Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" },
ContributorId = Guid.NewGuid(),
Role = MediaContributorRole.Illustrator
}
],
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>تغيير الغلاف</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>الاسم</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>الأشخاص الذين ساهموا في الكتاب، مثل مؤلفيه.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Titelbild ändern</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Die Personen, die zum Buch beigetragen haben, wie seine Autoren.</value>
</data>
@@ -150,9 +150,6 @@
<data name="Contributors" xml:space="preserve">
<value>Contributors</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="RoleName" xml:space="preserve">
<value>Role</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Cambiar portada</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nombre</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Las personas que contribuyeron al libro, como sus autores.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Changer la couverture</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nom</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Les personnes ayant contribué au livre, comme ses auteurs.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Cambia copertina</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nome</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Le persone che hanno contribuito al libro, come i suoi autori.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>表紙を変更</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>名前</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>著者など、本に貢献した人々。</value>
</data>
@@ -150,9 +150,6 @@
<data name="Contributors" xml:space="preserve">
<value>Contributors</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="RoleName" xml:space="preserve">
<value>Role</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Schimbă coperta</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nume</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Persoanele care au contribuit la carte, precum autorii ei.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Змінити обкладинку</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Ім'я</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Люди, які долучилися до створення книги, як-от її автори.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>更换封面</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>姓名</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>为图书作出贡献的人,例如其作者。</value>
</data>
@@ -34,7 +34,7 @@
var genres = metadata?.Genres ?? [];
var tags = metadata?.Tags ?? [];
var isbns = Model.ISBNs ?? [];
var contributors = Model.Contributors ?? [];
var contributors = Model.Contributors ?? [];
var ratings = Model.Ratings ?? [];
// The full set of canonical media contributor roles, mirroring the MediaContributorRole enum members, offered by the role combobox.
var contributorRoles = new[]
@@ -42,7 +42,7 @@
"Other", "Author", "Translator", "Illustrator", "Publisher", "Narrator", "Actor", "Director", "Screenwriter",
"Composer", "Lyricist", "Arranger", "Conductor", "Producer", "ExecutiveProducer", "Engineer", "Mixer", "Remixer",
"RecordLabel", "Vocals", "BackingVocals", "Guitar", "BassGuitar", "Drums", "Percussion", "Keyboards", "Piano",
"Synthesizer", "Strings", "Woodwinds", "Brass", "Choir", "Orchestrator"
"Synthesizer", "Strings", "Woodwinds", "Brass", "Choir", "Orchestrator", "Performer"
};
// Resolves the localized label of a contributor role, keyed by its canonical value.
Func<string?, string> roleLabel = role => role switch
@@ -441,7 +441,7 @@
<table class="w-100 form-table book-list-table">
<thead>
<tr>
<th>@_localizer["ContributorName"]</th>
<th>@_localizer["ContributorId"]</th>
<th>@_localizer["Role"]</th>
<th class="w-40px"></th>
</tr>
@@ -451,7 +451,7 @@
@foreach (var contributor in contributors)
{
<tr class="contributor-row">
<td><input type="text" class="enlightenment-input contributor-name w-100" value="@(contributor.Name?.DisplayName ?? string.Empty)" /></td>
<td><input type="text" class="enlightenment-input contributor-id w-100" value="@(contributor.ContributorId.ToString())" /></td>
<td>
<div class="enlightenment-combobox inline-block w-100 contributor-role-combobox">
<div class="shine-effect" style="top: 1px;"></div>
@@ -637,7 +637,7 @@
Format: readRowComboboxValue(row, '.isbn-format-combobox') || null
})),
Contributors: Array.from(contributorsBody.querySelectorAll('.contributor-row')).map(row => ({
Name: { DisplayName: row.querySelector('.contributor-name').value.trim() || null },
ContributorId: row.querySelector('.contributor-id').value.trim() || '00000000-0000-0000-0000-000000000000',
Role: readRowComboboxValue(row, '.contributor-role-combobox') || null
})),
Ratings: Array.from(ratingsBody.querySelectorAll('.rating-row')).map(row => ({
@@ -787,15 +787,13 @@
await updateContentAsync(`${libraryIndexUrl}?libraryId=${encodeURIComponent(libraryId)}`, true);
}
// Builds the HTML of an enlightenment combobox of a row, with the provided option values.
function buildRowCombobox(optionValues, selectedValue) {
// Builds the HTML of an enlightenment combobox of a row, with the provided option values and an optional wrapper class.
function buildRowCombobox(optionValues, selectedValue, wrapperClass) {
const id = `row-combobox-${generatedId++}`;
const options = optionValues.map(option => {
const selected = option.value === selectedValue ? ' selected' : '';
return `<div class="enlightenment-option" data-value="${option.value}">${option.label}</div>`;
}).join('');
const options = optionValues.map(option =>
`<div class="enlightenment-option" data-value="${option.value}">${option.label}</div>`).join('');
return `
<div class="enlightenment-combobox inline-block w-100">
<div class="enlightenment-combobox inline-block w-100 ${wrapperClass || ''}">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="${id}" />
<label class="enlightenment-toggle" for="${id}">
@@ -845,7 +843,7 @@
isbnsBody.insertAdjacentHTML('beforeend', `
<tr class="isbn-row">
<td><input type="text" class="enlightenment-input isbn-value" /></td>
<td>${buildRowCombobox(isbnOptions, '')}</td>
<td>${buildRowCombobox(isbnOptions, '', 'isbn-format-combobox')}</td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
}
@@ -854,8 +852,8 @@
function addContributorRow() {
contributorsBody.insertAdjacentHTML('beforeend', `
<tr class="contributor-row">
<td><input type="text" class="enlightenment-input contributor-name w-100" /></td>
<td>${buildRowCombobox(contributorRoleOptions, 'Author')}</td>
<td><input type="text" class="enlightenment-input contributor-id w-100" /></td>
<td>${buildRowCombobox(contributorRoleOptions, 'Author', 'contributor-role-combobox')}</td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
}
@@ -866,7 +864,7 @@
<tr class="rating-row">
<td><input type="number" step="any" min="0" class="enlightenment-input rating-value" /></td>
<td><input type="number" step="any" min="0" class="enlightenment-input rating-max-value" /></td>
<td>${buildRowCombobox(ratingSourceOptions, '')}</td>
<td>${buildRowCombobox(ratingSourceOptions, '', 'rating-source-combobox')}</td>
<td><input type="number" min="0" class="enlightenment-input rating-vote-count" /></td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
@@ -1,47 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.MediaContributors;
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Nemera.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorDtoFixture
{
private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new();
/// <summary>
/// Creates a new <see cref="MediaContributorDto"/> instance with randomized test data.
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <param name="role">Optional. The canonical role of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorDto"/> instance.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? legalName = null,
MediaContributorRole? role = null)
{
return new MediaContributorDto
{
Name = _mediaContributorNameDtoFixture.Create(displayName, legalName),
Role = role ?? MediaContributorRole.Author
};
}
/// <summary>
/// Creates multiple <see cref="MediaContributorDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorDto"/> instances.</returns>
public List<MediaContributorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Nemera.Presentation.Web.Common.DTO.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Nemera.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorNameDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorNameDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MediaContributorNameDto"/> instance with randomized test data.
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorNameDto"/> instance.</returns>
public MediaContributorNameDto Create(
string? displayName = null,
string? legalName = null)
{
return new MediaContributorNameDto
{
DisplayName = displayName ?? _faker.Name.FullName(),
LegalName = legalName ?? _faker.Name.FullName()
};
}
/// <summary>
/// Creates multiple <see cref="MediaContributorNameDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorNameDto"/> instances.</returns>
public List<MediaContributorNameDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -23,7 +23,7 @@ public class BookDetailsDtoFixture
private readonly Faker _faker = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
@@ -61,7 +61,7 @@ public class BookDetailsDtoFixture
BarnesAndNobleId = _faker.Random.String2(10, "0123456789"),
AppleBooksId = $"id{_faker.Random.Number(1, 999999)}",
ISBNs = [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Contributors = [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Contributors = [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Ratings = [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
MetadataStatus = _faker.Random.String2(_faker.Random.Number(1, 20)),
LastMetadataUpdateUtc = _faker.Date.Recent(),
@@ -24,7 +24,7 @@ public class UpdateBookRequestFixture
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
@@ -91,7 +91,7 @@ public class UpdateBookRequestFixture
BarnesAndNobleId: includeBarnesAndNobleId ? _faker.Random.String2(10, "0123456789") : null,
AppleBooksId: includeAppleBooksId ? $"id{_faker.Random.Number(1, 999999)}" : null,
ISBNs: includeIsbns ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Contributors: includeContributors ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Contributors: includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Ratings: includeRatings ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null
);
}
@@ -50,5 +50,8 @@ public class EditBookViewEndpointTests : IClassFixture<NemeraWebFactory>
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("A book", content);
Assert.Contains("btn-delete-book", content);
Assert.Contains("contributor-id", content);
Assert.DoesNotContain("contributor-name", content);
Assert.Contains(expectedBook.Contributors![0].ContributorId.ToString(), content);
}
}
@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.Common;
using Nemera.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Nemera.Presentation.Web.Common.Exceptions;
using Nemera.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
using Nemera.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
@@ -172,6 +174,90 @@ public class SaveBookEndpointTests : IClassFixture<NemeraWebFactory>
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenContributorIdIsEmpty_ShouldForwardItAndReturnASanitizedApiError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
string endpoint = $"libraries/{libraryId}/books/{bookId}";
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
request.Contributors![0].ContributorId = Guid.Empty;
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
new ProblemDetailsDto
{
Type = "https://tools.ietf.org/html/rfc4918#section-11.2",
Title = "General.Validation",
Status = 422,
Detail = "MediaContributorIdCannotBeEmpty"
},
(HttpStatusCode)422,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains("media contributor", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.OrdinalIgnoreCase);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest =>
putRequest.Endpoint == endpoint &&
putRequest.Data is UpdateBookRequest forwardedRequest &&
forwardedRequest.Contributors![0].ContributorId == Guid.Empty);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenContributorDoesNotExist_ShouldForwardItAndReturnASanitizedApiError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
Guid unknownContributorId = Guid.NewGuid();
string endpoint = $"libraries/{libraryId}/books/{bookId}";
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
request.Contributors![0].ContributorId = unknownContributorId;
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
new ProblemDetailsDto
{
Type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
Title = "General.NotFound",
Status = 404,
Detail = "MediaContributorNotFound"
},
HttpStatusCode.NotFound,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest =>
putRequest.Endpoint == endpoint &&
putRequest.Data is UpdateBookRequest forwardedRequest &&
forwardedRequest.Contributors![0].ContributorId == unknownContributorId);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Nemera.Presentation.Web.UnitTests.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Contains unit tests for the <see cref="BookDetailsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookDetailsDtoTests
{
private static readonly JsonSerializerOptions s_jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
[Fact]
public void Deserialize_WhenBookResponseHasContributorReferences_ShouldBindContributorIdAndRole()
{
// Arrange
Guid firstContributorId = Guid.NewGuid();
Guid secondContributorId = Guid.NewGuid();
string json = $$"""
{
"id": "{{Guid.NewGuid()}}",
"libraryId": "{{Guid.NewGuid()}}",
"path": "C:\\books\\book.epub",
"contributors": [
{ "contributorId": "{{firstContributorId}}", "role": "Author" },
{ "contributorId": "{{secondContributorId}}", "role": "Illustrator" }
]
}
""";
// Act
BookDetailsDto? result = JsonSerializer.Deserialize<BookDetailsDto>(json, s_jsonOptions);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Contributors);
Assert.Equal(2, result.Contributors.Count);
Assert.Equal(firstContributorId, result.Contributors[0].ContributorId);
Assert.Equal(MediaContributorRole.Author, result.Contributors[0].Role);
Assert.Equal(secondContributorId, result.Contributors[1].ContributorId);
Assert.Equal(MediaContributorRole.Illustrator, result.Contributors[1].Role);
}
}
@@ -62,6 +62,31 @@ public class SaveBookEndpointTests
Assert.Equal(originalBookId, request.BookId);
}
[Fact]
public async Task ExecuteAsync_WhenContributorsAreProvided_ShouldForwardContributorReferencesToApi()
{
// Arrange
string routeId = Guid.NewGuid().ToString();
UpdateBookRequest request = _updateBookRequestFixture.Create();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
.Returns(expectedBook);
ConfigureRequest(routeId);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Any<string>(),
Arg.Is<UpdateBookRequest>(forwardedRequest =>
forwardedRequest.Contributors != null &&
forwardedRequest.Contributors.Count == request.Contributors!.Count &&
forwardedRequest.Contributors[0].ContributorId == request.Contributors[0].ContributorId &&
forwardedRequest.Contributors[0].Role == request.Contributors[0].Role),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi()
{