From 001146eefc174ef44b98f7869f08a8a171891c3f Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 12 Sep 2026 12:13:18 -0700 Subject: [PATCH] Refactors the update book slice across the stack --- .../book-library/Api.Books.md | 268 ++- .../book-library/books/UpdateBook.http | 13 +- .../Books/UpdateBookCommandMapping.cs | 105 +- .../Books/UpdateBookRequestMapping.cs | 7 +- .../Commands/UpdateBook/UpdateBookCommand.cs | 10 +- .../UpdateBook/UpdateBookCommandHandler.cs | 113 +- .../UpdateBook/UpdateBookCommandValidator.cs | 72 +- .../BookLibrary/Books/UpdateBookRequest.cs | 8 +- .../Books/UpdateBook/UpdateBookEndpoint.cs | 12 +- .../UpdateBook/UpdateBookEndpointSummary.cs | 135 +- .../BookLibrary/Books/UpdateBookRequest.cs | 10 +- .../Books/SaveBook/SaveBookEndpoint.cs | 12 +- .../Books/SaveBook/SaveBookEndpointSummary.cs | 13 +- .../UpdateBook/UpdateBookCommandFixture.cs | 20 +- .../Books/UpdateBookRequestFixture.cs | 18 +- .../Books/UpdateBookRequestFixture.cs | 5 +- .../UpdateBook/UpdateBookEndpointTests.cs | 1669 ++++++++++++++++- .../Books/SaveBook/SaveBookEndpointTests.cs | 18 +- .../UpdateBook/UpdateBookEndpointTests.cs | 68 +- .../Books/SaveBook/SaveBookEndpointTests.cs | 16 +- .../Books/UpdateBookCommandMappingTests.cs | 155 +- .../Books/UpdateBookRequestMappingTests.cs | 63 +- .../UpdateBookCommandHandlerTests.cs | 291 ++- .../UpdateBookCommandValidatorTests.cs | 1467 ++++++++++++++- .../Books/UpdateBookRequestTests.cs | 6 +- .../UpdateBook/UpdateBookEndpointTests.cs | 103 +- .../Books/SaveBook/SaveBookEndpointTests.cs | 20 +- 27 files changed, 4065 insertions(+), 632 deletions(-) diff --git a/docs/technical/api/library/written-content-library/book-library/Api.Books.md b/docs/technical/api/library/written-content-library/book-library/Api.Books.md index 2ae349ac..fa93fdc1 100644 --- a/docs/technical/api/library/written-content-library/book-library/Api.Books.md +++ b/docs/technical/api/library/written-content-library/book-library/Api.Books.md @@ -14,6 +14,9 @@ - [Get Books Lite](#get-books-lite) - [Get Books Lite Request](#get-books-lite-request) - [Get Books Lite Response](#get-books-lite-response) + - [Update Book](#update-book) + - [Update Book Request](#update-book-request) + - [Update Book Response](#update-book-response) - [Get Reading Availability](#get-reading-availability) - [Get Reading Availability Request](#get-reading-availability-request) - [Get Reading Availability Response](#get-reading-availability-response) @@ -34,13 +37,12 @@ #### Add Book Request ```js -POST api/v1/books +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books ``` ```json { - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -50,7 +52,7 @@ POST api/v1/books "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -93,31 +95,27 @@ POST api/v1/books "appleBooksId": "id395211", "isbns": [ { - "value": "0395272238", - "format": "Isbn10" + "value": "0395272238", + "format": "Isbn10" }, { - "value": "9780395272237", - "format": "Isbn13" + "value": "9780395272237", + "format": "Isbn13" } ], "contributors": [ { - "name": { - "displayName": "J.R.R. Tolkien" - }, + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, { - "name": { - "displayName": "Alan Lee" - }, + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } ], "ratings": [ { - "source": "Goodreads", + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 @@ -142,7 +140,7 @@ POST api/v1/books { "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "publisher": "Houghton Mifflin", "pageCount": 398, @@ -154,7 +152,7 @@ POST api/v1/books "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "language": { @@ -213,14 +211,19 @@ POST api/v1/books "format": "Isbn13" } ], - "contributors": [], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], "ratings": [ { + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 }, { + "source": "Amazon", "value": 4.7, "maxValue": 5, "voteCount": 87654 @@ -230,7 +233,8 @@ POST api/v1/books "lastMetadataUpdateUtc": null, "metadataProvider": null, "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "updatedOnUtc": null, + "coverPath": null } ``` @@ -239,7 +243,7 @@ POST api/v1/books #### Get Book Request ```js -GET api/v1/books/{id} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} ``` #### Get Book Response @@ -255,12 +259,11 @@ Returns an empty response. This endpoint is not yet implemented. #### Get Books Request ```js -GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. | | `currentPage` | `int` | Optional. The page of results to retrieve. | | `perPage` | `int` | Optional. The maximum number of books to retrieve per page. | | `searchTerm` | `string` | Optional. The search term used to filter results. | @@ -279,7 +282,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe { "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -289,7 +292,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -343,6 +346,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe "contributors": [], "ratings": [ { + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 @@ -367,12 +371,11 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe #### Get Books Lite Request ```js -GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. | | `currentPage` | `int` | Optional. The page of results to retrieve. | | `perPage` | `int` | Optional. The maximum number of books to retrieve per page. | | `searchTerm` | `string` | Optional. The search term used to filter results. | @@ -404,12 +407,217 @@ GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage } ``` +### Update Book + +#### Update Book Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} +``` + +```json +{ + "metadata": { + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "genres": [ + { "name": "fantasy" }, + { "name": "adventure" }, + { "name": "classic" } + ], + "tags": [ + { "name": "epic fantasy" }, + { "name": "quest" }, + { "name": "middle-earth" } + ], + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "publisher": "Houghton Mifflin", + "pageCount": 398 + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": { + "title": "The Lord of the Rings" + }, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Author" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Illustrator" + } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ] +} +``` + +#### Update Book Response + +```js +200 Ok +``` + +```json +{ + "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", + "metadata": { + "publisher": "Houghton Mifflin", + "pageCount": 398, + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { + "name": "epic fantasy" + }, + { + "name": "quest" + }, + { + "name": "middle-earth" + } + ], + "genres": [ + { + "name": "fantasy" + }, + { + "name": "adventure" + }, + { + "name": "classic" + } + ] + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": null, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ], + "metadataStatus": "Enriched", + "lastMetadataUpdateUtc": "2025-01-01T12:00:00.0000000Z", + "metadataProvider": "GoogleBooks", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": "2025-02-01T12:00:00.0000000Z", + "coverPath": "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" +} +``` + ### Get Reading Availability #### Get Reading Availability Request ```js -GET api/v1/books/{bookId}/reading/availability +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/availability ``` Reports whether the book identified by `bookId` can be opened for reading: the book reader that supports the format of the book is resolved and its enablement for the media library of the book is checked, without extracting the book. When the book cannot be read, the response carries the code of the error preventing it, so the client can tell a missing book reader apart from a disabled one. @@ -434,7 +642,7 @@ Reports whether the book identified by `bookId` can be opened for reading: the b #### Get Reading Manifest Request ```js -GET api/v1/books/{bookId}/reading/manifest +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/manifest ``` Opens the book identified by `bookId` for reading by extracting its contents through the book reader that is enabled for its media library, and returns the reading manifest: the title and author of the book, its hierarchical table of contents, its ordered spine of reading sections, the keys of its resources, and whether it has extractable text content. A scanned book, whose pages are only images, has no text content and is displayed as page images. @@ -485,7 +693,7 @@ Opens the book identified by `bookId` for reading by extracting its contents thr #### Get Reading Section Request ```js -GET api/v1/books/{bookId}/reading/sections/{locationRef} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/sections/{locationRef} ``` Returns the reading section identified by `locationRef` of the book identified by `bookId`. The section content is sanitized by the host before it is served, and its references to the resources of the book are resolved by the client through the resource endpoint. The `locationRef` of a section is taken from the spine of the reading manifest of the book. @@ -509,7 +717,7 @@ Returns the reading section identified by `locationRef` of the book identified b #### Get Reading Resource Request ```js -GET api/v1/books/{bookId}/reading/resources/{resourceKey} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/resources/{resourceKey} ``` Returns the binary resource identified by `resourceKey` of the book identified by `bookId` (for example an image, a font, or a stylesheet of the book, or a page image of a scanned PDF that is rendered on demand). The `resourceKey` of a resource is taken from the reading manifest of the book. diff --git a/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http index 6631a24a..ea851263 100644 --- a/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http +++ b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http @@ -1,9 +1,8 @@ -PUT {{host}}/api/v1/books/{{$guid}} +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}} Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "id": "{{$guid}}", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -66,17 +65,11 @@ Content-Type: application/json ], "contributors": [ { - "name": { - "displayName": "J.R.R. Tolkien", - "legalName": "John Ronald Reuel Tolkien" - }, + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, { - "name": { - "displayName": "Alan Lee", - "legalName": "Alan Lee" - }, + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } ], 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 82de4c1c..adbce645 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 @@ -1,6 +1,19 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -11,40 +24,66 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B public static class UpdateBookCommandMapping { /// - /// Converts to , so that the edited data can be applied to the domain book. + /// Converts to , preserving the identity and creation metadata of the stored book identified by . /// - /// The command containing the edited data of the book. - /// The built metadata. - public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command) + /// The command to be converted. + /// The stored book whose identity, file system path and creation metadata are preserved. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook) { - return new BookMetadataDto( - Title: command.Metadata!.Title, - OriginalTitle: command.Metadata.OriginalTitle, - Description: command.Metadata.Description, - ReleaseInfo: command.Metadata.ReleaseInfo, - Genres: command.Metadata.Genres, - Tags: command.Metadata.Tags, - Language: command.Metadata.Language, - OriginalLanguage: command.Metadata.OriginalLanguage, - Publisher: command.Metadata.Publisher, - PageCount: command.Metadata.PageCount, - Format: command.Format, - Edition: command.Edition, - VolumeNumber: command.VolumeNumber, - Series: command.Series, - ASIN: command.ASIN, - GoodreadsId: command.GoodreadsId, - LCCN: command.LCCN, - OCLCNumber: command.OCLCNumber, - OpenLibraryId: command.OpenLibraryId, - LibraryThingId: command.LibraryThingId, - GoogleBooksId: command.GoogleBooksId, - BarnesAndNobleId: command.BarnesAndNobleId, - AppleBooksId: command.AppleBooksId, - Isbns: command.ISBNs, - Contributors: command.Contributors, - Ratings: command.Ratings, - CoverImagePath: null + IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + 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) ?? []]; + if (errors.Count > 0) + return errors; + + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + // TODO: update Api.Books.md documentation when the functionality is fully implemented. + BookSeries? bookSeries = null; + if (command.Series != null) + { + // TODO: add logic to search the book series repository for existing book series, based on the provided title. + // TODO: uncomment integration and unit tests about series. + } + + // 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) ?? []]; + if (errors.Count > 0) + return errors; + + return Book.Create( + BookId.Create(existingBook.Id), + LibraryId.Create(existingBook.LibraryId), + existingBook.Path, + metadataResult.Value, + Optional.FromNullable(command.Format), + Optional.FromNullable(command.Edition), + Optional.FromNullable(command.VolumeNumber), + Optional.FromNullable(bookSeries), + Optional.FromNullable(command.ASIN), + Optional.FromNullable(command.GoodreadsId), + Optional.FromNullable(command.LCCN), + Optional.FromNullable(command.OCLCNumber), + Optional.FromNullable(command.OpenLibraryId), + Optional.FromNullable(command.LibraryThingId), + Optional.FromNullable(command.GoogleBooksId), + Optional.FromNullable(command.BarnesAndNobleId), + Optional.FromNullable(command.AppleBooksId), + existingBook.CreatedOnUtc, + Optional.FromNullable(existingBook.UpdatedOnUtc), + [.. domainIsbnsResult.Select(isbn => isbn.Value)], + [.. domainContributorsResult.Select(domainContributor => domainContributor.Value)], + [.. domainRatingsResult.Select(domainRating => domainRating.Value)] ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs index 6720e145..25b2dd97 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs @@ -15,11 +15,14 @@ public static class UpdateBookRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library the book belongs to, taken from the route. + /// The Id of the book to update, taken from the route. /// The converted command. - public static UpdateBookCommand ToCommand(this UpdateBookRequest request) + public static UpdateBookCommand ToCommand(this UpdateBookRequest request, string? libraryId, string? bookId) { return new UpdateBookCommand( - Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty, + libraryId, + bookId, request.Metadata, request.Format, request.Edition, diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs index f9650855..c5f65dec 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -14,7 +14,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Command for updating an existing book. /// -/// The Id of the book to update. +/// The unique identifier of the media library this book belongs to, taken from the route. +/// The unique identifier of the book to update, taken from the route. /// Written content metadata of the book. /// The format of the book (e.g., Hardcover, Paperback), if applicable. /// The edition of the book, if applicable. @@ -34,7 +35,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// The list of ratings for this book. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateBookCommand( - Guid Id, + string? LibraryId, + string? BookId, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -50,6 +52,6 @@ public record UpdateBookCommand( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs index c844a210..8a2582f2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -8,12 +8,9 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Linq; @@ -70,74 +67,44 @@ public class UpdateBookCommandHandler : ICommandHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.WrittenContent.BookNotFound; BookEntity existingBook = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be edited through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (existingBook.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; + // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // Convert the book to a domain object and apply the edited metadata to it. - Result getDomainBookResult = existingBook.ToDomainEntity(); - if (getDomainBookResult.IsFailure) - return getDomainBookResult.Errors; - Book book = getDomainBookResult.Value; + // Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; - Result applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto()); - if (applyMetadataResult.IsFailure) - return applyMetadataResult.Errors; - - // Link the media contributors typed by the user to the book, finding or creating a single contributor per person. - List linkedContributors = []; - // A person can be credited under several roles in the same book; each distinct display name must resolve to the same media - // contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved. - Dictionary contributorsByDisplayName = []; - foreach (MediaContributorDto contributor in command.Contributors!) - { - if (contributor.Name?.DisplayName is null) - continue; - - if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity)) - { - Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); - if (findOrCreateResult.IsFailure) - return findOrCreateResult.Errors; - contributorEntity = findOrCreateResult.Value; - contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity); - } - - string roleName = contributor.Role?.Name ?? "Contributor"; - MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; - linkedContributors.Add(new BookContributorEntity - { - Id = Guid.NewGuid(), - BookId = existingBook.Id, - MediaContributorId = contributorEntity.Id, - RoleName = roleName, - RoleCategory = roleCategory, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = userId, - UpdatedBy = null - }); - } - book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]); + // Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored book. + Result updateBookResult = command.ToDomainEntity(existingBook); + if (updateBookResult.IsFailure) + return updateBookResult.Errors; // Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data. - BookEntity updatedBook = book.ToRepositoryEntity(); - updatedBook.BookContributors = linkedContributors; - updatedBook.UpdatedOnUtc = DateTime.UtcNow; - updatedBook.UpdatedBy = userId; + BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity(); - // The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that - // backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path). - updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc; + // The enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that the repository + // replaces the stored data with; without this, the stored artwork would be cleared. updatedBook.MetadataStatus = existingBook.MetadataStatus; updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc; updatedBook.MetadataProvider = existingBook.MetadataProvider; @@ -147,8 +114,40 @@ public class UpdateBookCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - return updatedBook.ToResponse() with { Contributors = command.Contributors }; + // Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save. + Result getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(existingBook.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedBookResult.IsFailure) + return getPersistedBookResult.Errors; + if (getPersistedBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + + return getPersistedBookResult.Value.ToResponse(); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(UpdateBookCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs index 3f3de404..9b9715aa 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs @@ -18,18 +18,34 @@ public class UpdateBookCommandValidator : AbstractValidator /// public UpdateBookCommandValidator() { - RuleFor(command => command.Id) + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book to update, taken from the route. + RuleFor(command => command.BookId) .NotEmpty() - .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) - .Must(id => id != Guid.Empty) .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + RuleFor(command => command.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(command => command.BookId is not null && command.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + // Validates the metadata of the book: title, lengths, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) .ChildRules(metadata => { metadata.RuleFor(m => m!.Title) + .NotNull() .NotEmpty() .WithError(Errors.Metadata.TitleCannotBeEmpty) .MaximumLength(255) @@ -125,7 +141,7 @@ public class UpdateBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.Language!.LanguageCode) .NotEmpty() .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.Language is not null); @@ -144,7 +160,7 @@ public class UpdateBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) .NotEmpty() .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.OriginalLanguage is not null); @@ -171,6 +187,7 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); }); + // Validates the physical characteristics of the book: format, edition and volume number. RuleFor(command => command.Format) .IsInEnum() .When(command => command.Format is not null) @@ -186,6 +203,7 @@ public class UpdateBookCommandValidator : AbstractValidator .When(command => command.VolumeNumber.HasValue) .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + // Validates the series the book is part of, when the request carries one. RuleFor(command => command.Series) .ChildRules(series => series.RuleFor(s => s!.Title) @@ -195,6 +213,7 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong)) .When(command => command.Series is not null); + // Validates the external identifiers of the book. RuleFor(command => command.ASIN) .Length(10) .When(command => command.ASIN is not null) @@ -246,6 +265,7 @@ public class UpdateBookCommandValidator : AbstractValidator .When(command => command.AppleBooksId is not null) .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + // Validates the ISBN list of the book. RuleFor(command => command.ISBNs) .NotNull() .WithError(Errors.WrittenContent.IsbnListCannotBeNull); @@ -272,48 +292,26 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.WrittenContent.UnknownIsbnFormat); }); + // Validates the media contributors that contributed to the book. RuleFor(command => command.Contributors) .NotNull() - .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + .WithError(Errors.WrittenContent.ContributorsListCannotBeNull); RuleForEach(command => command.Contributors) .ChildRules(contributor => { - contributor.RuleFor(c => c.Name) - .NotNull() - .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty) - .ChildRules(name => - { - name.RuleFor(n => n!.DisplayName) - .NotNull() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .NotEmpty() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .MaximumLength(100) - .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); - - name.RuleFor(n => n!.LegalName) - .MaximumLength(100) - .When(n => n!.LegalName is not null) - .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); - }); + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); contributor.RuleFor(c => c.Role) - .NotNull() - .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull) - .ChildRules(role => - { - role.RuleFor(r => r!.Name) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty) - .MaximumLength(50) - .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); - role.RuleFor(r => r!.Category) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); - }); + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); }); + // Validates the ratings of the book. RuleFor(command => command.Ratings) .NotNull() .WithError(Errors.Metadata.RatingsListCannotBeNull); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs index 192ed038..4abc5ed9 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -12,7 +12,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to update an existing book. /// -/// The Id of the book to update, taken from the route. Required. /// Written content metadata of the book. Required. /// The format of the book (e.g., Hardcover, Paperback). Optional. /// The edition of the book. Optional. @@ -28,11 +27,10 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// The Barnes & Noble Id of the book. Optional. /// The Apple Books Id of the book. Optional. /// The list of ISBN (International Standard Book Number) of the book. Required. -/// The list of media contributors (actors, directors, etc) starring in this book. Required. +/// The list of media contributors of the book. Required. /// The list of ratings for this book. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateBookRequest( - string? Id, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -48,6 +46,6 @@ public record UpdateBookRequest( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs index 07c489b2..5b3a83e8 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; /// -/// API endpoint for the /books/{id} route. +/// API endpoint for the /{libraryId}/books/{bookId} route. /// public class UpdateBookEndpoint : BaseEndpoint { @@ -48,12 +48,10 @@ public class UpdateBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) { - // The book is identified by the {id} route value, not by the id of the request body, so that a mismatched or malicious id can never - // redirect the update to another book; the raw value is kept as a string, so that an unparseable id reaches the command validator, - // which reports it with a ProblemDetails validation error instead of failing the request binding. - request = request with { Id = HttpContext.Request.RouteValues["id"]?.ToString() }; - - Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + // take unique identifiers from the route + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } 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 6d42a2b0..0c478ada 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 @@ -30,7 +30,6 @@ public class UpdateBookEndpointSummary : Summary r.Id, "The Id of the book to update. Required."); RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); @@ -57,8 +56,8 @@ public class UpdateBookEndpointSummary : Summary r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional."); RequestParam(r => r.Edition, "The edition of the book. Optional."); RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional."); - RequestParam(r => r.Series, "The series the book is part of. Optional."); - RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional."); + RequestParam(r => r.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional."); + RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. Optional."); RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional."); RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional."); RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional."); @@ -73,7 +72,6 @@ public class UpdateBookEndpointSummary : Summary r.Ratings, "The list of ratings of the book. Required."); ExampleRequest = new UpdateBookRequest( - Id: Guid.NewGuid().ToString(), Metadata: new WrittenContentMetadataDto( Title: "The Fellowship of the Ring", OriginalTitle: "The Fellowship of the Ring", @@ -139,25 +137,13 @@ public class UpdateBookEndpointSummary : Summary(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); ResponseParam(r => r.Edition, "The edition of the book, if applicable."); ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); - ResponseParam(r => r.Series, "The series the book is part of, if applicable."); - ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null."); ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); @@ -218,7 +204,7 @@ public class UpdateBookEndpointSummary : Summary(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); - ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played."); ResponseParam(r => r.Ratings, "The list of ratings for the book."); ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); @@ -297,25 +283,13 @@ public class UpdateBookEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "MetadataCannotBeNull", "TitleCannotBeEmpty", @@ -399,7 +405,6 @@ public class UpdateBookEndpointSummary : Summary /// Gets or sets the Id of the book to update, taken from the route. /// - public string? Id { get; set; } + public string? BookId { get; set; } + + /// + /// Gets or sets the Id of the media library the book belongs to. + /// + public Guid LibraryId { get; set; } /// /// Gets or sets the written content metadata of the book. @@ -96,7 +102,7 @@ public class UpdateBookRequest public List? ISBNs { get; set; } /// - /// Gets or sets the list of media contributors of the book. + /// Gets or sets the list of media contributors of the book. Required. /// public List? Contributors { get; set; } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs index e51e1720..469a89e2 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; /// -/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-save-book route. +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book route. /// public class SaveBookEndpoint : BaseEndpoint { @@ -50,14 +50,14 @@ public class SaveBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) { - // The book is identified by the {id} route value, not by the id posted in the form, so that a mismatched id can never redirect + // The book is identified by the {bookId} route value, not by the id posted in the form, so that a mismatched id can never redirect // the update to another book; the value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted // route value can never escape its URL segment, and an unparseable id is reported by the API as a missing book id. - string routeId = HttpContext.Request.RouteValues["id"]?.ToString() ?? string.Empty; - request.Id = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString(); + string routeId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty; + request.BookId = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString(); BookDetailsDto book = await _apiHttpClient.PutAsync( - ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false); + ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(book); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs index a5fe6ee9..3dc3b0c6 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs @@ -1,10 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.MediaContributors; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.MediaContributors; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Enums.Common; using System; @@ -28,7 +29,8 @@ public class SaveBookEndpointSummary : Summary r.Id, "The unique identifier of the book to update. Required."); + RequestParam(r => r.BookId, "The unique identifier of the book to update. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); @@ -72,7 +74,8 @@ public class SaveBookEndpointSummary : Summary /// Creates a random valid command to update a book. /// - /// Optional. The Id of the book to update. + /// Optional. The Id of the media library the book belongs to. + /// Optional. The Id of the book to update. /// Optional. The written content metadata of the book. /// Optional. The format of the book. /// Optional. The edition of the book. @@ -53,7 +54,8 @@ public class UpdateBookCommandFixture /// Whether the properties that are not explicitly provided should be randomized, or forced to . /// The created command to update a book. public UpdateBookCommand Create( - Guid? id = null, + string? libraryId = null, + string? bookId = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, string? edition = null, @@ -69,13 +71,14 @@ public class UpdateBookCommandFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, bool includeMetadata = true, bool includeOptionalProperties = true) { return new Faker() .CustomInstantiator(f => new UpdateBookCommand( + default, default, default!, default, @@ -90,12 +93,13 @@ public class UpdateBookCommandFixture default, default, default, - default, + default!, default!, default!, default! )) - .RuleFor(x => x.Id, id ?? Guid.NewGuid()) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString()) + .RuleFor(x => x.BookId, bookId ?? Guid.NewGuid().ToString()) .RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null) .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) @@ -112,7 +116,7 @@ public class UpdateBookCommandFixture .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs index f71ecc3f..637549a0 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -24,13 +24,12 @@ public class UpdateBookRequestFixture { private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid request to update a book. /// - /// Optional. The Id of the book to update. /// Optional. The written content metadata of the book. /// Optional. The format of the book. /// Optional. The edition of the book. @@ -49,11 +48,8 @@ public class UpdateBookRequestFixture /// Optional. The contributors of the book. /// Optional. The ratings of the book. /// Whether the properties that are not explicitly provided should be randomized, or forced to . - /// Optional. The raw string value of the Id of the book to update. Takes precedence over . - /// Whether the Id should be included, or forced to . /// The created request to update a book. public UpdateBookRequest Create( - Guid? id = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, string? edition = null, @@ -69,15 +65,12 @@ public class UpdateBookRequestFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, - bool includeOptionalProperties = true, - string? rawId = null, - bool includeId = true) + bool includeOptionalProperties = true) { return new Faker() .CustomInstantiator(f => new UpdateBookRequest( - default, default!, default, default, @@ -96,7 +89,6 @@ public class UpdateBookRequestFixture default!, default! )) - .RuleFor(x => x.Id, f => includeId ? (rawId ?? id?.ToString() ?? Guid.NewGuid().ToString()) : null) .RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create()) .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) @@ -113,7 +105,7 @@ public class UpdateBookRequestFixture .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs index 675dc2f8..ba22b06e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -31,17 +31,20 @@ public class UpdateBookRequestFixture /// Creates a new instance with randomized test data. /// /// Optional Id of the book to update. + /// Optional Id of the media library the book belongs to. /// Optional written content metadata of the book. /// Whether the properties that are not explicitly provided should be randomized, or forced to . /// A configured instance. public UpdateBookRequest Create( Guid? id = null, + Guid? libraryId = null, WrittenContentMetadataDto? metadata = null, bool includeOptionalProperties = true) { return new UpdateBookRequest { - Id = id?.ToString() ?? Guid.NewGuid().ToString(), + BookId = id?.ToString() ?? Guid.NewGuid().ToString(), + LibraryId = libraryId ?? Guid.NewGuid(), Metadata = metadata ?? (includeOptionalProperties ? _writtenContentMetadataDtoFixture.Create() : null), Format = includeOptionalProperties ? _faker.PickRandom() : null, Edition = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index a7ae66b2..cdd64907 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -1,17 +1,25 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== +using Bogus; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; @@ -46,9 +54,17 @@ public class UpdateBookEndpointTests : IClassFixture @@ -75,10 +91,10 @@ public class UpdateBookEndpointTests : IClassFixture duplicatedContributors = + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + Guid contributorId = Guid.NewGuid(); + List duplicatedContributors = [ - new MediaContributorDto( - new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), - new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author)), - new MediaContributorDto( - new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), - new MediaContributorRoleDto("illustrator", MediaContributorRoleCategory.Illustrator)) + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) ]; - UpdateBookRequest request = _requestBookFixture.Create(id: bookId, contributors: duplicatedContributors, isbns: [], ratings: [], includeOptionalProperties: false); + await SeedContributorsAsync(duplicatedContributors); + UpdateBookRequest request = _requestBookFixture.Create(contributors: duplicatedContributors, isbns: [], ratings: [], includeOptionalProperties: false); // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author"); List links = dbContext.Books .Include(book => book.BookContributors) .Single(book => book.Id == bookId) .BookContributors .ToList(); Assert.Equal(2, links.Count); - Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId)); - Assert.Contains(links, link => link.RoleName == "author"); - Assert.Contains(links, link => link.RoleName == "illustrator"); + Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId)); + Assert.Contains(links, link => link.Role == MediaContributorRole.Author); + Assert.Contains(links, link => link.Role == MediaContributorRole.Illustrator); } [Fact] - public async Task UpdateBook_WhenRouteBookDoesNotExistButBodyIdExists_ShouldNotUpdateTheBodyBook() + public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldNotUpdateAnyBook() { // Arrange Guid userId = GetCurrentUserId(); (Guid libraryId, Guid bodyBookId) = await SeedLibraryAndBookAsync(userId, "Body Book Title"); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _requestBookFixture.Create(id: bodyBookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply")); + UpdateBookRequest request = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply")); // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -157,10 +170,11 @@ public class UpdateBookEndpointTests : IClassFixture + /// Updates the book described by the provided request, seeding the media library, the book and the referenced media contributors. + /// + /// The request to send. + /// The HTTP response of the PUT request. + private async Task PutBookAsync(UpdateBookRequest request) + { + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + await SeedContributorsAsync(request.Contributors); + return await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert. + /// The validation error codes expected in the response. + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"])); + } + /// /// Seeds a library owned by and a book belonging to it. /// @@ -261,6 +1848,26 @@ public class UpdateBookEndpointTests : IClassFixture + /// Seeds the media contributors referenced by the provided book contributors, so that the handler finds them already existing. + /// + /// The contributors of the book request. + private async Task SeedContributorsAsync(List? contributors) + { + if (contributors is null || contributors.Count == 0) + return; + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + foreach (Guid contributorId in contributors.Select(contributor => contributor.ContributorId).Distinct()) + { + if (contributorId == Guid.Empty || await dbContext.MediaContributors.AnyAsync(contributor => contributor.Id == contributorId)) + continue; + dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString())); + } + await dbContext.SaveChangesAsync(); + } + /// /// Seeds a user distinct from the authenticated test user and returns its Id. /// @@ -295,4 +1902,4 @@ public class UpdateBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -60,7 +61,7 @@ public class SaveBookEndpointTests : IClassFixture using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == bookId.ToString()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == bookId.ToString()); } [Fact] @@ -70,9 +71,10 @@ public class SaveBookEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid routeId = Guid.NewGuid(); Guid bodyId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: routeId); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(routeId, request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -84,8 +86,8 @@ public class SaveBookEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == routeId.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == routeId.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}"); } [Fact] @@ -103,7 +105,7 @@ public class SaveBookEndpointTests : IClassFixture // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}"); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{request.LibraryId}/books/{bookId}"); } [Fact] diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index 3864d177..18cbfadb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -2,10 +2,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -39,15 +44,23 @@ public class UpdateBookEndpointTests : IClassFixture { // Arrange HttpClient client = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/books/{bookId}", problemDetails["instance"].GetProperty("value").GetString()); } [Theory] @@ -58,10 +71,12 @@ public class UpdateBookEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle)); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert // The injected title is validated and handled by the parameterized update flow: the route book does not exist, @@ -83,15 +98,16 @@ public class UpdateBookEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{Uri.EscapeDataString(maliciousBookId)}", request); // Assert // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command - // mapping and becomes Guid.Empty, which the command validator reports as a clean validation error. The response must - // not leak stack traces, database details, or the injected payload, and the body Id never redirects the update. + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -105,16 +121,17 @@ public class UpdateBookEndpointTests : IClassFixture } [Fact] - public async Task UpdateBook_WhenRouteBookDoesNotExistEvenIfBodyIdDiffers_ShouldReturnNotFound() + public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldReturnNotFound() { // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -127,4 +144,39 @@ public class UpdateBookEndpointTests : IClassFixture await _apiFactory.RemoveTestUserAsync(username); } + + [Fact] + public async Task UpdateBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index 75fa6a13..c9f132d2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -45,10 +45,11 @@ public class SaveBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bodyId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); string normalizedBookId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{normalizedBookId}", _bookDetailsDtoFixture.Create()); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{normalizedBookId}", _bookDetailsDtoFixture.Create()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId)); + HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId)); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); // Act @@ -63,8 +64,8 @@ public class SaveBookEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == normalizedBookId); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == normalizedBookId); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}"); } [Theory] @@ -75,11 +76,12 @@ public class SaveBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId); request.Metadata!.Title = maliciousTitle; BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); expectedBook.Metadata!.Title = maliciousTitle; - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -93,7 +95,7 @@ public class SaveBookEndpointTests : IClassFixture Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs index f913bdd4..645c70f1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs @@ -1,8 +1,17 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -14,45 +23,125 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookCommandMappingTests { - private readonly UpdateBookCommandFixture _commandFixture = new(); + private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); [Fact] - public void ToBookMetadataDto_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() { // Arrange - UpdateBookCommand command = _commandFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString(), bookId: bookId.ToString()); + BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub"); + DateTime createdOnUtc = existingBook.CreatedOnUtc; // Act - BookMetadataDto result = command.ToBookMetadataDto(); + Result result = command.ToDomainEntity(existingBook); // Assert - Assert.NotNull(result); - Assert.Equal(command.Metadata!.Title, result.Title); - Assert.Equal(command.Metadata.OriginalTitle, result.OriginalTitle); - Assert.Equal(command.Metadata.Description, result.Description); - Assert.Equal(command.Metadata.ReleaseInfo, result.ReleaseInfo); - Assert.Equal(command.Metadata.Genres, result.Genres); - Assert.Equal(command.Metadata.Tags, result.Tags); - Assert.Equal(command.Metadata.Language, result.Language); - Assert.Equal(command.Metadata.OriginalLanguage, result.OriginalLanguage); - Assert.Equal(command.Metadata.Publisher, result.Publisher); - Assert.Equal(command.Metadata.PageCount, result.PageCount); - Assert.Equal(command.Format, result.Format); - Assert.Equal(command.Edition, result.Edition); - Assert.Equal(command.VolumeNumber, result.VolumeNumber); - Assert.Equal(command.Series, result.Series); - Assert.Equal(command.ASIN, result.ASIN); - Assert.Equal(command.GoodreadsId, result.GoodreadsId); - Assert.Equal(command.LCCN, result.LCCN); - Assert.Equal(command.OCLCNumber, result.OCLCNumber); - Assert.Equal(command.OpenLibraryId, result.OpenLibraryId); - Assert.Equal(command.LibraryThingId, result.LibraryThingId); - Assert.Equal(command.GoogleBooksId, result.GoogleBooksId); - Assert.Equal(command.BarnesAndNobleId, result.BarnesAndNobleId); - Assert.Equal(command.AppleBooksId, result.AppleBooksId); - Assert.Equal(command.ISBNs, result.Isbns); - Assert.Equal(command.Contributors, result.Contributors); - Assert.Equal(command.Ratings, result.Ratings); - Assert.Null(result.CoverImagePath); + Assert.False(result.IsFailure); + Assert.Equal(bookId, result.Value.Id.Value); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(existingBook.Path, result.Value.Path); + Assert.Equal(createdOnUtc, result.Value.CreatedOnUtc); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title); + Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count); + Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count); + Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count); + Assert.True(result.Value.Format.HasValue); + Assert.Equal(command.Format, result.Value.Format.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCommand command = _commandBookFixture.Create( + libraryId: libraryId.ToString(), + bookId: bookId.ToString(), + isbns: [], + contributors: [], + ratings: [], + includeOptionalProperties: false); + BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub"); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bookId, result.Value.Id.Value); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(existingBook.Path, result.Value.Path); + Assert.Empty(result.Value.ISBNs); + Assert.Empty(result.Value.Contributors); + Assert.Empty(result.Value.Ratings); + Assert.False(result.Value.Format.HasValue); + Assert.False(result.Value.Edition.HasValue); + Assert.False(result.Value.VolumeNumber.HasValue); + Assert.False(result.Value.ASIN.HasValue); + Assert.False(result.Value.GoodreadsId.HasValue); + Assert.False(result.Value.LCCN.HasValue); + Assert.False(result.Value.OCLCNumber.HasValue); + Assert.False(result.Value.OpenLibraryId.HasValue); + Assert.False(result.Value.LibraryThingId.HasValue); + Assert.False(result.Value.GoogleBooksId.HasValue); + Assert.False(result.Value.BarnesAndNobleId.HasValue); + Assert.False(result.Value.AppleBooksId.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description); + } + + [Fact] + public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs index 20937a11..11bd4200 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs @@ -1,6 +1,7 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -18,20 +19,23 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class UpdateBookRequestMappingTests { private readonly UpdateBookRequestFixture _requestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(id: bookId); + UpdateBookRequest request = _requestFixture.Create(); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); - Assert.Equal(bookId, result.Id); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(bookId.ToString(), result.BookId); Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.Format, result.Format); Assert.Equal(request.Edition, result.Edition); @@ -55,15 +59,16 @@ public class UpdateBookRequestMappingTests public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(id: bookId, includeOptionalProperties: false); + UpdateBookRequest request = _requestFixture.Create(includeOptionalProperties: false); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); - Assert.Equal(bookId, result.Id); + Assert.Equal(bookId.ToString(), result.BookId); Assert.NotNull(result.Metadata); Assert.Equal(request.Metadata, result.Metadata); Assert.Null(result.Format); @@ -88,21 +93,20 @@ public class UpdateBookRequestMappingTests public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _requestFixture.Create( isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], contributors: [ - new( - new("John Doe", "John Smith Doe"), - new("Author", MediaContributorRoleCategory.Author) - ) + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author) ], ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], includeOptionalProperties: false ); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); @@ -112,41 +116,16 @@ public class UpdateBookRequestMappingTests } [Fact] - public void ToCommand_WhenMappingRequestWithNullId_ShouldMapEmptyGuid() + public void ToCommand_WhenRouteValuesAreNotParseable_ShouldMapThemAsIs() { // Arrange - UpdateBookRequest request = _requestFixture.Create(includeId: false); + UpdateBookRequest request = _requestFixture.Create(includeOptionalProperties: false); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand("not-a-library-guid", "not-a-guid"); // Assert - Assert.Equal(Guid.Empty, result.Id); - } - - [Fact] - public void ToCommand_WhenMappingRequestWithEmptyId_ShouldMapEmptyGuid() - { - // Arrange - UpdateBookRequest request = _requestFixture.Create(rawId: string.Empty); - - // Act - UpdateBookCommand result = request.ToCommand(); - - // Assert - Assert.Equal(Guid.Empty, result.Id); - } - - [Fact] - public void ToCommand_WhenMappingRequestWithUnparseableId_ShouldMapEmptyGuid() - { - // Arrange - UpdateBookRequest request = _requestFixture.Create(rawId: "not-a-guid"); - - // Act - UpdateBookCommand result = request.ToCommand(); - - // Assert - Assert.Equal(Guid.Empty, result.Id); + Assert.Equal("not-a-library-guid", result.LibraryId); + Assert.Equal("not-a-guid", result.BookId); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs index 8bc4854e..71f14199 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; @@ -12,7 +12,10 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Boo using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -45,11 +48,15 @@ public class UpdateBookCommandHandlerTests private readonly IValidator _mockValidator; private readonly UpdateBookCommandHandler _sut; private readonly Guid _userId; - private static readonly Error s_findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor."); private readonly UpdateBookCommandFixture _commandBookFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -59,6 +66,7 @@ public class UpdateBookCommandHandlerTests _mockBookRepository = Substitute.For(); _mockMediaContributorRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); _mockAuthorizationService = Substitute.For(); @@ -72,10 +80,22 @@ public class UpdateBookCommandHandlerTests _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockValidator.Validate(Arg.Any()).Returns([]); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(_mediaContributorEntityFixture.Create())); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => new MediaContributorEntity + { + Id = contributorId, + DisplayName = contributorId.ToString(), + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + })]); + }); _sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } @@ -85,18 +105,25 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + BookEntity? updatedBook = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedBook)); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedBook = callInfo.Arg(); + return Result.Updated; + }); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(command.Id, result.Value.Id); + Assert.Equal(Guid.Parse(command.BookId!), result.Value.Id); Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title); - Assert.Equal(command.Contributors, result.Value.Contributors); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count); await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -114,7 +141,7 @@ public class UpdateBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -131,7 +158,7 @@ public class UpdateBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -139,7 +166,7 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -157,7 +184,7 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); // Act @@ -174,8 +201,8 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -192,34 +219,13 @@ public class UpdateBookCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutSaving() - { - // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(s_findOrCreateError); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(s_findOrCreateError, result.FirstError); - await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving() { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookNotFound); @@ -234,22 +240,21 @@ public class UpdateBookCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole() + public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnce() { // Arrange + Guid contributorId = Guid.NewGuid(); UpdateBookCommand command = _commandBookFixture.Create( contributors: [ - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) ]); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(contributor)); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookEntity? updatedEntity = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedEntity)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => { @@ -262,34 +267,30 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "John Doe", "John Smith Doe", Arg.Any()); Assert.NotNull(updatedEntity); Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId)); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author"); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator"); + Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId)); + Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author); + Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce() + public async Task HandleAsync_WhenContributorsHaveDistinctIds_ShouldLinkEachContributor() { // Arrange + Guid firstContributorId = Guid.NewGuid(); + Guid secondContributorId = Guid.NewGuid(); UpdateBookCommand command = _commandBookFixture.Create( contributors: [ - _mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator) ]); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); - MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => Result.From(callInfo.ArgAt(0) == "Author One" ? firstContributor : secondContributor)); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookEntity? updatedEntity = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedEntity)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => { @@ -302,14 +303,10 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "Author One", "Author One Legal", Arg.Any()); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "Author Two", "Author Two Legal", Arg.Any()); Assert.NotNull(updatedEntity); Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.Equal(firstContributor.Id, updatedEntity.BookContributors[0].MediaContributorId); - Assert.Equal(secondContributor.Id, updatedEntity.BookContributors[1].MediaContributorId); + Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId); + Assert.Equal(secondContributorId, updatedEntity.BookContributors[1].MediaContributorId); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -318,7 +315,7 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); existingBook.MetadataStatus = MetadataStatus.Enriched; existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc); existingBook.MetadataProvider = "TestProvider"; @@ -334,10 +331,15 @@ public class UpdateBookCommandHandlerTests CreatedBy = Guid.NewGuid(), UpdatedBy = null }); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); + BookEntity? updatedBook = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedBook)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); + .Returns(callInfo => + { + updatedBook = callInfo.Arg(); + return Result.Updated; + }); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -349,4 +351,145 @@ public class UpdateBookCommandHandlerTests Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider); Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath); } + + [Fact] + public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.TagNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2025, 1, 1), + originalReleaseYear: 2025, + reReleaseDate: new DateOnly(2024, 1, 1), + reReleaseYear: 2024))); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + // The stored book belongs to a different library than the one named by the route. + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs index 3decf083..fb904660 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs @@ -1,8 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; @@ -10,6 +12,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -27,49 +30,12 @@ public class UpdateBookCommandValidatorTests private readonly UpdateBookCommandValidator _validator = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - Assert.Empty(result); - } - - [Fact] - public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(id: Guid.Empty); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeMetadata: false); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); - } + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void Validate_WhenTitleIsNull_ShouldHaveValidationError() @@ -97,6 +63,110 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); } + [Fact] + public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + [Fact] public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { @@ -110,6 +180,123 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); } + [Fact] + public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 0, null, null, null, null))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 10000, null, null, null, null))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 0, null, null))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 10000, null, null))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + [Fact] public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { @@ -123,6 +310,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); } + [Fact] + public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + [Fact] public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { @@ -136,6 +349,45 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); } + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + [Fact] public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { @@ -149,6 +401,58 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); } + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + [Fact] public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { @@ -162,6 +466,305 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } + [Fact] + public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); + } + + [Fact] + public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(format: BookFormat.Hardcover); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); + } + [Fact] public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { @@ -175,6 +778,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.UnknownBookFormat); } + [Fact] + public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + } + [Fact] public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { @@ -188,6 +817,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); } + [Fact] + public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 0); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + [Fact] public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { @@ -201,6 +856,100 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } + [Fact] + public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 1); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + //[Fact] + //public void Validate_WhenSeriesTitleIsEmpty_ShouldHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = string.Empty } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Description); + //} + + //[Fact] + //public void Validate_WhenSeriesTitleExceeds255Characters_ShouldHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(256) } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); + //} + + //[Fact] + //public void Validate_WhenSeriesTitleIsValid_ShouldNotHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(200) } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldNotHaveValidationErrorFor(x => x.Series.Title); + //} + + [Fact] + public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(10)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); + } + [Fact] public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { @@ -214,6 +963,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); } + [Fact] + public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123456789"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + [Fact] public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { @@ -227,6 +1002,58 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } + [Fact] + public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123 456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123-456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n78890351"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + [Fact] public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { @@ -241,7 +1068,111 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenOclcNumberHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: new Faker().Random.String2(15)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n12"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocm12345678"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocn123456789"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "on1234567890"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "12345678"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); @@ -254,7 +1185,33 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenOpenLibraryIdHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456M"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); @@ -267,10 +1224,88 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenGoogleBooksIdHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: "invalid!"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123ABC"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456X"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -280,10 +1315,49 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenBarnesAndNobleIdIsNotTenDigits_ShouldHaveValidationError() + public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: "abc123"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -293,10 +1367,62 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenAppleBooksIdHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "395211"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); // Act List result = _validator.TestValidate(bookCommand); @@ -306,7 +1432,7 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbnsIsNull_ShouldHaveValidationError() + public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); @@ -319,7 +1445,7 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbnValueIsEmpty_ShouldHaveValidationError() + public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); @@ -332,10 +1458,23 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbn13ValueIsInvalid_ShouldHaveValidationError() + public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); + } + + [Fact] + public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -344,34 +1483,99 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); } + [Fact] + public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.UnknownIsbnFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); + } + + [Fact] + public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); + } + [Fact] public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + UpdateBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null }; // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); } [Fact] - public void Validate_WhenContributorDisplayNameIsEmpty_ShouldHaveValidationError() + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); } [Fact] - public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); @@ -384,7 +1588,7 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenRatingValueIsNegative_ShouldHaveValidationError() + public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); @@ -395,4 +1599,147 @@ public class UpdateBookCommandValidatorTests // Assert result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); } + + [Fact] + public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Fact] + public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Fact] + public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeOptionalProperties: false)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs index be7ca823..49145a8f 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -36,7 +36,6 @@ public class UpdateBookRequestTests // Assert Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Id)); Assert.NotNull(sut.Metadata); Assert.NotNull(sut.ISBNs); Assert.NotEmpty(sut.ISBNs); @@ -82,10 +81,9 @@ public class UpdateBookRequestTests UpdateBookRequest sut = _updateBookRequestFixture.Create(); // Act - (string? id, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; + (WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; // Assert - Assert.Equal(sut.Id, id); Assert.Equal(sut.Metadata, metadata); Assert.Equal(sut.Format, format); Assert.Equal(sut.Edition, edition); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index ce8b42b6..666ce786 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookEndpointTests { - private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _mockHandler; private readonly UpdateBookEndpoint _sut; private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); private readonly BookResponseFixture _bookResponseFixture = new(); @@ -34,7 +34,7 @@ public class UpdateBookEndpointTests /// public UpdateBookEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); } @@ -42,13 +42,14 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); - ConfigureRequest(routeId.ToString()); + ConfigureRequest(libraryId.ToString(), routeId.ToString()); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -62,13 +63,14 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); - ConfigureRequest(routeId.ToString()); + ConfigureRequest(libraryId.ToString(), routeId.ToString()); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -88,13 +90,14 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error validationError = Error.Validation(description: "BookIdCannotBeEmpty"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(validationError); - ConfigureRequest(routeId.ToString()); + ConfigureRequest(libraryId.ToString(), routeId.ToString()); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -112,15 +115,16 @@ public class UpdateBookEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldSendUpdateBookCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToHandler() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(routeId.ToString()); + ConfigureRequest(libraryId.ToString(), routeId.ToString()); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -128,7 +132,8 @@ public class UpdateBookEndpointTests // Assert await _mockHandler.Received(1).HandleAsync( Arg.Is(command => - command.Id == routeId && + command.LibraryId == libraryId.ToString() && + command.BookId == routeId.ToString() && command.Metadata == request.Metadata && command.Format == request.Format && command.Edition == request.Edition && @@ -140,80 +145,40 @@ public class UpdateBookEndpointTests } [Fact] - public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldSendCommandWithRouteId() - { - // Arrange - Guid routeId = Guid.NewGuid(); - Guid bodyId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(routeId.ToString()); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == routeId && command.Id != bodyId), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId() + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() { // Arrange UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest("not-a-guid"); + ConfigureRequest("not-a-library-guid", "not-a-guid"); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"), Arg.Is(cancellationToken)); } [Fact] - public async Task ExecuteAsync_WhenRouteIdIsEmpty_ShouldSendCommandWithEmptyBookId() + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() { // Arrange UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(string.Empty); + ConfigureRequestWithoutIds(); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldSendCommandWithEmptyBookId() - { - // Arrange - UpdateBookRequest request = _updateBookRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequestWithoutId(); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(command => command.LibraryId == null && command.BookId == null), Arg.Is(cancellationToken)); } @@ -221,8 +186,9 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -235,7 +201,7 @@ public class UpdateBookEndpointTests callInfo.Arg().ThrowIfCancellationRequested(); return Result.From(_bookResponseFixture.Create()); }, callInfo.Arg())); - ConfigureRequest(routeId.ToString()); + ConfigureRequest(libraryId.ToString(), routeId.ToString()); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); @@ -248,19 +214,22 @@ public class UpdateBookEndpointTests } /// - /// Sets the id route value the endpoint reads the book Id from. + /// Sets the libraryId and id route values the endpoint reads the identifiers from. /// - /// The raw route value of the book Id. - private void ConfigureRequest(string routeId) + /// The raw route value of the library Id. + /// The raw route value of the book Id. + private void ConfigureRequest(string libraryId, string bookId) { - _sut.HttpContext.Request.RouteValues["id"] = routeId; + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; + _sut.HttpContext.Request.RouteValues["bookId"] = bookId; } /// - /// Leaves the id route value unset. + /// Leaves the libraryId and id route values unset. /// - private void ConfigureRequestWithoutId() + private void ConfigureRequestWithoutIds() { - _sut.HttpContext.Request.RouteValues.Remove("id"); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index e52f6031..2d338d39 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -55,8 +55,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId), Arg.Any()); } @@ -67,7 +67,7 @@ public class SaveBookEndpointTests string routeId = Guid.NewGuid().ToString(); string bodyId = Guid.NewGuid().ToString(); UpdateBookRequest request = _updateBookRequestFixture.Create(); - request.Id = bodyId; + request.BookId = bodyId; BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(expectedBook); @@ -78,8 +78,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId && forwardedRequest.Id != bodyId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId && forwardedRequest.BookId != bodyId), Arg.Any()); } @@ -100,8 +100,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId), Arg.Any()); } @@ -121,8 +121,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId), Arg.Any()); } @@ -153,7 +153,7 @@ public class SaveBookEndpointTests /// The raw route value of the book Id. private void ConfigureRequest(string routeId) { - _sut.HttpContext.Request.RouteValues["id"] = routeId; + _sut.HttpContext.Request.RouteValues["bookId"] = routeId; } ///