From f37d06f8df71bd32071e2a6ef31e239a5d9e1bf8 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 28 Aug 2024 21:52:41 +0300 Subject: [PATCH] Adds refactoring --- .../BookLibrary/BookMappingConfig.cs | 16 +++---- .../Books/Commands/AddBookCommandHandler.cs | 7 +-- .../Books/Commands/AddBookCommandValidator.cs | 39 +++++++++++++++- .../BookLibraryAggregate/Book.cs | 16 ++++++- .../BookLibraryAggregate/ValueObjects/Isbn.cs | 45 +++++++------------ .../ValueObjects/WrittenContentMetadata.cs | 6 ++- .../Controllers/Books/BooksController.cs | 10 ++--- .../Controllers/Common/ApiController.cs | 2 +- src/Lumina.sln | 17 +++++++ 9 files changed, 109 insertions(+), 49 deletions(-) rename src/Lumina.Presentation.Api/{ => Core}/Controllers/Books/BooksController.cs (87%) rename src/Lumina.Presentation.Api/{ => Core}/Controllers/Common/ApiController.cs (98%) diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs index 32ad74be..b0f26d71 100644 --- a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs @@ -60,7 +60,7 @@ public class BookMappingConfig : IRegister .Map(dest => dest.ISBNs, src => src.ISBNs) .Map(dest => dest.Ratings, src => src.Ratings) .Map(dest => dest.Created, src => src.Created) - .Map(dest => dest.Updated, src => src.Updated); + .Map(dest => dest.Updated, src => src.Updated.HasValue ? src.Updated : null); config.NewConfig() .Map(dest => dest.Value, src => src.Value) @@ -71,7 +71,7 @@ public class BookMappingConfig : IRegister config.NewConfig, BookRatingSource?>() .MapWith(src => src.HasValue ? src.Value : default); - + // from BookDto to Book config.NewConfig() .MapWith(src => Book.Create( BookId.Create(src.Id), @@ -101,11 +101,11 @@ public class BookMappingConfig : IRegister ).Value : Optional.None(), Optional.FromNullable(src.Publisher), Optional.FromNullable(src.PageCount) - ), + ).Value, Enum.Parse(src.Format), Optional.FromNullable(src.Edition), Optional.FromNullable(src.VolumeNumber), - Optional.None(), // Assuming BookSeries is not part of BookDto + Optional.None(), Optional.FromNullable(src.ASIN), Optional.FromNullable(src.GoodreadsId), Optional.FromNullable(src.LCCN), @@ -115,17 +115,17 @@ public class BookMappingConfig : IRegister Optional.FromNullable(src.GoogleBooksId), Optional.FromNullable(src.BarnesAndNobleId), Optional.FromNullable(src.AppleBooksId), + src.Created, + Optional.FromNullable(src.Updated), src.ISBNs.Select(i => Isbn.Create(i.Value, i.Format).Value).ToList(), - new List(), // Assuming MediaContributorId is not part of BookDto + new List(), src.Ratings.Select(r => BookRating.Create( r.Value, r.MaxValue, Optional.FromNullable(r.Source), Optional.FromNullable(r.VoteCount) ).Value).ToList() - ).Value) // Assuming Create returns ErrorOr, we take the Value - .Ignore(dest => dest.Created) - .Ignore(dest => dest.Updated); + ).Value); } #endregion } \ 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 index 790d8740..edd488ec 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandler.cs @@ -125,7 +125,7 @@ public class AddBookCommandHandler : IRequestHandler.FromNullable(request.Metadata.OriginalTitle), Optional.FromNullable(request.Metadata.Description), @@ -137,9 +137,10 @@ public class AddBookCommandHandler : IRequestHandler.FromNullable(request.Metadata.Publisher), Optional.FromNullable(request.Metadata.PageCount) ); - + if (metadataResult.IsError) + return metadataResult.Errors; var createBookResult = Book.Create( - metadata, + metadataResult.Value, request.Format, Optional.FromNullable(request.Edition), request.VolumeNumber ?? default, diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs index 56496891..977b4f31 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidator.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; +using Lumina.Domain.Common.Enums; using Lumina.Domain.Common.Errors; +using System.Text.RegularExpressions; #endregion namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; @@ -157,7 +159,12 @@ public class AddBookCommandValidator : AbstractValidator { isbn.RuleFor(i => i.Value) .NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Code) - .MaximumLength(13).WithMessage(Errors.WrittenContent.InvalidIsbn13Format.Code); + .Matches(i => i.Format == IsbnFormat.Isbn13 + ? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$" + : @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$") + .WithMessage(i => i.Format == IsbnFormat.Isbn13 + ? Errors.WrittenContent.InvalidIsbn13Format.Code + : Errors.WrittenContent.InvalidIsbn10Format.Code); isbn.RuleFor(i => i.Format) .IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Code); }); @@ -196,5 +203,35 @@ public class AddBookCommandValidator : AbstractValidator .WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Code); }); } + + public static bool ValidateIsbn10(string isbn) + { + isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper(); + if (!Regex.IsMatch(isbn, @"^(?:\d{9}[\dX])$")) + return false; + + int sum = 0; + for (int i = 0; i < 9; i++) + sum += (10 - i) * (isbn[i] - '0'); + + char lastChar = isbn[9]; + sum += lastChar == 'X' ? 10 : (lastChar - '0'); + + return sum % 11 == 0; + } + + public static bool ValidateIsbn13(string isbn) + { + if (!Regex.IsMatch(isbn, @"^(978|979)-[0-9]{1,5}-[0-9]+-[0-9]+-[0-9]$")) + return false; + + isbn = isbn.Replace("-", ""); + int sum = 0; + for (int i = 0; i < 12; i++) + sum += (i % 2 == 0) ? isbn[i] - '0' : (isbn[i] - '0') * 3; + + int checkDigit = (10 - (sum % 10)) % 10; + return checkDigit == (isbn[12] - '0'); + } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs index 2f481a09..2205e256 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs @@ -139,10 +139,12 @@ public sealed class Book : AggregateRoot /// The optional Google Books ID of the book. /// The optional Barnes & Noble ID of the book. /// The optional Apple Books ID of the book. + /// The date and time when the entity was created. + /// The date and time when the entity was last updated. /// The list of ISBNs of the book. /// The list of media contributors of the book. /// The list of ratings for the book. - public Book( + private Book( BookId id, WrittenContentMetadata metadata, BookFormat format, @@ -158,6 +160,8 @@ public sealed class Book : AggregateRoot Optional googleBooksId, Optional barnesAndNobleId, Optional appleBooksId, + DateTime created, + Optional updated, List isbns, List contributors, List ratings) : base(id) @@ -177,6 +181,8 @@ public sealed class Book : AggregateRoot GoogleBooksId = googleBooksId; BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; + Created = created; + Updated = updated.HasValue ? updated.Value : null; _isbns = isbns; _contributors = contributors; _ratings = ratings; @@ -253,6 +259,8 @@ public sealed class Book : AggregateRoot googleBooksId, barnesAndNobleId, appleBooksId, + DateTime.UtcNow, + default, isbns, contributors, ratings); @@ -276,6 +284,8 @@ public sealed class Book : AggregateRoot /// The optional Google Books ID of the book. /// The optional Barnes & Noble ID of the book. /// The optional Apple Books ID of the book. + /// The date and time when the entity was created. + /// The date and time when the entity was last updated. /// The list of ISBNs of the book. /// The list of media contributors of the book. /// The list of ratings for the book. @@ -298,6 +308,8 @@ public sealed class Book : AggregateRoot Optional googleBooksId, Optional barnesAndNobleId, Optional appleBooksId, + DateTime created, + Optional updated, List isbns, List contributors, List ratings) @@ -319,6 +331,8 @@ public sealed class Book : AggregateRoot googleBooksId, barnesAndNobleId, appleBooksId, + created, + updated, isbns, contributors, ratings); diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs index 7bbfc5da..242d8a3b 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -13,6 +13,11 @@ namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggrega /// public sealed class Isbn : ValueObject { + #region ================================================================== FIELD MEMBERS ================================================================================ + private static readonly Regex Isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled); + private static readonly Regex Isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled); + #endregion + #region ==================================================================== PROPERTIES ================================================================================= /// /// Gets the value of the ISBN. @@ -71,58 +76,40 @@ public sealed class Isbn : ValueObject /// /// Validates an ISBN-10 string. /// - /// The ISBN-10 string to validate, without hyphens or spaces. + /// The ISBN-10 string to validate, with or without hyphens or spaces. /// if the ISBN-10 is valid, otherwise. public static bool IsValidIsbn10(string isbn) { - // ISBN-10 must be exactly 10 characters long - if (isbn.Length != 10) + if (!Isbn10Regex.IsMatch(isbn)) return false; + // remove any hyphens or spaces + isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper(); int sum = 0; for (int i = 0; i < 9; i++) - { - // each of the first 9 characters must be a digit - if (!char.IsDigit(isbn[i])) - return false; - // calculate the sum: each digit is multiplied by its position (10 to 2) and added sum += (10 - i) * (isbn[i] - '0'); - } - // check the last character, which can be a digit or 'X' char lastChar = isbn[9]; - if (lastChar == 'X' || lastChar == 'x') + if (lastChar == 'X') sum += 10; - else if (char.IsDigit(lastChar)) - sum += lastChar - '0'; else - return false; - // the ISBN-10 is valid if the sum is divisible by 11 + sum += lastChar - '0'; return sum % 11 == 0; } /// /// Validates an ISBN-13 string. /// - /// The ISBN-13 string to validate, without hyphens or spaces. + /// The ISBN-13 string to validate, with or without hyphens or spaces. /// if the ISBN-13 is valid, otherwise. public static bool IsValidIsbn13(string isbn) { - // ISBN-13 must be exactly 13 characters long - if (isbn.Length != 13) + if (!Isbn13Regex.IsMatch(isbn)) return false; + // remove any hyphens or spaces + isbn = isbn.Replace("-", "").Replace(" ", ""); int sum = 0; for (int i = 0; i < 12; i++) - { - // each of the first 12 characters must be a digit - if (!char.IsDigit(isbn[i])) - return false; - // calculate the sum: alternate digits are multiplied by 3 sum += (i % 2 == 0) ? isbn[i] - '0' : 3 * (isbn[i] - '0'); - } - // calculate the check digit - int checkDigit = 10 - (sum % 10); - if (checkDigit == 10) - checkDigit = 0; - // the ISBN-13 is valid if the calculated check digit matches the last digit + int checkDigit = (10 - (sum % 10)) % 10; return checkDigit == (isbn[12] - '0'); } 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 a1c1ee5f..d17fffdd 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Diagnostics; @@ -70,7 +71,10 @@ public class WrittenContentMetadata : BaseMetadata /// 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( + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( string title, Optional originalTitle, Optional description, diff --git a/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Books/BooksController.cs similarity index 87% rename from src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs rename to src/Lumina.Presentation.Api/Core/Controllers/Books/BooksController.cs index 4c4887a7..dd67ca34 100644 --- a/src/Lumina.Presentation.Api/Controllers/Books/BooksController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/Books/BooksController.cs @@ -2,20 +2,20 @@ using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands; using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries; using Lumina.Presentation.Api.Common.Contracts.Books; -using Lumina.Presentation.Api.Controllers.Common; +using Lumina.Presentation.Api.Core.Controllers.Common; using MapsterMapper; using Mediator; using Microsoft.AspNetCore.Mvc; #endregion -namespace Lumina.Presentation.Api.Controllers.Books; +namespace Lumina.Presentation.Api.Core.Controllers.Books; /// /// Controller for managing books. /// [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -public class BooksController : ApiController +public class BooksController : ApiController { #region ================================================================== FIELD MEMBERS ================================================================================ private readonly ISender _mediator; @@ -49,12 +49,12 @@ public class BooksController : ApiController /// /// Controller action for adding a book. /// - /// The command to add 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)); + return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors)); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Controllers/Common/ApiController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs similarity index 98% rename from src/Lumina.Presentation.Api/Controllers/Common/ApiController.cs rename to src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs index 730fd53a..fbd10685 100644 --- a/src/Lumina.Presentation.Api/Controllers/Common/ApiController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs @@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; #endregion -namespace Lumina.Presentation.Api.Controllers.Common; +namespace Lumina.Presentation.Api.Core.Controllers.Common; /// /// Base class for API controllers. diff --git a/src/Lumina.sln b/src/Lumina.sln index 927cd3a5..eedfba66 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -63,6 +63,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "books", "books", "{FAFD9E43 ..\docs\technical\requests\books\GetAll.http = ..\docs\technical\requests\books\GetAll.http EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{3F057926-562F-4EF4-BFC0-EE62372D4551}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.DataAccess.IntegrationTests", "..\tests\IntegrationTests\Lumina.DataAccess.IntegrationTests\Lumina.DataAccess.IntegrationTests.csproj", "{6B3FC07B-6208-4544-ACFB-79243A59EA1A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Api.IntegrationTests\Lumina.Presentation.Api.IntegrationTests.csproj", "{3680DAFB-10BA-4A0F-AE40-620D06DAF617}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -113,6 +119,14 @@ Global {4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Debug|Any CPU.Build.0 = Debug|Any CPU {4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.ActiveCfg = Release|Any CPU {4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.Build.0 = Release|Any CPU + {6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.Build.0 = Release|Any CPU + {3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -135,6 +149,9 @@ Global {4F8D14A3-A465-4EC2-B175-A188B113AB99} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} {C17A1188-FA69-42BC-92E6-4F91D31B3A58} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} {FAFD9E43-508B-4F20-8AA2-8CADA697ED2D} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58} + {3F057926-562F-4EF4-BFC0-EE62372D4551} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} + {6B3FC07B-6208-4544-ACFB-79243A59EA1A} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {3680DAFB-10BA-4A0F-AE40-620D06DAF617} = {3F057926-562F-4EF4-BFC0-EE62372D4551} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E}