Implements first stage library management system

This commit is contained in:
BinaryAlley committed 2024-11-03 19:43:46 +02:00
1 parent 5e0f94cd82
commit 36352ea9e8
291 files changed
+3733 -1384

No files matched your search

@@ -0,0 +1,327 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
/// <summary>
/// Aggregate root for a book.
/// </summary>
[DebuggerDisplay("Id: {Id} Title: {Title}")]
public sealed class Book : AggregateRoot<BookId>
{
private readonly List<MediaContributorId> _contributors;
private readonly List<BookRating> _ratings;
private readonly List<Isbn> _isbns;
/// <summary>
/// Gets the written content metadata of the book.
/// </summary>
public WrittenContentMetadata Metadata { get; private set; }
/// <summary>
/// Gets the format of the book (e.g., Hardcover, Paperback), if applicable.
/// </summary>
public Optional<BookFormat> Format { get; private set; }
/// <summary>
/// Gets the edition of the book, if applicable.
/// </summary>
public Optional<string> Edition { get; private set; }
/// <summary>
/// Gets the volume or book number in the series, if applicable.
/// </summary>
public Optional<int> VolumeNumber { get; private set; }
/// <summary>
/// Gets the series name, if the book is part of a series.
/// </summary>
public Optional<BookSeries> Series { get; private set; }
/// <summary>
/// Gets the ASIN (Amazon Standard Identification Number) of the book, if applicable.
/// </summary>
public Optional<string> ASIN { get; private set; }
/// <summary>
/// Gets the Goodreads ID of the book, if applicable.
/// </summary>
public Optional<string> GoodreadsId { get; private set; }
/// <summary>
/// Gets the Library of Congress Control Number (LCCN) of the book, if applicable.
/// </summary>
public Optional<string> LCCN { get; private set; }
/// <summary>
/// Gets the OCLC Number (WorldCat identifier) of the book, if applicable.
/// </summary>
public Optional<string> OCLCNumber { get; private set; }
/// <summary>
/// Gets the Open Library ID of the book, if applicable.
/// </summary>
public Optional<string> OpenLibraryId { get; private set; }
/// <summary>
/// Gets the LibraryThing ID of the book, if applicable.
/// </summary>
public Optional<string> LibraryThingId { get; private set; }
/// <summary>
/// Gets the Google Books ID of the book, if applicable.
/// </summary>
public Optional<string> GoogleBooksId { get; private set; }
/// <summary>
/// Gets the Barnes & Noble ID of the book, if applicable.
/// </summary>
public Optional<string> BarnesAndNobleId { get; private set; }
/// <summary>
/// Gets the Apple Books ID of the book, if applicable.
/// </summary>
public Optional<string> AppleBooksId { get; private set; }
/// <summary>
/// Gets the list of ISBN (International Standard Book Number) of the book.
/// </summary>
public IReadOnlyCollection<Isbn> ISBNs => _isbns.AsReadOnly();
/// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this book.
/// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
/// <summary>
/// Gets the list of ratings for this book.
/// </summary>
public IReadOnlyCollection<BookRating> Ratings => _ratings.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="Book"/> class.
/// </summary>
/// <param name="id">The unique identifier of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
private Book(
BookId id,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings) : base(id)
{
Id = id;
Metadata = metadata;
Format = format;
Edition = edition;
VolumeNumber = volumeNumber;
Series = series;
ASIN = asin;
GoodreadsId = goodreadsId;
LCCN = lccn;
OCLCNumber = oclcNumber;
OpenLibraryId = openLibraryId;
LibraryThingId = libraryThingId;
GoogleBooksId = googleBooksId;
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
Created = created;
Updated = updated.HasValue ? updated.Value : null;
_isbns = isbns;
_contributors = contributors;
_ratings = ratings;
}
#pragma warning disable CS8618
/// <summary>
/// Initializes a new instance of the <see cref="Book"/> class.
/// </summary>
private Book() // only needed during reflection
{
}
#pragma warning restore CS8618
/// <summary>
/// Creates a new instance of the <see cref="Book"/> class.
/// </summary>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
return new Book(
BookId.CreateUnique(),
metadata,
format,
edition,
volumeNumber,
series,
asin,
goodreadsId,
lccn,
oclcNumber,
openLibraryId,
libraryThingId,
googleBooksId,
barnesAndNobleId,
appleBooksId,
DateTime.UtcNow,
default,
isbns,
contributors,
ratings
);
}
/// <summary>
/// Creates a new instance of the <see cref="Book"/>, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the id of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
BookId id,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
return new Book(
id,
metadata,
format,
edition,
volumeNumber,
series,
asin,
goodreadsId,
lccn,
oclcNumber,
openLibraryId,
libraryThingId,
googleBooksId,
barnesAndNobleId,
appleBooksId,
created,
updated,
isbns,
contributors,
ratings
);
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
/// <summary>
/// Entity for a book series.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class BookSeries : Entity<BookSeriesId>
{
private readonly List<Book> _books;
/// <summary>
/// Gets the written content metadata of the book series.
/// </summary>
public WrittenContentMetadata Metadata { get; private set; }
/// <summary>
/// Gets a value indicating whether the series is complete.
/// </summary>
public bool IsComplete { get; private set; }
/// <summary>
/// Gets the collection of books in the series.
/// </summary>
public IReadOnlyCollection<Book> Books => _books.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
private BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List<Book> books)
: base(id)
{
Id = id;
Metadata = metadata;
IsComplete = isComplete;
_books = books;
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
BookSeriesId id,
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
id,
metadata,
isComplete,
books
);
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
BookSeriesId.CreateUnique(),
metadata,
isComplete,
books
);
}
/// <summary>
/// Adds a book to the series.
/// </summary>
/// <param name="book">The book to be added.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Created> AddBook(Book book)
{
if (_books.Contains(book))
return Errors.WrittenContent.TheBookIsAlreadyInTheSeries;
_books.Add(book);
return Result.Created;
}
/// <summary>
/// Removes a book from the series.
/// </summary>
/// <param name="book">The book to be removed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Deleted> RemoveBook(Book book)
{
if (!_books.Contains(book))
return Errors.WrittenContent.TheBookIsNotInTheSeries;
_books.Remove(book);
return Result.Deleted;
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
/// <summary>
/// Service for managing book libraries.
/// </summary>
public sealed class BookLibraryService : IBookLibraryService
{
/// <summary>
/// Gets the collection of books in the library.
/// </summary>
public ICollection<Book> Books => throw new NotImplementedException();
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
/// <summary>
/// Interface for the service for managing book libraries.
/// </summary>
public interface IBookLibraryService
{
/// <summary>
/// Gets the collection of books in the library.
/// </summary>
ICollection<Book> Books { get; }
// ICollection<BookSeries> Series { get; }
// void AddBook(Book book);
// void RemoveBook(Guid bookId);
// void AddSeries(BookSeries series);
// void RemoveSeries(Guid seriesId);
// Book GetBook(Guid bookId);
// BookSeries GetSeries(Guid seriesId);
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="BookId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="BookId"/> class.
/// </summary>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId CreateUnique()
{
return new BookId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookId"/> instance.</param>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId Create(Guid value)
{
return new BookId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book library.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookLibraryId : EntityId<Guid> // TODO: to be removed
{
/// <summary>
/// Initializes a new instance of the <see cref="BookLibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookLibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="BookLibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="BookLibraryId"/> instance.</returns>
public static ErrorOr<BookLibraryId> CreateUnique()
{
// TODO: enforce invariants
return new BookLibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookLibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookLibraryId"/> instance.</param>
/// <returns>The created <see cref="BookLibraryId"/> instance.</returns>
public static ErrorOr<BookLibraryId> Create(Guid value)
{
// TODO: enforce invariants
return new BookLibraryId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the rating of a media element.
/// </summary>
[DebuggerDisplay("{Value}/{MaxValue}")]
public class BookRating : Rating
{
/// <summary>
/// Gets the optional source of the rating (e.g., "Goodreads", "Amazon").
/// </summary>
public Optional<BookRatingSource> Source { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
private BookRating(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
: base(value, maxValue, voteCount)
{
Source = source;
}
/// <summary>
/// Creates a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Rating"/>, or an error message.
/// </returns>
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
{
if (maxValue < 0 || value < 0)
return Errors.Metadata.RatingValueMustBePositive;
if (value > maxValue)
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new BookRating(value, maxValue, source, voteCount);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return MaxValue;
yield return Source;
yield return VoteCount;
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current class.</returns>
public override string ToString()
{
string baseString = $"{Value}/{MaxValue}";
if (Source.HasValue)
baseString += $" ({Source.Value})";
if (VoteCount.HasValue)
baseString += $" [{VoteCount.Value} votes]";
return baseString;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book series.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookSeriesId : ValueObject
{
public Guid Value { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BookSeriesId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookSeriesId(Guid value)
{
Value = value;
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeriesId"/> class.
/// </summary>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static BookSeriesId CreateUnique()
{
return new BookSeriesId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeriesId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookSeriesId"/> instance.</param>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static BookSeriesId Create(Guid value)
{
return new BookSeriesId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the ISBN of a book.
/// </summary>
[DebuggerDisplay("{Value} ({Format})")]
public sealed class Isbn : ValueObject
{
private static readonly Regex s_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 s_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);
/// <summary>
/// Gets the value of the ISBN.
/// </summary>
public string Value { get; private set; }
/// <summary>
/// Gets the format of the ISBN.
/// </summary>
public IsbnFormat Format { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Isbn"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
/// <param name="format">The format of the ISBN representing this object.</param>
private Isbn(string value, IsbnFormat format)
{
Value = value;
Format = format;
}
/// <summary>
/// Creates a new instance of the <see cref="Isbn"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
/// <param name="format">The format of the ISBN representing this object.</param>
/// <returns>The created <see cref="Isbn"/> instance.</returns>
public static ErrorOr<Isbn> Create(string? value, IsbnFormat format)
{
// enforce invariants
if (string.IsNullOrWhiteSpace(value))
return Errors.WrittenContent.IsbnValueCannotBeEmpty;
// remove hyphens and spaces, for validation
string cleanedValue = Regex.Replace(value, @"[-\s]", string.Empty);
switch (format)
{
case IsbnFormat.Isbn10:
if (!IsValidIsbn10(cleanedValue))
return Errors.WrittenContent.InvalidIsbn10Format;
break;
case IsbnFormat.Isbn13:
if (!IsValidIsbn13(cleanedValue))
return Errors.WrittenContent.InvalidIsbn13Format;
break;
default:
return Errors.WrittenContent.UnknownIsbnFormat;
}
return new Isbn(value, format);
}
/// <summary>
/// Validates an ISBN-10 string.
/// </summary>
/// <param name="isbn">The ISBN-10 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-10 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn10(string isbn)
{
if (!s_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++)
sum += (10 - i) * (isbn[i] - '0');
char lastChar = isbn[9];
if (lastChar == 'X')
sum += 10;
else
sum += lastChar - '0';
return sum % 11 == 0;
}
/// <summary>
/// Validates an ISBN-13 string.
/// </summary>
/// <param name="isbn">The ISBN-13 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-13 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn13(string isbn)
{
if (!s_isbn13Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "");
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0) ? isbn[i] - '0' : 3 * (isbn[i] - '0');
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == (isbn[12] - '0');
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return Format;
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the metadata of a written media element.
/// </summary>
[DebuggerDisplay("{Title}")]
public class WrittenContentMetadata : BaseMetadata
{
/// <summary>
/// Gets the publisher of the written content, if applicable.
/// </summary>
public Optional<string> Publisher { get; }
/// <summary>
/// Gets the number of pages in the written content, if applicable.
/// </summary>
public Optional<int> PageCount { get; }
/// <summary>
/// Initializes a new instance of the <see cref="WrittenContentMetadata"/> class.
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the written content, if applicable.</param>
/// <param name="description">The description of the written content, if applicable.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content, if applicable.</param>
/// <param name="originalLanguage">The optional original language of the written content, if applicable.</param>
/// <param name="publisher">The publisher of the written content, if applicable.</param>
/// <param name="pageCount">The number of pages in the written content, if applicable.</param>
private WrittenContentMetadata(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
Publisher = publisher;
PageCount = pageCount;
}
/// <summary>
/// Creates a new instance of the <see cref="WrittenContentMetadata"/> class.
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the written content, if applicable.</param>
/// <param name="description">The description of the written content, if applicable.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content.</param>
/// <param name="originalLanguage">The optional original language of the written content, if applicable.</param>
/// <param name="publisher">The publisher of the written content, if applicable.</param>
/// <param name="pageCount">The number of pages in the written content, if applicable.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="WrittenContentMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<WrittenContentMetadata> Create(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
{
if (string.IsNullOrWhiteSpace(title))
return Errors.Metadata.TitleCannotBeEmpty;
if (releaseInfo is null)
return Errors.Metadata.ReleaseInfoCannotBeNull;
if (genres is null)
return Errors.Metadata.GenresListCannotBeNull;
if (tags is null)
return Errors.Metadata.TagsListCannotBeNull;
return new WrittenContentMetadata(
title,
originalTitle,
description,
releaseInfo,
genres, tags,
language,
originalLanguage,
publisher,
pageCount
);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return Publisher;
yield return PageCount;
}
}