From 0eb7b453f6dfd3d4e8ff30e5f472ca45ce27408d Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 24 Aug 2024 22:11:55 +0300 Subject: [PATCH] Adds the capability of adding a Book via API --- docs/technical/api/Api.Book.md | 125 +++++++++++++++ .../{ => domain}/Aggregates.FileManagement.md | 0 .../{ => domain}/Aggregates.VideoLibrary.md | 0 .../Aggregates.WrittenContentLibrary.md | 94 ++---------- .../technical/{ => domain}/Common.Metadata.md | 0 .../{ => domain}/UbiquitousLanguage.md | 0 docs/technical/requests/books/Add.http | 96 ++++++++++++ docs/technical/requests/books/Get.http | 1 + .../Common/Behaviors/ValidationBehavior.cs | 2 +- .../Converters/OptionalJsonConverter.cs | 45 ++++++ .../OptionalJsonConverterFactory.cs | 41 +++++ .../ApplicationLayerServices.cs | 8 + .../Common/Enums/BookFormat.cs | 25 +++ .../Common/Enums/BookRatingSource.cs | 17 +++ .../Common/Enums/IsbnFormat.cs | 15 ++ .../Common/Enums/MediaContributorRole.cs | 17 +++ .../Common/Models/Books/BookDto.cs | 29 ++++ .../Common/Models/Books/BookRatingDto.cs | 16 ++ .../Common/Models/Books/BookSeriesDto.cs | 8 + .../Common/Models/Books/IsbnDto.cs | 13 ++ .../Models/Books/WrittenContentMetadataDto.cs | 21 +++ .../Common/Models/Common/GenreDto.cs | 8 + .../Common/Models/Common/LanguageInfoDto.cs | 10 ++ .../Common/Models/Common/RatingDto.cs | 10 ++ .../Common/Models/Common/ReleaseInfoDto.cs | 13 ++ .../Common/Models/Common/TagDto.cs | 8 + .../Contributors/MediaContributorDto.cs | 9 ++ .../Contributors/MediaContributorNameDto.cs | 9 ++ .../Contributors/MediaContributorRoleDto.cs | 9 ++ .../Books/Commands/AddBookCommand.cs | 34 +++++ .../Books/Commands/AddBookCommandHandler.cs | 143 ++++++++++++++++++ .../Books/Commands/AddBookCommandValidator.cs | 95 ++++++++++++ .../Lumina.Application.csproj | 33 ++-- .../Lumina.DataAccess.csproj | 4 + .../Common/Enums/MediaContributorRole.cs | 27 ---- .../Common/Primitives/Optional.cs | 49 +++++- .../ValueObjects/Metadata/BaseMetadata.cs | 8 +- .../Common/ValueObjects/Metadata/Genre.cs | 2 +- .../ValueObjects/Metadata/LanguageInfo.cs | 5 +- .../Common/ValueObjects/Metadata/Rating.cs | 61 +------- .../ValueObjects/Metadata/ReleaseInfo.cs | 2 +- .../Common/ValueObjects/Metadata/Tag.cs | 2 +- .../ValueObjects/AudioMetadata.cs | 8 +- .../ValueObjects/FileInfo.cs | 2 +- .../ValueObjects/StreamInfo.cs | 2 +- .../ValueObjects/MediaContributorRole.cs | 59 ++++++++ .../ValueObjects/VideoMetadata.cs | 14 +- .../BookLibraryAggregate/Book.cs | 8 +- .../Entities/BookSeries.cs | 53 ++++++- .../ValueObjects/BookId.cs | 2 - .../ValueObjects/BookRating.cs | 83 ++++++++++ .../ValueObjects/BookSeriesId.cs | 7 +- .../ValueObjects/WrittenContentMetadata.cs | 46 +++++- .../Lumina.Infrastructure.csproj | 8 +- .../Common/Contracts/Books/AddBookRequest.cs | 31 ++++ .../OptionalJsonConverterFactory.cs | 0 .../PresentationApiLayerServices.cs | 16 +- .../Errors/CustomProblemDetailsFactory.cs | 4 - .../Common/Mapping/BookMappingConfig.cs | 30 ++++ .../Controllers/Books/BooksController.cs | 36 +++-- .../Lumina.Presentation.Api.csproj | 8 +- 61 files changed, 1276 insertions(+), 255 deletions(-) create mode 100644 docs/technical/api/Api.Book.md rename docs/technical/{ => domain}/Aggregates.FileManagement.md (100%) rename docs/technical/{ => domain}/Aggregates.VideoLibrary.md (100%) rename docs/technical/{ => domain}/Aggregates.WrittenContentLibrary.md (64%) rename docs/technical/{ => domain}/Common.Metadata.md (100%) rename docs/technical/{ => domain}/UbiquitousLanguage.md (100%) create mode 100644 docs/technical/requests/books/Add.http create mode 100644 docs/technical/requests/books/Get.http create mode 100644 src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs create mode 100644 src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs create mode 100644 src/Lumina.Application/Common/Enums/BookFormat.cs create mode 100644 src/Lumina.Application/Common/Enums/BookRatingSource.cs create mode 100644 src/Lumina.Application/Common/Enums/IsbnFormat.cs create mode 100644 src/Lumina.Application/Common/Enums/MediaContributorRole.cs create mode 100644 src/Lumina.Application/Common/Models/Books/BookDto.cs create mode 100644 src/Lumina.Application/Common/Models/Books/BookRatingDto.cs create mode 100644 src/Lumina.Application/Common/Models/Books/BookSeriesDto.cs create mode 100644 src/Lumina.Application/Common/Models/Books/IsbnDto.cs create mode 100644 src/Lumina.Application/Common/Models/Books/WrittenContentMetadataDto.cs create mode 100644 src/Lumina.Application/Common/Models/Common/GenreDto.cs create mode 100644 src/Lumina.Application/Common/Models/Common/LanguageInfoDto.cs create mode 100644 src/Lumina.Application/Common/Models/Common/RatingDto.cs create mode 100644 src/Lumina.Application/Common/Models/Common/ReleaseInfoDto.cs create mode 100644 src/Lumina.Application/Common/Models/Common/TagDto.cs create mode 100644 src/Lumina.Application/Common/Models/Contributors/MediaContributorDto.cs create mode 100644 src/Lumina.Application/Common/Models/Contributors/MediaContributorNameDto.cs create mode 100644 src/Lumina.Application/Common/Models/Contributors/MediaContributorRoleDto.cs create mode 100644 src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommand.cs create mode 100644 src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs create mode 100644 src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs delete mode 100644 src/Lumina.Domain/Common/Enums/MediaContributorRole.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs create mode 100644 src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs create mode 100644 src/Lumina.Presentation.Api/Common/Contracts/Books/AddBookRequest.cs create mode 100644 src/Lumina.Presentation.Api/Common/Converters/OptionalJsonConverterFactory.cs create mode 100644 src/Lumina.Presentation.Api/Common/Mapping/BookMappingConfig.cs diff --git a/docs/technical/api/Api.Book.md b/docs/technical/api/Api.Book.md new file mode 100644 index 00000000..71947702 --- /dev/null +++ b/docs/technical/api/Api.Book.md @@ -0,0 +1,125 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Book](#book) + - [Add Book](#add-book) + - [Add Book Request](#add-book-request) + - [Add Book Response](#add-book-response) + - [Get Books](#get-books) + - [Get Books Request](#get-books-request) + - [Get Books Response](#get-books-response) + +## Book + +### Add Book + +#### Add Book Request + +```js +POST /books +``` + +```json +{ + "name": "Yummy Menu", + "description": "A menu with yummy food", + "sections": [ + { + "name": "Appetizers", + "description": "Starters", + "items": [ + { + "name": "Fried Pickles", + "description": "Deep fried pickles" + } + ] + } + ] +} +``` + +#### Add Book Response + +```js +201 Created +``` + +```json +{ + "id": "00000000-0000-0000-0000-000000000000", + "name": "Yummy Menu", + "description": "A menu with yummy food", + "averageRating": null, + "sections": [ + { + "id": "00000000-0000-0000-0000-000000000000", + "name": "Appetizers", + "description": "Starters", + "items": [ + { + "id": "00000000-0000-0000-0000-000000000000", + "name": "Fried Pickles", + "description": "Deep fried pickles" + } + ] + } + ], + "hostId": "00000000-0000-0000-0000-000000000000", + "dinnerIds": [ + "00000000-0000-0000-0000-000000000000", + ], + "menuReviewIds": [ + "00000000-0000-0000-0000-000000000000", + ], + "createdDateTime": "2020-01-01T00:00:00.0000000Z", + "updatedDateTime": "2020-01-01T00:00:00.0000000Z" +} +``` + +### Get Books + +#### Get Books Request + +```js +GET /books +``` + +#### Get Books Response + +```js +200 Ok +``` + +```json +[ + { + "id": "00000000-0000-0000-0000-000000000000", + "name": "Yummy Menu", + "description": "A menu with yummy food", + "averageRating": null, + "sections": [ + { + "id": "00000000-0000-0000-0000-000000000000", + "name": "Appetizers", + "description": "Starters", + "items": [ + { + "id": "00000000-0000-0000-0000-000000000000", + "name": "Fried Pickles", + "description": "Deep fried pickles" + } + ] + } + ], + "hostId": "00000000-0000-0000-0000-000000000000", + "dinnerIds": [ + "00000000-0000-0000-0000-000000000000", + ], + "menuReviewIds": [ + "00000000-0000-0000-0000-000000000000", + ], + "createdDateTime": "2020-01-01T00:00:00.0000000Z", + "updatedDateTime": "2020-01-01T00:00:00.0000000Z" + } +] +``` \ No newline at end of file diff --git a/docs/technical/Aggregates.FileManagement.md b/docs/technical/domain/Aggregates.FileManagement.md similarity index 100% rename from docs/technical/Aggregates.FileManagement.md rename to docs/technical/domain/Aggregates.FileManagement.md diff --git a/docs/technical/Aggregates.VideoLibrary.md b/docs/technical/domain/Aggregates.VideoLibrary.md similarity index 100% rename from docs/technical/Aggregates.VideoLibrary.md rename to docs/technical/domain/Aggregates.VideoLibrary.md diff --git a/docs/technical/Aggregates.WrittenContentLibrary.md b/docs/technical/domain/Aggregates.WrittenContentLibrary.md similarity index 64% rename from docs/technical/Aggregates.WrittenContentLibrary.md rename to docs/technical/domain/Aggregates.WrittenContentLibrary.md index 79ced4f7..8e8da241 100644 --- a/docs/technical/Aggregates.WrittenContentLibrary.md +++ b/docs/technical/domain/Aggregates.WrittenContentLibrary.md @@ -50,6 +50,16 @@ class Book "releaseCountry": "uk", "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", @@ -60,16 +70,6 @@ class Book "languageName": "English", "nativeName": "English" }, - "tags": [ - { "name": "epic fantasy" }, - { "name": "quest" }, - { "name": "middle-earth" } - ], - "genres": [ - { "name": "fantasy" }, - { "name": "adventure" }, - { "name": "classic" } - ], "publisher": "Houghton Mifflin", "pageCount": 398 }, @@ -119,78 +119,4 @@ class Book } ] } -{ - "id": { - "value": "00000000-0000-0000-0000-000000000000" - }, - "metadata": { - "title": "The Lord of the Rings - The Fellowship of the Ring", - "originalTitle": "The Lord of the Rings - The Fellowship of the Ring", - "description": "The greatest fantasy movie ever made", - "releaseInfo": { - "originalReleaseDate": "2001-12-19", - "originalReleaseYear": 2001, - "reReleaseDate": "2024-06-08", - "reReleaseYear": 2024, - "releaseCountry": "us", - "releaseVersion": "Director's Cut" - }, - "language": { - "languageCode": "en", - "languageName": "English", - "nativeName": "English" - }, - "originalLanguage": { - "languageCode": "en", - "languageName": "English", - "nativeName": "English" - }, - "tags": [ - { "name": "epic quest" }, - { "name": "friendship" }, - { "name": "middle-earth" } - ], - "genres": [ - { "name": "fantasy" }, - { "name": "adventure" }, - { "name": "action" } - ], - "publisher": "Allen & Unwin", - "pageCount": 432 - }, - "format": "Hardcover", - "edition": "First Edition", - "volumeNumber": 1, - "series": "The Lord of the Rings", - "isbn": "978-0261103573", - "asin": "B00GO9BZLU", - "goodreadsId": "3", - "lccn": "2001271784", - "oclcNumber": "46516480", - "openLibraryId": "OL7603610M", - "libraryThingId": "3203347", - "googleBooksId": "aWZzLPhY4o0C", - "barnesAndNobleId": "1100307790", - "koboId": "lord-of-the-rings-fellowship-of-the-ring", - "appleBooksId": "id395211", - "contributors": [ - { - "value": "00000000-0000-0000-0000-000000000000", - } - ], - "ratings": [ - { - "source": "Goodreads", - "value": 4.36, - "maxValue": 5, - "voteCount": 2345678 - }, - { - "source": "Amazon", - "value": 4.7, - "maxValue": 5, - "voteCount": 87654 - } - ] -} ``` \ No newline at end of file diff --git a/docs/technical/Common.Metadata.md b/docs/technical/domain/Common.Metadata.md similarity index 100% rename from docs/technical/Common.Metadata.md rename to docs/technical/domain/Common.Metadata.md diff --git a/docs/technical/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md similarity index 100% rename from docs/technical/UbiquitousLanguage.md rename to docs/technical/domain/UbiquitousLanguage.md diff --git a/docs/technical/requests/books/Add.http b/docs/technical/requests/books/Add.http new file mode 100644 index 00000000..5efcf86c --- /dev/null +++ b/docs/technical/requests/books/Add.http @@ -0,0 +1,96 @@ +POST {{host}}/api/v1/books +Content-Type: application/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": "uk", + "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": "2001025199", + "oclcNumber": "48494995", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "koboId": "the-fellowship-of-the-ring", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { + "name": "J.R.R. Tolkien", + "role": { + "name": "author", + "category": "book" + } + }, + { + "name": "Alan Lee", + "role": { + "name": "illustrator", + "category": "book" + } + } + ], + "ratings": [ + { + "source": "Goodreads", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ] +} \ No newline at end of file diff --git a/docs/technical/requests/books/Get.http b/docs/technical/requests/books/Get.http new file mode 100644 index 00000000..d5353d7f --- /dev/null +++ b/docs/technical/requests/books/Get.http @@ -0,0 +1 @@ +GET {{host}}/api/v1/books \ No newline at end of file diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs index d42a990e..2246a76d 100644 --- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs +++ b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs @@ -47,7 +47,7 @@ public class ValidationBehavior : IPipelineBehavior Error.Validation(validationFailure.ErrorMessage)); + var errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage)); // the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic // this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!) return (dynamic)errors; diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs new file mode 100644 index 00000000..61d764b1 --- /dev/null +++ b/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json; +using System.Text.Json.Serialization; +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Application.Common.Converters; + +/// +/// Converts an to and from JSON. +/// +/// The type of the value represented by the structure. +public class OptionalJsonConverter : JsonConverter> +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Reads and converts the JSON to an instance of . + /// + /// The to read from. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override Optional Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + return Optional.None(); + var value = JsonSerializer.Deserialize(ref reader, options); + return Optional.Some(value!); + } + + /// + /// Writes an value as JSON. + /// + /// The to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, Optional value, JsonSerializerOptions options) + { + if (value.HasValue) + JsonSerializer.Serialize(writer, value.Value, options); + else + writer.WriteNullValue(); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs new file mode 100644 index 00000000..92a66150 --- /dev/null +++ b/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json; +using System.Text.Json.Serialization; +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Application.Common.Converters; + +/// +/// A factory for creating instances. +/// +public class OptionalJsonConverterFactory : JsonConverterFactory +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Determines whether the converter can convert the specified type. + /// + /// The type to check for convertibility. + /// if the type is , otherwise. + public override bool CanConvert(Type typeToConvert) + { + if (!typeToConvert.IsGenericType) + return false; + return typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>); + } + + /// + /// Creates a converter for the specified type. + /// + /// The type for which to create a converter. + /// The serializer options to use. + /// A converter for . + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + Type valueType = typeToConvert.GetGenericArguments()[0]; + JsonConverter converter = (JsonConverter)Activator.CreateInstance( + typeof(OptionalJsonConverter<>).MakeGenericType(valueType))!; + return converter; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 221b509d..c83f12ac 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -3,6 +3,8 @@ using Lumina.Application.Common.Behaviors; using Mediator; using Microsoft.Extensions.DependencyInjection; using FluentValidation; +using MapsterMapper; +using Mapster; #endregion namespace Lumina.Application.Common.DependencyInjection; @@ -32,6 +34,12 @@ public static class ApplicationLayerServices // register fluent validators services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); + // register mapster configs in this assembly + var mapsterConfig = TypeAdapterConfig.GlobalSettings; + mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly); + services.AddSingleton(mapsterConfig); + services.AddScoped(); + return services; } #endregion diff --git a/src/Lumina.Application/Common/Enums/BookFormat.cs b/src/Lumina.Application/Common/Enums/BookFormat.cs new file mode 100644 index 00000000..4c8fb8ae --- /dev/null +++ b/src/Lumina.Application/Common/Enums/BookFormat.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Application.Common.Enums; + +/// +/// Represents the format of a book. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum BookFormat +{ + Hardcover, + Paperback, + MassMarketPaperback, + TradePaperback, + eBook, + Audiobook, + LargePrint, + BoardBook, + SpiralBound, + LibraryBinding, + LeatherBound, + PopupBook +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Enums/BookRatingSource.cs b/src/Lumina.Application/Common/Enums/BookRatingSource.cs new file mode 100644 index 00000000..1153a942 --- /dev/null +++ b/src/Lumina.Application/Common/Enums/BookRatingSource.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Application.Common.Enums; + +/// +/// Enumeration for the various sources of book ratings. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum BookRatingSource +{ + User, + Goodreads, + Amazon, + GoogleBooks, +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Enums/IsbnFormat.cs b/src/Lumina.Application/Common/Enums/IsbnFormat.cs new file mode 100644 index 00000000..507724fe --- /dev/null +++ b/src/Lumina.Application/Common/Enums/IsbnFormat.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Application.Common.Enums; + +/// +/// Enumeration for the different ISBN (International Standard Book Number) formats. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum IsbnFormat +{ + Isbn10, + Isbn13 +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Enums/MediaContributorRole.cs b/src/Lumina.Application/Common/Enums/MediaContributorRole.cs new file mode 100644 index 00000000..db20962d --- /dev/null +++ b/src/Lumina.Application/Common/Enums/MediaContributorRole.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Application.Common.Enums; + +/// +/// Enumeration for the various roles of media contributors across different types of media. +/// +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum MediaContributorRole +{ + Actor, + Director, + Singer, + Author, +} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Books/BookDto.cs b/src/Lumina.Application/Common/Models/Books/BookDto.cs new file mode 100644 index 00000000..48b7e486 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Books/BookDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Enums; +#endregion + +namespace Lumina.Application.Common.Models.Books; + +/// +/// Represents a book. +/// +public record BookDto( + WrittenContentMetadataDto Metadata, + BookFormat Format, + string? Edition, + int? VolumeNumber, + BookSeriesDto? Series, + string? ASIN, + string? GoodreadsId, + string? LCCN, + string? OCLCNumber, + string? OpenLibraryId, + string? LibraryThingId, + string? GoogleBooksId, + string? BarnesAndNobleId, + string? KoboId, + string? AppleBooksId, + List ISBNs, + List Contributors, + List Ratings +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Books/BookRatingDto.cs b/src/Lumina.Application/Common/Models/Books/BookRatingDto.cs new file mode 100644 index 00000000..c2a6d9f8 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Books/BookRatingDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Enums; +using Lumina.Application.Common.Models.Common; +#endregion + +namespace Lumina.Application.Common.Models.Books; + +/// +/// Represents a book rating. +/// +public record BookRatingDto( + decimal Value, + decimal MaxValue, + BookRatingSource? Source, + int? VoteCount +) : RatingDto(Value, MaxValue, VoteCount); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Books/BookSeriesDto.cs b/src/Lumina.Application/Common/Models/Books/BookSeriesDto.cs new file mode 100644 index 00000000..73e479bc --- /dev/null +++ b/src/Lumina.Application/Common/Models/Books/BookSeriesDto.cs @@ -0,0 +1,8 @@ +namespace Lumina.Application.Common.Models.Books; + +/// +/// Represents a request to get book series information. +/// +public record BookSeriesDto( + string Title +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Books/IsbnDto.cs b/src/Lumina.Application/Common/Models/Books/IsbnDto.cs new file mode 100644 index 00000000..5663c8b9 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Books/IsbnDto.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Enums; +#endregion + +namespace Lumina.Application.Common.Models.Books; + +/// +/// Represents a request to get ISBN information. +/// +public record IsbnDto( + string Value, + IsbnFormat Format +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Books/WrittenContentMetadataDto.cs b/src/Lumina.Application/Common/Models/Books/WrittenContentMetadataDto.cs new file mode 100644 index 00000000..f6a3571e --- /dev/null +++ b/src/Lumina.Application/Common/Models/Books/WrittenContentMetadataDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Models.Common; +#endregion + +namespace Lumina.Application.Common.Models.Books; + +/// +/// Represents written content metadata. +/// +public record WrittenContentMetadataDto( + string Title, + string? OriginalTitle, + string? Description, + ReleaseInfoDto ReleaseInfo, + List Genres, + List Tags, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + string? Publisher, + int? PageCount +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Common/GenreDto.cs b/src/Lumina.Application/Common/Models/Common/GenreDto.cs new file mode 100644 index 00000000..686f337c --- /dev/null +++ b/src/Lumina.Application/Common/Models/Common/GenreDto.cs @@ -0,0 +1,8 @@ +namespace Lumina.Application.Common.Models.Common; + +/// +/// Represents a request to get genre information. +/// +public record GenreDto( + string Name +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Common/LanguageInfoDto.cs b/src/Lumina.Application/Common/Models/Common/LanguageInfoDto.cs new file mode 100644 index 00000000..71c565ae --- /dev/null +++ b/src/Lumina.Application/Common/Models/Common/LanguageInfoDto.cs @@ -0,0 +1,10 @@ +namespace Lumina.Application.Common.Models.Common; + +/// +/// Represents a request to get language information. +/// +public record LanguageInfoDto( + string LanguageCode, + string LanguageName, + string? NativeName +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Common/RatingDto.cs b/src/Lumina.Application/Common/Models/Common/RatingDto.cs new file mode 100644 index 00000000..923b9be9 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Common/RatingDto.cs @@ -0,0 +1,10 @@ +namespace Lumina.Application.Common.Models.Common; + +/// +/// Represents a rating. +/// +public abstract record RatingDto( + decimal Value, + decimal MaxValue, + int? VoteCount +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Common/ReleaseInfoDto.cs b/src/Lumina.Application/Common/Models/Common/ReleaseInfoDto.cs new file mode 100644 index 00000000..a11153de --- /dev/null +++ b/src/Lumina.Application/Common/Models/Common/ReleaseInfoDto.cs @@ -0,0 +1,13 @@ +namespace Lumina.Application.Common.Models.Common; + +/// +/// Represents a request to get release information. +/// +public record ReleaseInfoDto( + DateOnly? OriginalReleaseDate, + int? OriginalReleaseYear, + DateOnly? ReReleaseDate, + int? ReReleaseYear, + string? ReleaseCountry, + string? ReleaseVersion +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Common/TagDto.cs b/src/Lumina.Application/Common/Models/Common/TagDto.cs new file mode 100644 index 00000000..6684dbb6 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Common/TagDto.cs @@ -0,0 +1,8 @@ +namespace Lumina.Application.Common.Models.Common; + +/// +/// Represents a request to get tag information. +/// +public record TagDto( + string Name +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Contributors/MediaContributorDto.cs b/src/Lumina.Application/Common/Models/Contributors/MediaContributorDto.cs new file mode 100644 index 00000000..acbeaa5b --- /dev/null +++ b/src/Lumina.Application/Common/Models/Contributors/MediaContributorDto.cs @@ -0,0 +1,9 @@ +namespace Lumina.Application.Common.Models.Contributors; + +/// +/// Represents a media contributor. +/// +public record MediaContributorDto( + string Name, + MediaContributorRoleDto Role +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Contributors/MediaContributorNameDto.cs b/src/Lumina.Application/Common/Models/Contributors/MediaContributorNameDto.cs new file mode 100644 index 00000000..81846c68 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Contributors/MediaContributorNameDto.cs @@ -0,0 +1,9 @@ +namespace Lumina.Application.Common.Models.Contributors; + +/// +/// Represents a media contributor name. +/// +public record MediaContributorNameDto( + string DisplayName, + string? LegalName +); \ No newline at end of file diff --git a/src/Lumina.Application/Common/Models/Contributors/MediaContributorRoleDto.cs b/src/Lumina.Application/Common/Models/Contributors/MediaContributorRoleDto.cs new file mode 100644 index 00000000..69c58610 --- /dev/null +++ b/src/Lumina.Application/Common/Models/Contributors/MediaContributorRoleDto.cs @@ -0,0 +1,9 @@ +namespace Lumina.Application.Common.Models.Contributors; + +/// +/// Represents a media contributor role. +/// +public record MediaContributorRoleDto( + string Name, + string Category +); \ No newline at end of file diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommand.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommand.cs new file mode 100644 index 00000000..3e6885e8 --- /dev/null +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommand.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.Models.Books; +using Lumina.Application.Common.Models.Contributors; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Mediator; +#endregion + +namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; + +/// +/// Command for adding a book. +/// +public record AddBookCommand( + WrittenContentMetadataDto Metadata, + BookFormat Format, + string? Edition, + int? VolumeNumber, + BookSeriesDto? Series, + string? ASIN, + string? GoodreadsId, + string? LCCN, + string? OCLCNumber, + string? OpenLibraryId, + string? LibraryThingId, + string? GoogleBooksId, + string? BarnesAndNobleId, + string? KoboId, + string? AppleBooksId, + List ISBNs, + List Contributors, + List Ratings +) : IRequest>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs new file mode 100644 index 00000000..67c32952 --- /dev/null +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using Mediator; +#endregion + +namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; + +/// +/// Handler for the command to add a book. +/// +public class AddBookCommandHandler : IRequestHandler> +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Handles the command to add a book. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(AddBookCommand request, CancellationToken cancellationToken) + { + List contributorIds = new(); + foreach(var mediaContributor in request.Contributors) + { + // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names + } + BookSeries? bookSeries = null; + if (request.Series != null) + { + // TODO: add logic to search the book series repository for existing book series, based on the provided title + } + var domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create( + rating.Value, + rating.MaxValue, + Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default), + Optional.FromNullable(rating.VoteCount))); + // check if any of the results contain errors + var errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList(); + if (errors.Count != 0) // if there are errors, return them + return errors; + + List domainRatings = domainRatingsResult.Select(rating => rating.Value as Rating).ToList(); + + var domainGenresResult = request.Metadata.Genres.ConvertAll(genre => Genre.Create(genre.Name)); + errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList(); + if (errors.Count != 0) + return errors; + List domainGenres = domainGenresResult.Select(genre => genre.Value).ToList(); + + var domainTagsResult = request.Metadata.Tags.ConvertAll(tag => Tag.Create(tag.Name)); + errors = domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors).ToList(); + if (errors.Count != 0) + return errors; + List domainTags = domainTagsResult.Select(tag => tag.Value).ToList(); + + + var domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format)); + errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList(); + if (errors.Count != 0) + return errors; + List domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList(); + + var releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseDate), + Optional.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear), + Optional.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate), + Optional.FromNullable(request.Metadata.ReleaseInfo.ReReleaseYear), + Optional.FromNullable(request.Metadata.ReleaseInfo.ReleaseCountry), + Optional.FromNullable(request.Metadata.ReleaseInfo.ReleaseVersion) + ); + if (releaseInfoResult.IsError) + return releaseInfoResult.Errors; + ReleaseInfo releaseInfo = releaseInfoResult.Value; + LanguageInfo? languageInfo = null; + if (request.Metadata.Language is not null) + { + var languageInfoResult = LanguageInfo.Create( + request.Metadata.Language.LanguageCode, + request.Metadata.Language.LanguageName, + Optional.FromNullable(request.Metadata.Language.NativeName)); + if (languageInfoResult.IsError) + return languageInfoResult.Errors; + languageInfo = languageInfoResult.Value; + } + LanguageInfo? originalLanguageInfo = null; + if (request.Metadata.OriginalLanguage is not null) + { + var originalLanguageInfoResult = LanguageInfo.Create( + request.Metadata.OriginalLanguage.LanguageCode, + request.Metadata.OriginalLanguage.LanguageName, + Optional.FromNullable(request.Metadata.OriginalLanguage.NativeName)); + if (originalLanguageInfoResult.IsError) + return originalLanguageInfoResult.Errors; + originalLanguageInfo = originalLanguageInfoResult.Value; + } + WrittenContentMetadata metadata = WrittenContentMetadata.Create( + request.Metadata.Title, + Optional.FromNullable(request.Metadata.OriginalTitle), + Optional.FromNullable(request.Metadata.Description), + releaseInfo, + domainGenres, + domainTags, + Optional.FromNullable(languageInfo), + Optional.FromNullable(originalLanguageInfo), + Optional.FromNullable(request.Metadata.Publisher), + Optional.FromNullable(request.Metadata.PageCount) + ); + + var createBookResult = Book.Create( + metadata, + request.Format, + Optional.FromNullable(request.Edition), + request.VolumeNumber ?? default, + Optional.FromNullable(bookSeries), + Optional.FromNullable(request.ASIN), + Optional.FromNullable(request.GoodreadsId), + Optional.FromNullable(request.LCCN), + Optional.FromNullable(request.OCLCNumber), + Optional.FromNullable(request.OpenLibraryId), + Optional.FromNullable(request.LibraryThingId), + Optional.FromNullable(request.GoogleBooksId), + Optional.FromNullable(request.BarnesAndNobleId), + Optional.FromNullable(request.KoboId), + Optional.FromNullable(request.AppleBooksId), + domainIsbns, + contributorIds, + ratings: domainRatings + ); + if (createBookResult.IsError) + return createBookResult.Errors; + return createBookResult.Value; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs new file mode 100644 index 00000000..27a14d94 --- /dev/null +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +#endregion + +namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; + +/// +/// Validates the needed validation rules for . +/// +public class AddBookCommandValidator : AbstractValidator +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public AddBookCommandValidator() + { + RuleFor(x => x.Metadata).NotNull() + .ChildRules(metadata => + { + metadata.RuleFor(m => m.Title).NotEmpty().MaximumLength(255); + metadata.RuleFor(m => m.OriginalTitle).MaximumLength(255); + metadata.RuleFor(m => m.Description).MaximumLength(2000); + metadata.RuleFor(m => m.ReleaseInfo).NotNull() + .ChildRules(ri => + { + ri.RuleFor(r => r.OriginalReleaseYear).InclusiveBetween(1, 9999).When(r => r.OriginalReleaseYear.HasValue); + ri.RuleFor(r => r.ReReleaseYear).InclusiveBetween(1, 9999).When(r => r.ReReleaseYear.HasValue); + ri.RuleFor(r => r.ReleaseCountry).MaximumLength(50); + ri.RuleFor(r => r.ReleaseVersion).MaximumLength(50); + }); + metadata.RuleFor(m => m.Genres).NotEmpty(); + metadata.RuleForEach(m => m.Genres).ChildRules(g => g.RuleFor(genre => genre.Name).NotEmpty().MaximumLength(50)); + metadata.RuleForEach(m => m.Tags).ChildRules(t => t.RuleFor(tag => tag.Name).NotEmpty().MaximumLength(50)); + metadata.RuleFor(m => m.Language).ChildRules(l => + { + l.RuleFor(x => x.LanguageCode).NotEmpty().MaximumLength(10); + l.RuleFor(x => x.LanguageName).NotEmpty().MaximumLength(50); + l.RuleFor(x => x.NativeName).MaximumLength(50); + }).When(m => m.Language != null); + metadata.RuleFor(m => m.OriginalLanguage).ChildRules(l => + { + l.RuleFor(x => x.LanguageCode).NotEmpty().MaximumLength(10); + l.RuleFor(x => x.LanguageName).NotEmpty().MaximumLength(50); + l.RuleFor(x => x.NativeName).MaximumLength(50); + }).When(m => m.OriginalLanguage != null); + metadata.RuleFor(m => m.Publisher).MaximumLength(100); + metadata.RuleFor(m => m.PageCount).GreaterThan(0).When(m => m.PageCount.HasValue); + }); + + RuleFor(x => x.Format).IsInEnum(); + RuleFor(x => x.Edition).MaximumLength(50); + RuleFor(x => x.VolumeNumber).GreaterThan(0).When(x => x.VolumeNumber.HasValue); + + RuleFor(x => x.Series).ChildRules(s => s.RuleFor(series => series.Title).NotEmpty().MaximumLength(255)).When(x => x.Series != null); + + RuleFor(x => x.ASIN).MaximumLength(10); + RuleFor(x => x.GoodreadsId).MaximumLength(20); + RuleFor(x => x.LCCN).MaximumLength(20); + RuleFor(x => x.OCLCNumber).MaximumLength(20); + RuleFor(x => x.OpenLibraryId).MaximumLength(20); + RuleFor(x => x.LibraryThingId).MaximumLength(20); + RuleFor(x => x.GoogleBooksId).MaximumLength(20); + RuleFor(x => x.BarnesAndNobleId).MaximumLength(20); + RuleFor(x => x.KoboId).MaximumLength(20); + RuleFor(x => x.AppleBooksId).MaximumLength(20); + + RuleFor(x => x.ISBNs).NotEmpty(); + RuleForEach(x => x.ISBNs).ChildRules(isbn => + { + isbn.RuleFor(i => i.Value).NotEmpty().MaximumLength(13); + isbn.RuleFor(i => i.Format).IsInEnum(); + }); + + RuleFor(x => x.Contributors).NotEmpty(); + RuleForEach(x => x.Contributors).ChildRules(contributor => + { + contributor.RuleFor(c => c.Name).NotEmpty().MaximumLength(100); + contributor.RuleFor(c => c.Role).ChildRules(role => + { + role.RuleFor(r => r.Name).NotEmpty().MaximumLength(50); + role.RuleFor(r => r.Category).NotEmpty().MaximumLength(50); + }); + }); + + RuleForEach(x => x.Ratings).ChildRules(rating => + { + rating.RuleFor(r => r.Value).Must((r, value) => value >= 0 && value <= r.MaxValue) + .WithMessage("Value must be between 0 and MaxValue"); + rating.RuleFor(r => r.MaxValue).GreaterThan(0); + rating.RuleFor(r => r.VoteCount).GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue); + }); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 1d1c998d..1ef8b479 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -1,21 +1,5 @@  - - - - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - net8.0 enable @@ -23,4 +7,21 @@ ..\..\bin\ + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index 69269f15..1eadaafa 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -7,4 +7,8 @@ ..\..\bin\ + + + + diff --git a/src/Lumina.Domain/Common/Enums/MediaContributorRole.cs b/src/Lumina.Domain/Common/Enums/MediaContributorRole.cs deleted file mode 100644 index d17f748d..00000000 --- a/src/Lumina.Domain/Common/Enums/MediaContributorRole.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Lumina.Domain.Common.Enums; - -/// -/// Enumeration for the various roles of media contributors across different types of media. -/// -public enum MediaContributorRole -{ - /// - /// A person who portrays a character in a performance, typically in films, television shows, or theater productions. - /// - Actor, - - /// - /// The person responsible for overseeing and directing the production of a film, play, television show, or other performing art. - /// - Director, - - /// - /// A person who uses their voice to produce musical sounds, typically with a melody and often with lyrics in songs. - /// - Singer, - - /// - /// The creator or originator of a written work, such as a book, article, or other literary piece. - /// - Author -} \ No newline at end of file diff --git a/src/Lumina.Domain/Common/Primitives/Optional.cs b/src/Lumina.Domain/Common/Primitives/Optional.cs index fb89e794..00b197f4 100644 --- a/src/Lumina.Domain/Common/Primitives/Optional.cs +++ b/src/Lumina.Domain/Common/Primitives/Optional.cs @@ -24,7 +24,7 @@ public readonly struct Optional { get { - return HasValue ? _value! : throw new InvalidOperationException("Optional has no value."); + return HasValue ? _value! : default!; } } #endregion @@ -34,10 +34,11 @@ public readonly struct Optional /// Initializes a new instance of the structure. /// /// The value represented by this structure. - public Optional(T value) + /// if is not , otherwise. + private Optional(T? value, bool hasValue) { _value = value; - HasValue = true; + HasValue = hasValue; } #endregion @@ -48,7 +49,47 @@ public readonly struct Optional /// The value to be converted. public static implicit operator Optional(T value) { - return new Optional(value); + return Some(value); + } + + /// + /// Creates an with a value. + /// + /// The value to wrap in the . + /// An containing the specified value. + public static Optional Some(T value) + { + return new Optional(value, true); + } + + /// + /// Creates an with no value. + /// + /// An empty . + public static Optional None() + { + return new(default, false); + } + + /// + /// Creates an from a nullable reference type. + /// + /// The nullable value to convert. + /// An representing the nullable value. + public static Optional FromNullable(T? value) + { + return value is null ? None() : Some(value); + } + + /// + /// Creates an from a nullable value type. + /// + /// The underlying value type. + /// The nullable value to convert. + /// An representing the nullable value. + public static Optional FromNullable(TValue? value) where TValue : struct, T + { + return value.HasValue ? Some(value.Value) : None(); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs index da747d33..b8a7fdab 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs @@ -71,8 +71,8 @@ public abstract class BaseMetadata : ValueObject /// /// The title of the element to which this metadata object belongs to. /// The optional original title of the element to which this metadata object belongs to. - /// The optional release information of the media item. /// The optional description of the element to which this metadata object belongs to. + /// The optional release information of the media item. /// The list of genres of the element to which this metadata object belongs to. /// The list of tags of the element to which this metadata object belongs to. /// The optional language of the element to which this metadata object belongs to. @@ -81,8 +81,8 @@ public abstract class BaseMetadata : ValueObject protected BaseMetadata( string title, Optional originalTitle, - ReleaseInfo releaseInfo, Optional description, + ReleaseInfo releaseInfo, List genres, List tags, Optional language, @@ -90,8 +90,8 @@ public abstract class BaseMetadata : ValueObject { Title = title ?? throw new ArgumentNullException(nameof(title)); OriginalTitle = originalTitle; - ReleaseInfo = releaseInfo; Description = description; + ReleaseInfo = releaseInfo; _genres = genres; _tags = tags; Language = language; @@ -105,8 +105,8 @@ public abstract class BaseMetadata : ValueObject { yield return Title; yield return OriginalTitle; - yield return ReleaseInfo; yield return Description; + yield return ReleaseInfo; foreach (var genre in _genres) yield return genre; foreach (var tag in _tags) diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index d2d6fc70..03d0025d 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -36,7 +36,7 @@ public class Genre : ValueObject /// /// The value of the genre. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create(string name) { diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index 3647621e..ee5ccd7d 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Common.Enums; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using System.Diagnostics; @@ -38,8 +37,6 @@ public class LanguageInfo : ValueObject /// The ISO 639-1 two-letter language code. /// The full name of the language in English. /// The optional native name of the language. - /// Thrown if languageCode or languageName is null. - /// Thrown if languageCode is not a valid ISO 639-1 code. private LanguageInfo(string languageCode, string languageName, Optional nativeName) { LanguageCode = languageCode.ToLowerInvariant(); @@ -56,7 +53,7 @@ public class LanguageInfo : ValueObject /// The full name of the language in English. /// The optional native name of the language. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create(string languageCode, string languageName, Optional nativeName) { diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs index befe204e..e93f2355 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs @@ -1,6 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.Common.Enums; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using System.Diagnostics; @@ -12,28 +10,23 @@ namespace Lumina.Domain.Common.ValueObjects.Metadata; /// Value Object for the rating of a media element. /// [DebuggerDisplay("{Value}/{MaxValue}")] -public class Rating : ValueObject +public abstract class Rating : ValueObject { #region ==================================================================== PROPERTIES ================================================================================= /// /// Gets the numeric value of the rating. /// - public decimal Value { get; } + public decimal Value { get; private set; } /// /// Gets the maximum possible rating value. /// - public decimal MaxValue { get; } - - /// - /// Gets the optional source of the rating (e.g., "IMDB", "Rotten Tomatoes"). - /// - public Optional Source { get; } + public decimal MaxValue { get; private set; } /// /// Gets the optional number of votes or reviews this rating is based on. /// - public Optional VoteCount { get; } + public Optional VoteCount { get; private set; } #endregion #region ====================================================================== CTOR ===================================================================================== @@ -42,37 +35,16 @@ public class Rating : ValueObject /// /// The numeric value of the rating. /// The maximum possible rating value. - /// The optional source of the rating. /// The optional number of votes or reviews. - private Rating(decimal value, decimal maxValue, Optional source, Optional voteCount) + protected Rating(decimal value, decimal maxValue, Optional voteCount) { Value = value; MaxValue = maxValue; - Source = source; VoteCount = voteCount; } #endregion #region ===================================================================== METHODS =================================================================================== - /// - /// Creates a new instance of the class. - /// - /// The numeric value of the rating. - /// The maximum possible rating value. - /// The optional source of the rating. - /// The optional number of votes or reviews. - /// - /// An containing either a successfully created or an error message. - /// - public static ErrorOr Create(decimal value, decimal maxValue, Optional source, Optional voteCount) - { - if (maxValue < 0 || value < 0) - return Errors.Errors.Metadata.RatingMustBePositive; - if (value > maxValue) - return Errors.Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue; - return new Rating(value, maxValue, source, voteCount); - } - /// /// Returns the rating as a percentage. /// @@ -81,28 +53,5 @@ public class Rating : ValueObject { return (Value / MaxValue) * 100; } - - /// - public override IEnumerable GetEqualityComponents() - { - yield return Value; - yield return MaxValue; - yield return Source; - yield return VoteCount; - } - - /// - /// Customized ToString() method. - /// - /// Custom string value showing relevant data for current class. - public override string ToString() - { - string baseString = $"{Value}/{MaxValue}"; - if (Source.HasValue) - baseString += $" ({Source.Value})"; - if (VoteCount.HasValue) - baseString += $" [{VoteCount.Value} votes]"; - return baseString; - } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs index 6d799931..fe1f463c 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs @@ -84,7 +84,7 @@ public class ReleaseInfo : ValueObject /// The optional country or region of release. /// The optional release version or edition. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( Optional originalReleaseDate, diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index 0fb0c321..e244fb7d 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -36,7 +36,7 @@ public class Tag : ValueObject /// /// The value of the tag. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create(string name) { diff --git a/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs index 8ff8cf52..6ec66e9f 100644 --- a/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs @@ -54,7 +54,7 @@ public class AudioMetadata : BaseMetadata /// The duration of the audio, in seconds. /// The sample rate of the audio, in Hz. /// The number of audio channels. - /// The release information of the audio. + /// The release information of the audio. /// The description of the audio. /// The language of the audio. /// The optional original language of the video. @@ -68,7 +68,7 @@ public class AudioMetadata : BaseMetadata int durationInSeconds, int sampleRate, int channels, - ReleaseInfo release, + ReleaseInfo releaseInfo, Optional description, List genres, List tags, @@ -77,7 +77,7 @@ public class AudioMetadata : BaseMetadata Optional bitDepth, Optional audioCodec, Optional bitrate) - : base(title, originalTitle, release, description, genres, tags, language, originalLanguage) + : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { DurationInSeconds = durationInSeconds; SampleRate = sampleRate; @@ -106,7 +106,7 @@ public class AudioMetadata : BaseMetadata /// The genres of the audio. /// The tags associated with the audio. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( string title, diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs index 03486b09..8aa2f743 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileInfo.cs @@ -68,7 +68,7 @@ public class FileInfo : ValueObject /// The date and time when the file was last modified. /// The MIME type of the file, if available. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create(string path, string fileExtension, long sizeInBytes, DateTime lastModified, Optional mimeType) { diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs index 428bb218..5edf393b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs @@ -100,7 +100,7 @@ public class StreamInfo : ValueObject /// The sample rate of the stream (for audio). /// The number of channels (for audio). /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( string streamId, diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs new file mode 100644 index 00000000..170f5202 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using Lumina.Domain.Common.Models.Core; +#endregion + +namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; + +/// +/// Value Object for the role of a media contributor. +/// +[DebuggerDisplay("{DisplayName}")] +public sealed class MediaContributorRole : ValueObject +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the value representing this object. + /// + public string Name { get; } + + /// + /// Gets the category of this object. + /// + public string Category { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + /// The category of this object. + private MediaContributorRole(string name, string category) + { + Name = name; + Category = category; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value representing this object. + /// The category of this object. + /// The created instance. + public static MediaContributorRole Create(string name, string category) + { + // TODO: enforce invariants + return new MediaContributorRole(name, category); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Name; + yield return Category; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs index ff8eba44..0425e784 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs @@ -48,7 +48,7 @@ public class VideoMetadata : BaseMetadata /// The optional original title of the video. /// The duration of the video, in seconds. /// The resolution of the video. - /// The release information of the video. + /// The release information of the video. /// The optional description of the video. /// The language of the video. /// The optional original language of the video. @@ -62,8 +62,8 @@ public class VideoMetadata : BaseMetadata Optional originalTitle, int durationInSeconds, string resolution, - ReleaseInfo release, Optional description, + ReleaseInfo releaseInfo, Optional language, Optional originalLanguage, Optional frameRate, @@ -71,7 +71,7 @@ public class VideoMetadata : BaseMetadata Optional audioCodec, List genres, List tags) - : base(title, originalTitle, release, description, genres, tags, language, originalLanguage) + : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { DurationInSeconds = durationInSeconds; Resolution = resolution ?? throw new ArgumentNullException(nameof(resolution)); @@ -89,8 +89,8 @@ public class VideoMetadata : BaseMetadata /// The optional original title of the video. /// The duration of the video in seconds. /// The resolution of the video. - /// The release information of the video. /// The optional description of the video. + /// The release information of the video. /// The language of the video. /// The optional original language of the video. /// The optional frame rate of the video. @@ -100,15 +100,15 @@ public class VideoMetadata : BaseMetadata /// The tags associated with the video. /// The list of contributors for this video. /// - /// An containing either a successfully created or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( string title, Optional originalTitle, int durationInSeconds, string resolution, - ReleaseInfo release, Optional description, + ReleaseInfo releaseInfo, Optional language, Optional originalLanguage, Optional frameRate, @@ -117,7 +117,7 @@ public class VideoMetadata : BaseMetadata List genres, List tags) { - return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, release, description, + return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo, language, originalLanguage, frameRate, videoCodec, audioCodec, genres, tags); } diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs index 05340d24..565d83bf 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs @@ -223,7 +223,9 @@ public sealed class Book : AggregateRoot /// The list of ISBNs of the book. /// The list of media contributors of the book. /// The list of ratings for the book. - /// The created . + /// + /// An containing either a successfully created , or an error message. + /// public static ErrorOr Create( WrittenContentMetadata metadata, BookFormat format, @@ -289,7 +291,9 @@ public sealed class Book : AggregateRoot /// The list of ISBNs of the book. /// The list of media contributors of the book. /// The list of ratings for the book. - /// The created . + /// + /// An containing either a successfully created , or an error message. + /// public static ErrorOr Create( BookId id, WrittenContentMetadata metadata, diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs index 3586a9d1..2f9822ab 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs @@ -43,8 +43,10 @@ public sealed class BookSeries : Entity /// Initializes a new instance of the class. /// /// The identifier of the book series. - /// The title of the book series. - public BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List books) + /// The metadata of the book series. + /// The current status of the book series. + /// The books of the book series. + private BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List books) : base(id) { Id = id; @@ -56,6 +58,53 @@ public sealed class BookSeries : Entity #region ===================================================================== METHODS =================================================================================== /// + /// Creates a new instance of the class. + /// + /// The identifier of the book series. + /// The metadata of the book series. + /// The current status of the book series. + /// The books of the book series. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + BookSeriesId id, + WrittenContentMetadata metadata, + bool isComplete, + List books) + { + // TODO: enforce invariants + return new BookSeries( + id, + metadata, + isComplete, + books + ); + } + + /// + /// Creates a new instance of the class. + /// + /// The metadata of the book series. + /// The current status of the book series. + /// The books of the book series. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + WrittenContentMetadata metadata, + bool isComplete, + List books) + { + // TODO: enforce invariants + return new BookSeries( + BookSeriesId.CreateUnique(), + metadata, + isComplete, + books + ); + } + /// /// Adds a book to the series. /// /// The book to be added. diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs index 31512a6e..5155c3f7 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs @@ -34,7 +34,6 @@ public sealed class BookId : AggregateRootId /// The created instance. public static BookId CreateUnique() { - // TODO: enforce invariants return new BookId(Guid.NewGuid()); } @@ -45,7 +44,6 @@ public sealed class BookId : AggregateRootId /// The created instance. public static BookId Create(Guid value) { - // TODO: enforce invariants return new BookId(value); } diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs new file mode 100644 index 00000000..91ea0b9e --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using ErrorOr; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; + +/// +/// Value Object for the rating of a media element. +/// +[DebuggerDisplay("{Value}/{MaxValue}")] +public class BookRating : Rating +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the optional source of the rating (e.g., "Goodreads", "Amazon"). + /// + public Optional Source { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The numeric value of the rating. + /// The maximum possible rating value. + /// The optional source of the rating. + /// The optional number of votes or reviews. + private BookRating(decimal value, decimal maxValue, Optional source, Optional voteCount) + : base(value, maxValue, voteCount) + { + Source = source; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a new instance of the class. + /// + /// The numeric value of the rating. + /// The maximum possible rating value. + /// The optional source of the rating. + /// The optional number of votes or reviews. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create(decimal value, decimal maxValue, Optional source, Optional voteCount) + { + if (maxValue < 0 || value < 0) + return Errors.Metadata.RatingMustBePositive; + if (value > maxValue) + return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue; + return new BookRating(value, maxValue, source, voteCount); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Value; + yield return MaxValue; + yield return Source; + yield return VoteCount; + } + + /// + /// Customized ToString() method. + /// + /// Custom string value showing relevant data for current class. + public override string ToString() + { + string baseString = $"{Value}/{MaxValue}"; + if (Source.HasValue) + baseString += $" ({Source.Value})"; + if (VoteCount.HasValue) + baseString += $" [{VoteCount.Value} votes]"; + return baseString; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs index 950fedf6..63f7bc37 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; using Lumina.Domain.Common.Models.Core; #endregion @@ -30,9 +29,8 @@ public sealed class BookSeriesId : ValueObject /// Creates a new instance of the class. /// /// The created instance. - public static ErrorOr CreateUnique() + public static BookSeriesId CreateUnique() { - // TODO: enforce invariants return new BookSeriesId(Guid.NewGuid()); } @@ -41,9 +39,8 @@ public sealed class BookSeriesId : ValueObject /// /// The value used to create the instance. /// The created instance. - public static ErrorOr Create(Guid value) + public static BookSeriesId Create(Guid value) { - // TODO: enforce invariants return new BookSeriesId(value); } diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index ec747821..a1c1ee5f 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -30,26 +30,26 @@ public class WrittenContentMetadata : BaseMetadata /// /// The title of the written content. /// The optional original title of the video. - /// The release information of the written content. /// The description of the written content. + /// The release information of the written content. /// The genres of the written content. /// The tags associated with the written content. /// The language of the written content. /// The optional original language of the video. /// The publisher of the written content. /// The number of pages in the written content. - public WrittenContentMetadata( + private WrittenContentMetadata( string title, Optional originalTitle, - ReleaseInfo release, Optional description, + ReleaseInfo releaseInfo, List genres, List tags, Optional language, Optional originalLanguage, Optional publisher, Optional pageCount) - : base(title, originalTitle, release, description, genres, tags, language, originalLanguage) + : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { Publisher = publisher; PageCount = pageCount; @@ -57,6 +57,44 @@ public class WrittenContentMetadata : BaseMetadata #endregion #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a new instance of the class. + /// + /// The title of the written content. + /// The optional original title of the video. + /// The description of the written content. + /// The release information of the written content. + /// The genres of the written content. + /// The tags associated with the written content. + /// The language of the written content. + /// The optional original language of the video. + /// The publisher of the written content. + /// The number of pages in the written content. + public static WrittenContentMetadata Create( + string title, + Optional originalTitle, + Optional description, + ReleaseInfo releaseInfo, + List genres, + List tags, + Optional language, + Optional originalLanguage, + Optional publisher, + Optional pageCount) + { + return new WrittenContentMetadata( + title, + originalTitle, + description, + releaseInfo, + genres, tags, + language, + originalLanguage, + publisher, + pageCount + ); + } + /// public override IEnumerable GetEqualityComponents() { diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 507abf41..1eadaafa 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -1,9 +1,5 @@  - - - - net8.0 enable @@ -11,4 +7,8 @@ ..\..\bin\ + + + + diff --git a/src/Lumina.Presentation.Api/Common/Contracts/Books/AddBookRequest.cs b/src/Lumina.Presentation.Api/Common/Contracts/Books/AddBookRequest.cs new file mode 100644 index 00000000..eb953285 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Contracts/Books/AddBookRequest.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Enums; +using Lumina.Application.Common.Models.Books; +using Lumina.Application.Common.Models.Contributors; +#endregion + +namespace Lumina.Presentation.Api.Common.Contracts.Books; + +/// +/// Represents a request to add a book. +/// +public record AddBookRequest( + WrittenContentMetadataDto Metadata, + BookFormat Format, + string? Edition, + int? VolumeNumber, + BookSeriesDto? Series, + string? ASIN, + string? GoodreadsId, + string? LCCN, + string? OCLCNumber, + string? OpenLibraryId, + string? LibraryThingId, + string? GoogleBooksId, + string? BarnesAndNobleId, + string? KoboId, + string? AppleBooksId, + List ISBNs, + List Contributors, + List Ratings +); \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Common/Converters/OptionalJsonConverterFactory.cs b/src/Lumina.Presentation.Api/Common/Converters/OptionalJsonConverterFactory.cs new file mode 100644 index 00000000..e69de29b diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 1c1e8692..e728c0ff 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -1,6 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +using Lumina.Application.Common.Converters; using Lumina.Presentation.Api.Common.Configuration; using Lumina.Presentation.Api.Common.Errors; +using Mapster; +using MapsterMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; #endregion @@ -21,7 +25,11 @@ public static class PresentationApiLayerServices public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) { // add services to the container - services.AddControllers(); + services.AddControllers().AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory()); + }); // add services to the container. services.AddEndpointsApiExplorer(); @@ -43,6 +51,12 @@ public static class PresentationApiLayerServices services.AddSingleton(); + // register mapster configs + var mapsterConfig = TypeAdapterConfig.GlobalSettings; + mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly); + services.AddSingleton(mapsterConfig); + services.AddScoped(); + return services; } #endregion diff --git a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs index 8d7ba628..df06cf75 100644 --- a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs +++ b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs @@ -1,11 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using System; using ErrorOr; -using System.Linq; using System.Diagnostics; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; using Microsoft.Extensions.Options; using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; diff --git a/src/Lumina.Presentation.Api/Common/Mapping/BookMappingConfig.cs b/src/Lumina.Presentation.Api/Common/Mapping/BookMappingConfig.cs new file mode 100644 index 00000000..07301d73 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Mapping/BookMappingConfig.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; +using Lumina.Presentation.Api.Common.Contracts.Books; +using Mapster; +#endregion + +namespace Lumina.Presentation.Api.Common.Mapping; + +/// +/// Mapping configuration for books. +/// +public class BookMappingConfig : IRegister +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Registers the mapping configuration. + /// + /// The type adapter configuration. + public void Register(TypeAdapterConfig config) + { + config.NewConfig() + .Map(dest => dest.ASIN, src => src.ASIN) + .Map(dest => dest.ISBNs, src => src.ISBNs) + .Map(dest => dest.LCCN, src => src.LCCN) + .Map(dest => dest.OCLCNumber, src => src.OCLCNumber) + .MapToConstructor(true); + + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs b/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs index d03b41c4..bbe1b0fa 100644 --- a/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs +++ b/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using ErrorOr; +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; +using Lumina.Presentation.Api.Common.Contracts.Books; using Lumina.Presentation.Api.Controllers.Common; +using MapsterMapper; using Mediator; using Microsoft.AspNetCore.Mvc; #endregion @@ -15,7 +17,8 @@ namespace Lumina.Presentation.Api.Controllers.Books; public class BooksController : ApiController { #region ================================================================== FIELD MEMBERS ================================================================================ - private readonly ISender mediator; + private readonly ISender _mediator; + private readonly IMapper _mapper; #endregion #region ====================================================================== CTOR ===================================================================================== @@ -23,17 +26,18 @@ public class BooksController : ApiController /// Initializes a new instance of the class. /// /// Injecting service for mediating commands and queries. - public BooksController(ISender mediator) + /// Injected service for mapping objects. + public BooksController(ISender mediator, IMapper mapper) { - this.mediator = mediator; + _mediator = mediator; + _mapper = mapper; } #endregion #region ===================================================================== METHODS =================================================================================== /// - /// Gets all books. + /// Controller action for getting the list of all books. /// - /// An containing either a collection of books, or an error. [HttpGet()] public async Task GetBooks() { @@ -42,15 +46,15 @@ public class BooksController : ApiController return Ok(new List { "Book 1", "Book 2", "Book 3" }); } - // /// - // /// Adds a book. - // /// - // /// - // /// The result of the HTTP request. - // public async Task AddBook(AddBookCommand command) - // { - // ErrorOr result = await mediator.Send(command); - // return result.Match(result => Ok(result), errors => Problem(errors)); - // } + /// + /// Controller action for adding a book. + /// + /// The command to add a book. + [HttpPost()] + public async Task AddBook(AddBookRequest request) + { + var result = await _mediator.Send(_mapper.Map(request)); + return result.Match(result => Ok(result), errors => Problem(errors)); + } #endregion } \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 2462e4ed..a8b6a0c1 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -8,10 +8,12 @@ + + - - runtime; build; native; contentfiles; analyzers; buildtransitive - all + + runtime; build; native; contentfiles; analyzers; buildtransitive + all