Centralizes audit column ownership in the auditing interceptor

Removes explicit audit assignments from mappings, handlers, repositories,
seeding, and background jobs, leaving the auditing interceptor as the only
writer of the audit columns for ordinary saves.

Adds a one-time initialization save so setup can attribute the original admin
account and seeded rows to the SYSTEM audit identity, while ordinary anonymous
writes remain unattributed with Guid.Empty.
This commit is contained in:
BinaryAlley committed 2026-11-21 12:00:00 +02:00
1 parent b56fabf5df
commit 7253f1507c
98 files changed
+731 -516

No files matched your search

@@ -94,3 +94,11 @@ Ordering is storage owned as well. The unique index on `(PlaylistId, Position)`
The playlist row now carries a denormalized `EntryCount`, maintained by the set-based append and removal operations in the same statement that updates the playlist activity time and concurrency token. Window reads, moves and the single-add read-back use that column instead of counting the entries of the playlist, so none of them scan an index proportional to the playlist size. The playlist row now carries a denormalized `EntryCount`, maintained by the set-based append and removal operations in the same statement that updates the playlist activity time and concurrency token. Window reads, moves and the single-add read-back use that column instead of counting the entries of the playlist, so none of them scan an index proportional to the playlist size.
Details edits still go through `EditableValuesCopier`, but the copier now compares the incoming value with the tracked value before assigning it and marks only an actual change as modified. `PlaylistRepository.UpdateAsync` also compares the tracked original values explicitly before it decides to increment the concurrency token, so a no-op save neither restamps the row nor bumps its version. Details edits still go through `EditableValuesCopier`, but the copier now compares the incoming value with the tracked value before assigning it and marks only an actual change as modified. `PlaylistRepository.UpdateAsync` also compares the tracked original values explicitly before it decides to increment the concurrency token, so a no-op save neither restamps the row nor bumps its version.
## Amendment: Explicit Audit Identity for Application Initialization (2026-11-20)
The one-time application initialization is the only save whose audit identity is provided explicitly instead of being stamped by the auditing interceptor. The setup handler creates the original administrator account before any user exists, and the seed service creates the default permissions, roles, role-permission grants, user-role link and scheduled jobs in the same anonymous flow. Those rows therefore cannot derive an actor from `ICurrentUserService`.
The bootstrap code sets `CreatedBy` to the fixed SYSTEM audit identifier `11111111-1111-1111-1111-111111111111` and sets `CreatedOnUtc` from `IDateTimeProvider`, then saves through `SaveChangesAsInitializationAsync`. That method marks the save on the `LuminaDbContext` for its duration, and the interceptor skips its stamping only for that save. No other save path is affected.
The SYSTEM identity is never inferred from a missing authenticated user. Ordinary anonymous creation and modification remain unattributed with `Guid.Empty`, and the interceptor is still the sole writer for every ordinary save. The initialization exception exists because the app has no user account to attribute the bootstrap rows to, and it is confined to the setup and seed code paths.
@@ -84,3 +84,7 @@ Construct the version 7 timestamp and random fields inside the bulk SQL statemen
Migrate every stored primary key and foreign key to a version 7 value. Migrate every stored primary key and foreign key to a version 7 value.
**Rejected**: rewriting primary keys means rewriting every foreign key that references them, with a high risk of corruption and downtime, for no benefit to existing rows. **Rejected**: rewriting primary keys means rewriting every foreign key that references them, with a high risk of corruption and downtime, for no benefit to existing rows.
## Amendment: Relocation of the SYSTEM Audit Identity (2026-11-25)
The fixed SYSTEM audit identifier is no longer declared inline in `UpdateAuditableEntitiesInterceptor`. It is declared as the static readonly field `AuditIdentities.s_systemUserId` in `Lumina.Application/Common/DataAccess/Entities/Common/AuditIdentities.cs`. The identifier value and its behavior are unchanged.
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Common;
/// <summary>
/// Defines the fixed audit identities used by the persistence layer.
/// </summary>
/// <remarks>
/// The SYSTEM identity is only for the explicit one-time application initialization save. Ordinary anonymous creation and modification remain
/// unattributed with <see cref="Guid.Empty"/>; the SYSTEM identity is never inferred from a missing authenticated user.
/// </remarks>
public static class AuditIdentities
{
/// <summary>
/// The fixed identifier of the SYSTEM audit user, used for rows created during application initialization, before any user account exists.
/// </summary>
public static readonly Guid s_systemUserId = Guid.Parse("11111111-1111-1111-1111-111111111111");
}
@@ -40,12 +40,12 @@ public class FavoriteEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -55,5 +55,5 @@ public class FavoriteEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -99,12 +99,12 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -114,5 +114,5 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -73,12 +73,12 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -88,5 +88,5 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -46,12 +46,12 @@ public class MediaContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -61,5 +61,5 @@ public class MediaContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -37,12 +37,12 @@ public class AlbumContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -245,12 +245,12 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -260,5 +260,5 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -37,12 +37,12 @@ public class ArtistContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -164,12 +164,12 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -179,5 +179,5 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -72,12 +72,12 @@ public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -87,5 +87,5 @@ public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -37,12 +37,12 @@ public class TrackContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -305,12 +305,12 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -320,5 +320,5 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -121,12 +121,12 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -136,5 +136,5 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -53,12 +53,12 @@ public class LibraryScanEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -68,5 +68,5 @@ public class LibraryScanEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -50,12 +50,12 @@ public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -65,5 +65,5 @@ public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -65,12 +65,12 @@ public class BookArtworkEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -80,5 +80,5 @@ public class BookArtworkEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -37,12 +37,12 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -241,12 +241,12 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -256,5 +256,5 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -61,12 +61,12 @@ public class PlaylistEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -76,5 +76,5 @@ public class PlaylistEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -40,12 +40,12 @@ public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAudita
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -55,5 +55,5 @@ public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAudita
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -35,12 +35,12 @@ public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEn
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -50,5 +50,5 @@ public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEn
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -40,12 +40,12 @@ public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAudit
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -55,5 +55,5 @@ public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAudit
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -56,12 +56,12 @@ public class PluginEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -71,5 +71,5 @@ public class PluginEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -71,12 +71,12 @@ public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -86,5 +86,5 @@ public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -56,12 +56,12 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -71,5 +71,5 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -41,12 +41,12 @@ public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntit
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -56,5 +56,5 @@ public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntit
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -71,12 +71,12 @@ public class ThemeEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the time and date when the entity was added. /// Gets or sets the time and date when the entity was added.
/// </summary> /// </summary>
public required DateTime CreatedOnUtc { get; set; } public DateTime CreatedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Id of the user that created the entity. /// Gets or sets the Id of the user that created the entity.
/// </summary> /// </summary>
public required Guid CreatedBy { get; set; } public Guid CreatedBy { get; set; }
/// <summary> /// <summary>
/// Gets or sets the optional time and date when the entity was updated. /// Gets or sets the optional time and date when the entity was updated.
@@ -86,5 +86,5 @@ public class ThemeEntity : IStorageEntity, IAuditableEntity
/// <summary> /// <summary>
/// Gets or sets the optional Id of the user that updated the entity. /// Gets or sets the optional Id of the user that updated the entity.
/// </summary> /// </summary>
public required Guid? UpdatedBy { get; set; } public Guid? UpdatedBy { get; set; }
} }
@@ -15,26 +15,23 @@ public interface IDataSeedService
/// <summary> /// <summary>
/// Sets up default authorization permissions in the system. /// Sets up default authorization permissions in the system.
/// </summary> /// </summary>
/// <param name="adminId">The unique identifier of the admin admin user who will own these permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken); Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Sets up default authorization roles in the system. /// Sets up default authorization roles in the system.
/// </summary> /// </summary>
/// <param name="userId">The unique identifier of the admin user for whom roles will be set.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken); Task<Result<Created>> SetDefaultAuthorizationRolesAsync(CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Assigns admin role permissions to the admin user. /// Assigns admin role permissions to the admin user.
/// </summary> /// </summary>
/// <param name="userId">The unique identifier of the admin user to receive admin role permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken); Task<Result<Created>> SetAdminRolePermissionsAsync(CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Assigns admin role to the admin user. /// Assigns admin role to the admin user.
@@ -185,6 +185,14 @@ public interface IUnitOfWork
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken); Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken);
/// <summary>
/// Saves the changes made during the one-time application initialization, whose audit values are provided explicitly by the bootstrap code instead of
/// being stamped by the auditing interceptor.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> SaveChangesAsInitializationAsync(CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
/// </summary> /// </summary>
@@ -1,7 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Favorites; using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate; using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
using System;
#endregion #endregion
namespace Lumina.Application.Common.Mapping.Favorites; namespace Lumina.Application.Common.Mapping.Favorites;
@@ -23,11 +22,7 @@ public static class FavoriteMapping
Id = domainEntity.Id.Value, Id = domainEntity.Id.Value,
UserId = domainEntity.UserId.Value, UserId = domainEntity.UserId.Value,
MediaKind = domainEntity.MediaKind, MediaKind = domainEntity.MediaKind,
MediaItemId = domainEntity.MediaItemId.Value, MediaItemId = domainEntity.MediaItemId.Value
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
UpdatedBy = null
}; };
} }
} }
@@ -44,12 +44,7 @@ public static class MediaConsumptionRecordMapping
: null, : null,
LastProgressFraction = domainEntity.LastProgressFraction, LastProgressFraction = domainEntity.LastProgressFraction,
ConsecutivePagesRead = domainEntity.ConsecutivePagesRead, ConsecutivePagesRead = domainEntity.ConsecutivePagesRead,
Version = 1, Version = 1
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
@@ -37,12 +37,7 @@ public static class MediaResumePointMapping
: null, : null,
LastProgressFraction = domainEntity.LastProgressFraction, LastProgressFraction = domainEntity.LastProgressFraction,
LastConsumedOnUtc = domainEntity.LastConsumedOnUtc, LastConsumedOnUtc = domainEntity.LastConsumedOnUtc,
Version = 1, Version = 1
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
@@ -69,18 +69,10 @@ public static class AlbumMapping
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
AlbumId = domainEntity.Id.Value, AlbumId = domainEntity.Id.Value,
MediaContributorId = contributor.ContributorId.Value, MediaContributorId = contributor.ContributorId.Value,
Role = contributor.Role, Role = contributor.Role
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedBy = null
})], })],
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
Tracks = [.. domainEntity.Tracks.Select(track => track.ToRepositoryEntity(domainEntity.Id.Value, libraryId))], Tracks = [.. domainEntity.Tracks.Select(track => track.ToRepositoryEntity(domainEntity.Id.Value, libraryId))]
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
} }
@@ -51,17 +51,9 @@ public static class ArtistMapping
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
ArtistId = domainEntity.Id.Value, ArtistId = domainEntity.Id.Value,
MediaContributorId = contributor.ContributorId.Value, MediaContributorId = contributor.ContributorId.Value,
Role = contributor.Role, Role = contributor.Role
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedBy = null
})], })],
Albums = [.. domainEntity.Albums.Select(album => album.ToRepositoryEntity(domainEntity.Id.Value, domainEntity.LibraryId.Value))], Albums = [.. domainEntity.Albums.Select(album => album.ToRepositoryEntity(domainEntity.Id.Value, domainEntity.LibraryId.Value))]
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
} }
@@ -75,10 +75,7 @@ public static class TrackMapping
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
TrackId = domainEntity.Id.Value, TrackId = domainEntity.Id.Value,
MediaContributorId = contributor.ContributorId.Value, MediaContributorId = contributor.ContributorId.Value,
Role = contributor.Role, Role = contributor.Role
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedBy = null
})], })],
Moods = [.. domainEntity.Moods.ToRepositoryEntities()], Moods = [.. domainEntity.Moods.ToRepositoryEntities()],
Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()], Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()],
@@ -88,12 +85,7 @@ public static class TrackMapping
WorkIswcs = domainEntity.Work.HasValue WorkIswcs = domainEntity.Work.HasValue
? [.. domainEntity.Work.Value.Iswcs.Select(iswc => new TrackWorkIswcEntity(iswc))] ? [.. domainEntity.Work.Value.Iswcs.Select(iswc => new TrackWorkIswcEntity(iswc))]
: [], : [],
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()]
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
} }
@@ -1,7 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Linq; using System.Linq;
#endregion #endregion
@@ -51,16 +50,8 @@ public static class LibraryMapping
UserId = domainEntity.UserId.Value, // Rest of properties will be populated by EF Core. UserId = domainEntity.UserId.Value, // Rest of properties will be populated by EF Core.
Status = default, Status = default,
User = null!, User = null!,
Library = null!, Library = null!
CreatedBy = default, })]
CreatedOnUtc = default,
UpdatedBy = default,
})],
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
} }
@@ -1,7 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using System;
#endregion #endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
@@ -25,11 +24,7 @@ public static class LibraryScanMapping
LibraryId = domainEntity.LibraryId.Value, LibraryId = domainEntity.LibraryId.Value,
Status = domainEntity.Status, Status = domainEntity.Status,
User = null!, User = null!,
Library = null!, Library = null!
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
UpdatedBy = Guid.Empty
}; };
} }
} }
@@ -63,17 +63,9 @@ public static class BookMapping
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
BookId = domainEntity.Id.Value, BookId = domainEntity.Id.Value,
MediaContributorId = contributor.ContributorId.Value, MediaContributorId = contributor.ContributorId.Value,
Role = contributor.Role, Role = contributor.Role
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedBy = null
})], })],
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()]
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null,
}; };
} }
@@ -114,7 +106,5 @@ public static class BookMapping
entity.GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null; entity.GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null;
entity.BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null; entity.BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null;
entity.AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null; entity.AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null;
entity.UpdatedOnUtc = DateTime.UtcNow;
entity.UpdatedBy = Guid.CreateVersion7();
} }
} }
@@ -21,9 +21,8 @@ public static class UpdateBookCoverCommandMapping
/// <param name="existingCover">The existing cover artwork of the book, or <see langword="null"/> when the book has none.</param> /// <param name="existingCover">The existing cover artwork of the book, or <see langword="null"/> when the book has none.</param>
/// <param name="bookId">The Id of the book the cover belongs to.</param> /// <param name="bookId">The Id of the book the cover belongs to.</param>
/// <param name="storedCoverPath">The relative path of the stored cover image.</param> /// <param name="storedCoverPath">The relative path of the stored cover image.</param>
/// <param name="userId">The Id of the user that stored the cover image.</param>
/// <returns>The cover artwork of the book, carrying the stored cover image.</returns> /// <returns>The cover artwork of the book, carrying the stored cover image.</returns>
public static BookArtworkEntity ToRepositoryEntity(this UpdateBookCoverCommand command, BookArtworkEntity? existingCover, Guid bookId, string storedCoverPath, Guid userId) public static BookArtworkEntity ToRepositoryEntity(this UpdateBookCoverCommand command, BookArtworkEntity? existingCover, Guid bookId, string storedCoverPath)
{ {
if (existingCover is null) if (existingCover is null)
{ {
@@ -34,18 +33,13 @@ public static class UpdateBookCoverCommandMapping
ArtworkType = ArtworkType.Cover, ArtworkType = ArtworkType.Cover,
Ordinal = 0, Ordinal = 0,
FileName = storedCoverPath, FileName = storedCoverPath,
Status = ArtworkStatus.Enriched, Status = ArtworkStatus.Enriched
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = null
}; };
} }
existingCover.FileName = storedCoverPath; existingCover.FileName = storedCoverPath;
existingCover.Status = ArtworkStatus.Enriched; existingCover.Status = ArtworkStatus.Enriched;
existingCover.LastUpdateUtc = DateTime.UtcNow; existingCover.LastUpdateUtc = DateTime.UtcNow;
existingCover.UpdatedOnUtc = DateTime.UtcNow;
existingCover.UpdatedBy = userId;
return existingCover; return existingCover;
} }
} }
@@ -1,7 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Playlists; using Lumina.Application.Common.DataAccess.Entities.Playlists;
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
using System;
using System.Linq; using System.Linq;
#endregion #endregion
@@ -30,11 +29,7 @@ public static class PlaylistMapping
.OrderBy(entry => entry.Position) .OrderBy(entry => entry.Position)
.Select(entry => entry.ToRepositoryEntity(domainEntity.Id.Value))], .Select(entry => entry.ToRepositoryEntity(domainEntity.Id.Value))],
// This is the correct count for an insert. The update path deliberately keeps the stored count, because details edits never load the entries and must not overwrite it. // This is the correct count for an insert. The update path deliberately keeps the stored count, because details edits never load the entries and must not overwrite it.
EntryCount = domainEntity.Entries.Count, EntryCount = domainEntity.Entries.Count
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
UpdatedBy = null
}; };
} }
} }
@@ -99,11 +99,7 @@ public static class ScheduledJobEntityMapping
Status = status, Status = status,
OwnerUserId = repositoryEntity.OwnerUserId, OwnerUserId = repositoryEntity.OwnerUserId,
LastStartedOnUtc = lastStartedOnUtc, LastStartedOnUtc = lastStartedOnUtc,
LastCompletedOnUtc = lastCompletedOnUtc, LastCompletedOnUtc = lastCompletedOnUtc
CreatedOnUtc = repositoryEntity.CreatedOnUtc,
CreatedBy = repositoryEntity.CreatedBy,
UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
UpdatedBy = repositoryEntity.UpdatedBy
}; };
} }
@@ -44,11 +44,7 @@ public static class ScheduledJobExecutionEntityMapping
IsCycleRun = repositoryEntity.IsCycleRun, IsCycleRun = repositoryEntity.IsCycleRun,
WasCycleActive = repositoryEntity.WasCycleActive, WasCycleActive = repositoryEntity.WasCycleActive,
StartedOnUtc = repositoryEntity.StartedOnUtc, StartedOnUtc = repositoryEntity.StartedOnUtc,
CompletedOnUtc = completedOnUtc, CompletedOnUtc = completedOnUtc
CreatedOnUtc = repositoryEntity.CreatedOnUtc,
CreatedBy = repositoryEntity.CreatedBy,
UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
UpdatedBy = repositoryEntity.UpdatedBy
}; };
} }
} }
@@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling; using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
#endregion #endregion
namespace Lumina.Application.Common.Mapping.Scheduling; namespace Lumina.Application.Common.Mapping.Scheduling;
@@ -32,11 +31,7 @@ public static class ScheduledJobMapping
Status = domainEntity.Status, Status = domainEntity.Status,
OwnerUserId = domainEntity.OwnerUserId.Value, OwnerUserId = domainEntity.OwnerUserId.Value,
LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null, LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null, LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
UpdatedBy = Guid.Empty
}; };
} }
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS; using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.Seed;
@@ -107,7 +108,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
Libraries = [], Libraries = [],
UserPermissions = [], UserPermissions = [],
UserRole = null, UserRole = null,
CreatedBy = id, CreatedBy = AuditIdentities.s_systemUserId,
LibraryScans = [], LibraryScans = [],
}; };
// If the user enabled two factor auth, include a QR with the totp secret. // If the user enabled two factor auth, include a QR with the totp secret.
@@ -124,20 +125,20 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (insertUserResult.IsFailure) if (insertUserResult.IsFailure)
return insertUserResult.Errors; return insertUserResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
// Set the default permissions, roles, roles permissions. // Set the default permissions, roles, roles permissions.
Result<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); Result<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(cancellationToken).ConfigureAwait(false);
if (setPermissionsResult.IsFailure) if (setPermissionsResult.IsFailure)
return setPermissionsResult.Errors; return setPermissionsResult.Errors;
Result<Created> setRoleResult = await _dataSeedService.SetDefaultAuthorizationRolesAsync(id, cancellationToken).ConfigureAwait(false); Result<Created> setRoleResult = await _dataSeedService.SetDefaultAuthorizationRolesAsync(cancellationToken).ConfigureAwait(false);
if (setRoleResult.IsFailure) if (setRoleResult.IsFailure)
return setRoleResult.Errors; return setRoleResult.Errors;
Result<Created> setRolePermissionResult = await _dataSeedService.SetAdminRolePermissionsAsync(id, cancellationToken).ConfigureAwait(false); Result<Created> setRolePermissionResult = await _dataSeedService.SetAdminRolePermissionsAsync(cancellationToken).ConfigureAwait(false);
if (setRolePermissionResult.IsFailure) if (setRolePermissionResult.IsFailure)
return setRolePermissionResult.Errors; return setRolePermissionResult.Errors;
@@ -122,7 +122,7 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
// Map the newly stored cover image onto the artwork of the book, replacing the existing cover or adding a new one. // Map the newly stored cover image onto the artwork of the book, replacing the existing cover or adding a new one.
BookArtworkEntity? existingCover = existingBook.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover); BookArtworkEntity? existingCover = existingBook.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover);
BookArtworkEntity coverArtwork = command.ToRepositoryEntity(existingCover, bookId, storeArtworkResult.Value, userId); BookArtworkEntity coverArtwork = command.ToRepositoryEntity(existingCover, bookId, storeArtworkResult.Value);
if (existingCover is null) if (existingCover is null)
existingBook.Artwork.Add(coverArtwork); existingBook.Artwork.Add(coverArtwork);
@@ -71,11 +71,7 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler<U
UserId = userId, UserId = userId,
JobTypeFilter = command.JobTypeFilter, JobTypeFilter = command.JobTypeFilter,
DisplayTimeSpan = command.DisplayTimeSpan, DisplayTimeSpan = command.DisplayTimeSpan,
DisplayTimeUnit = command.DisplayTimeUnit, DisplayTimeUnit = command.DisplayTimeUnit
CreatedOnUtc = default,
CreatedBy = default,
UpdatedOnUtc = null,
UpdatedBy = null
}; };
Result<Updated> upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -72,11 +72,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle
IsCycleRun = domainEvent.IsCycleRun, IsCycleRun = domainEvent.IsCycleRun,
WasCycleActive = wasCycleActive, WasCycleActive = wasCycleActive,
StartedOnUtc = domainEvent.StartedOnUtc, StartedOnUtc = domainEvent.StartedOnUtc,
CompletedOnUtc = null, CompletedOnUtc = null
CreatedOnUtc = scheduledJob.CreatedOnUtc,
CreatedBy = scheduledJob.CreatedBy,
UpdatedOnUtc = null,
UpdatedBy = null
}; };
Result<Created> insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false); Result<Created> insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false);
if (insertExecutionResult.IsFailure) if (insertExecutionResult.IsFailure)
@@ -119,8 +119,6 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
// Bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them. // Bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them.
theme.IsDeleted = true; theme.IsDeleted = true;
theme.IsCurrent = null; theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
} }
else else
@@ -103,11 +103,7 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
IsCurrent = existingTheme.IsCurrent, IsCurrent = existingTheme.IsCurrent,
// Reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again. // Reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again.
IsDeleted = false, IsDeleted = false,
InstalledAtUtc = DateTime.UtcNow, InstalledAtUtc = DateTime.UtcNow
CreatedOnUtc = existingTheme.CreatedOnUtc,
CreatedBy = existingTheme.CreatedBy,
UpdatedOnUtc = DateTime.UtcNow,
UpdatedBy = userId
}; };
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(themeEntity, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(themeEntity, cancellationToken).ConfigureAwait(false);
@@ -126,10 +122,7 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
Version = manifest.Version, Version = manifest.Version,
PreviewPath = manifest.Preview, PreviewPath = manifest.Preview,
InstallSource = ThemeInstallSource.Uploaded, InstallSource = ThemeInstallSource.Uploaded,
InstalledAtUtc = DateTime.UtcNow, InstalledAtUtc = DateTime.UtcNow
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = userId
}; };
Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
@@ -93,8 +93,6 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
theme.IsDeleted = false; theme.IsDeleted = false;
theme.IsCurrent = null; theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
return updateResult.Errors; return updateResult.Errors;
@@ -96,8 +96,6 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
// Activate the requested theme and persist its update. // Activate the requested theme and persist its update.
theme.IsCurrent = true; theme.IsCurrent = true;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -7,7 +7,6 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors; using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authentication; using Lumina.Contracts.Responses.Authentication;
using System; using System;
@@ -28,7 +27,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
private readonly ICryptographyService _cryptographyService; private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator; private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator; private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IValidator<RegisterUserCommand> _validator; private readonly IValidator<RegisterUserCommand> _validator;
/// <summary> /// <summary>
@@ -39,7 +37,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param> /// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param> /// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param> /// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="validator">Injected validator for application validation rules.</param> /// <param name="validator">Injected validator for application validation rules.</param>
public RegisterUserCommandHandler( public RegisterUserCommandHandler(
IUnitOfWork unitOfWork, IUnitOfWork unitOfWork,
@@ -47,7 +44,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
ICryptographyService cryptographyService, ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator, ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator, IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider,
IValidator<RegisterUserCommand> validator) IValidator<RegisterUserCommand> validator)
{ {
_unitOfWork = unitOfWork; _unitOfWork = unitOfWork;
@@ -55,7 +51,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
_cryptographyService = cryptographyService; _cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator; _totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator; _qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_validator = validator; _validator = validator;
} }
@@ -88,11 +83,9 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
Id = id, Id = id,
Username = command.Username!, Username = command.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)), Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)),
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [], Libraries = [],
UserPermissions = [], UserPermissions = [],
UserRole = null, UserRole = null,
CreatedBy = id,
LibraryScans = [], LibraryScans = [],
}; };
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics;
@@ -64,6 +65,9 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
{ {
if (context is null) if (context is null)
return; return;
// Initialization is the one save whose audit identity is provided explicitly, because no user account exists yet.
if (context is LuminaDbContext luminaDbContext && luminaDbContext.IsInitializationSave)
return;
Guid? userId = _currentUserService.UserId; Guid? userId = _currentUserService.UserId;
DateTime utcNow = _dateTimeProvider.UtcNow; DateTime utcNow = _dateTimeProvider.UtcNow;
@@ -106,6 +110,6 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
// Set modification properties. // Set modification properties.
entry.Entity.UpdatedOnUtc = utcNow; entry.Entity.UpdatedOnUtc = utcNow;
entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id. entry.Entity.UpdatedBy = userId ?? default;
} }
} }
@@ -89,10 +89,7 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
{ {
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
DisplayName = displayName, DisplayName = displayName,
LegalName = legalName, LegalName = legalName
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
_luminaDbContext.MediaContributors.Add(contributor); _luminaDbContext.MediaContributors.Add(contributor);
return contributor; return contributor;
@@ -173,12 +173,7 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
ArtworkType = ArtworkType.Cover, ArtworkType = ArtworkType.Cover,
Ordinal = 0, Ordinal = 0,
FileName = fileName, FileName = fileName,
Status = ArtworkStatus.Enriched, Status = ArtworkStatus.Enriched
CreatedOnUtc = now,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
}); });
} }
else else
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.Seed;
@@ -41,18 +42,17 @@ public class DataSeedService : IDataSeedService
/// <summary> /// <summary>
/// Sets up default authorization permissions in the system. /// Sets up default authorization permissions in the system.
/// </summary> /// </summary>
/// <param name="adminId">The unique identifier of the admin admin user who will own these permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(CancellationToken cancellationToken)
{ {
// Create the default authorization permissions and add them to the repository. // Create the default authorization permissions and add them to the repository.
PermissionEntity[] defaultPermissions = PermissionEntity[] defaultPermissions =
[ [
new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow } new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId }
]; ];
foreach (PermissionEntity permission in defaultPermissions) foreach (PermissionEntity permission in defaultPermissions)
{ {
@@ -60,7 +60,7 @@ public class DataSeedService : IDataSeedService
if (insertPermissionResult.IsFailure) if (insertPermissionResult.IsFailure)
return insertPermissionResult.Errors; return insertPermissionResult.Errors;
} }
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
return Result.Created; return Result.Created;
@@ -69,15 +69,14 @@ public class DataSeedService : IDataSeedService
/// <summary> /// <summary>
/// Sets up default authorization roles in the system. /// Sets up default authorization roles in the system.
/// </summary> /// </summary>
/// <param name="userId">The unique identifier of the admin user for whom roles will be set.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(CancellationToken cancellationToken)
{ {
// Create the default authorization roles and add them to the repository. // Create the default authorization roles and add them to the repository.
RoleEntity[] defaultRoles = RoleEntity[] defaultRoles =
[ [
new() { RoleName = AuthorizationRoles.ADMIN, CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } new() { RoleName = AuthorizationRoles.ADMIN, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId }
]; ];
foreach (RoleEntity role in defaultRoles) foreach (RoleEntity role in defaultRoles)
{ {
@@ -85,7 +84,7 @@ public class DataSeedService : IDataSeedService
if (insertRoleResult.IsFailure) if (insertRoleResult.IsFailure)
return insertRoleResult.Errors; return insertRoleResult.Errors;
} }
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
return Result.Created; return Result.Created;
@@ -94,10 +93,9 @@ public class DataSeedService : IDataSeedService
/// <summary> /// <summary>
/// Assigns admin role permissions to the admin user. /// Assigns admin role permissions to the admin user.
/// </summary> /// </summary>
/// <param name="userId">The unique identifier of the admin user to receive admin role permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) public async Task<Result<Created>> SetAdminRolePermissionsAsync(CancellationToken cancellationToken)
{ {
// Get the admin role. // Get the admin role.
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false); Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
@@ -121,14 +119,14 @@ public class DataSeedService : IDataSeedService
PermissionId = permission.Id, PermissionId = permission.Id,
Role = getAdminRoleResult.Value, Role = getAdminRoleResult.Value,
RoleId = getAdminRoleResult.Value.Id, RoleId = getAdminRoleResult.Value.Id,
CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow,
CreatedOnUtc = _dateTimeProvider.UtcNow CreatedBy = AuditIdentities.s_systemUserId
}; };
Result<Created> insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false); Result<Created> insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
if (insertRolePermissionResult.IsFailure) if (insertRolePermissionResult.IsFailure)
return insertRolePermissionResult.Errors; return insertRolePermissionResult.Errors;
} }
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
return Result.Created; return Result.Created;
@@ -161,18 +159,18 @@ public class DataSeedService : IDataSeedService
// Add the admin role to the admin user. // Add the admin role to the admin user.
UserRoleEntity userRole = new() UserRoleEntity userRole = new()
{ {
CreatedBy = userId,
CreatedOnUtc = _dateTimeProvider.UtcNow,
Role = getAdminRoleResult.Value, Role = getAdminRoleResult.Value,
RoleId = getAdminRoleResult.Value.Id, RoleId = getAdminRoleResult.Value.Id,
User = getUserResult.Value, User = getUserResult.Value,
UserId = getUserResult.Value.Id UserId = getUserResult.Value.Id,
CreatedOnUtc = _dateTimeProvider.UtcNow,
CreatedBy = AuditIdentities.s_systemUserId
}; };
Result<Created> insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false); Result<Created> insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
if (insertUserRoleResult.IsFailure) if (insertUserRoleResult.IsFailure)
return insertUserRoleResult.Errors; return insertUserRoleResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
return Result.Created; return Result.Created;
@@ -208,7 +206,7 @@ public class DataSeedService : IDataSeedService
if (insertScheduledJobResult.IsFailure) if (insertScheduledJobResult.IsFailure)
return insertScheduledJobResult.Errors; return insertScheduledJobResult.Errors;
} }
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
return saveChangesResult.Errors; return saveChangesResult.Errors;
return Result.Created; return Result.Created;
@@ -241,9 +239,7 @@ public class DataSeedService : IDataSeedService
LastStartedOnUtc = null, LastStartedOnUtc = null,
LastCompletedOnUtc = null, LastCompletedOnUtc = null,
CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedOnUtc = _dateTimeProvider.UtcNow,
CreatedBy = adminUserId, CreatedBy = AuditIdentities.s_systemUserId
UpdatedOnUtc = null,
UpdatedBy = null
}; };
} }
} }
@@ -196,6 +196,12 @@ public class LuminaDbContext : DbContext
/// </summary> /// </summary>
public virtual DbSet<MediaResumePointEntity> MediaResumePoints { get; set; } = null!; public virtual DbSet<MediaResumePointEntity> MediaResumePoints { get; set; } = null!;
/// <summary>
/// Gets or sets whether the changes are being saved by the one-time application initialization, whose audit values are provided explicitly instead of
/// being stamped by the auditing interceptor.
/// </summary>
internal bool IsInitializationSave { get; set; }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class. /// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
/// </summary> /// </summary>
@@ -467,6 +467,35 @@ public class UnitOfWork : IUnitOfWork, IDisposable
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken) public async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken)
{
return await SaveChangesCoreAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Saves the changes made during the one-time application initialization, whose audit values are provided explicitly by the bootstrap code instead of
/// being stamped by the auditing interceptor.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> SaveChangesAsInitializationAsync(CancellationToken cancellationToken)
{
_luminaDbContext.IsInitializationSave = true;
try
{
return await SaveChangesCoreAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_luminaDbContext.IsInitializationSave = false;
}
}
/// <summary>
/// Saves the changes made to the database, reporting expected persistence conflicts as failure results.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> SaveChangesCoreAsync(CancellationToken cancellationToken)
{ {
try try
{ {
@@ -647,10 +647,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
ContentHash = contentHash, ContentHash = contentHash,
Status = status, Status = status,
Provider = provider, Provider = provider,
LastUpdateUtc = DateTime.UtcNow, LastUpdateUtc = DateTime.UtcNow
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
@@ -261,10 +261,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
LibraryId = libraryId, LibraryId = libraryId,
Name = name, Name = name,
MusicBrainzArtistId = musicBrainzArtistId, MusicBrainzArtistId = musicBrainzArtistId,
MetadataStatus = MetadataStatus.Pending, MetadataStatus = MetadataStatus.Pending
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
@@ -293,10 +290,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId, MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId,
ReleaseTypes = firstStagedItem.ReleaseType is null ? [] : [new AlbumReleaseTypeEntity(firstStagedItem.ReleaseType.Value)], ReleaseTypes = firstStagedItem.ReleaseType is null ? [] : [new AlbumReleaseTypeEntity(firstStagedItem.ReleaseType.Value)],
OriginalReleaseYear = firstStagedItem.ReleaseYear, OriginalReleaseYear = firstStagedItem.ReleaseYear,
MetadataStatus = MetadataStatus.Pending, MetadataStatus = MetadataStatus.Pending
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
@@ -335,10 +329,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
MusicBrainzTrackId = stagedItem.MusicBrainzTrackId, MusicBrainzTrackId = stagedItem.MusicBrainzTrackId,
MusicBrainzWorkId = stagedItem.MusicBrainzWorkId, MusicBrainzWorkId = stagedItem.MusicBrainzWorkId,
WorkTitle = stagedItem.WorkTitle, WorkTitle = stagedItem.WorkTitle,
MetadataStatus = MetadataStatus.Pending, MetadataStatus = MetadataStatus.Pending
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
} }
@@ -146,8 +146,6 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
library.PathTemplateFingerprint = pathTemplateFingerprint; library.PathTemplateFingerprint = pathTemplateFingerprint;
library.UpdatedOnUtc = DateTime.UtcNow;
library.UpdatedBy = Guid.CreateVersion7();
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
@@ -209,8 +209,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
else else
{ {
coverArtwork.Status = ArtworkStatus.Failed; coverArtwork.Status = ArtworkStatus.Failed;
coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
coverArtwork.UpdatedBy = Guid.CreateVersion7();
} }
return; return;
} }
@@ -239,8 +237,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
else else
{ {
existingCoverArtwork.Status = ArtworkStatus.Failed; existingCoverArtwork.Status = ArtworkStatus.Failed;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
} }
return; return;
} }
@@ -261,8 +257,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
existingCoverArtwork.Status = ArtworkStatus.Enriched; existingCoverArtwork.Status = ArtworkStatus.Enriched;
existingCoverArtwork.Provider = resolvedArtwork.ProviderName; existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
} }
} }
else else
@@ -271,8 +265,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
existingCoverArtwork!.Status = ArtworkStatus.Enriched; existingCoverArtwork!.Status = ArtworkStatus.Enriched;
existingCoverArtwork.Provider = resolvedArtwork.ProviderName; existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
} }
} }
@@ -340,10 +332,7 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
ContentHash = contentHash, ContentHash = contentHash,
Status = status, Status = status,
Provider = provider, Provider = provider,
LastUpdateUtc = lastUpdateUtc, LastUpdateUtc = lastUpdateUtc
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
@@ -176,10 +176,7 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
Path = path, Path = path,
Title = title, Title = title,
VolumeNumber = volumeNumber, VolumeNumber = volumeNumber,
MetadataStatus = MetadataStatus.Pending, MetadataStatus = MetadataStatus.Pending
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}; };
} }
@@ -220,8 +220,6 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
{ {
// No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata. // No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata.
bookEntity.MetadataStatus = MetadataStatus.Failed; bookEntity.MetadataStatus = MetadataStatus.Failed;
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
bookEntity.UpdatedBy = Guid.CreateVersion7();
return; return;
} }
@@ -247,10 +245,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
BookId = bookEntity.Id, BookId = bookEntity.Id,
MediaContributorId = contributorEntity.Id, MediaContributorId = contributorEntity.Id,
Role = role, Role = role
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
}); });
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value); domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
} }
@@ -295,9 +295,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
LibraryId = libraryId, LibraryId = libraryId,
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -337,9 +334,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
LibraryId = libraryId, LibraryId = libraryId,
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -389,9 +383,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
Rank = nextRank, Rank = nextRank,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -442,9 +433,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
Rank = nextRank, Rank = nextRank,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -484,9 +472,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
Rank = nextRank, Rank = nextRank,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -526,9 +511,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = false, IsEnabled = false,
Rank = nextRank, Rank = nextRank,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -583,9 +565,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = isEnabled, IsEnabled = isEnabled,
Rank = index + 1, Rank = index + 1,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
configuration.IsEnabled = isEnabled; configuration.IsEnabled = isEnabled;
configuration.Rank = index + 1; configuration.Rank = index + 1;
@@ -641,9 +620,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
PluginId = pluginId, PluginId = pluginId,
IsEnabled = isEnabled, IsEnabled = isEnabled,
Rank = index + 1, Rank = index + 1,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
configuration.IsEnabled = isEnabled; configuration.IsEnabled = isEnabled;
configuration.Rank = index + 1; configuration.Rank = index + 1;
@@ -697,9 +673,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
LibraryId = libraryId, LibraryId = libraryId,
PluginId = pluginId, PluginId = pluginId,
IsEnabled = isEnabled, IsEnabled = isEnabled,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
}; };
configuration.IsEnabled = isEnabled; configuration.IsEnabled = isEnabled;
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
@@ -74,10 +74,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
Author = plugin.Author, Author = plugin.Author,
Version = plugin.Version.ToString(), Version = plugin.Version.ToString(),
Description = plugin.Description, Description = plugin.Description,
LoadStatus = PluginLoadStatus.Loaded, LoadStatus = PluginLoadStatus.Loaded
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -98,10 +95,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
Version = string.Empty, Version = string.Empty,
Description = string.Empty, Description = string.Empty,
LoadStatus = PluginLoadStatus.FailedToLoad, LoadStatus = PluginLoadStatus.FailedToLoad,
LoadError = loadError.ErrorMessage, LoadError = loadError.ErrorMessage
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
@@ -191,11 +191,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Status = ScheduledJobStatus.Active, Status = ScheduledJobStatus.Active,
OwnerUserId = ownerUserId, OwnerUserId = ownerUserId,
LastStartedOnUtc = null, LastStartedOnUtc = null,
LastCompletedOnUtc = null, LastCompletedOnUtc = null
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = ownerUserId,
UpdatedOnUtc = null,
UpdatedBy = null
}; };
Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false); Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure) if (insertScheduledJobResult.IsFailure)
@@ -84,8 +84,6 @@ internal static class ThemeSynchronizer
if (!string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal)) if (!string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal))
{ {
existingTheme.Version = manifestResult.Value.Version; existingTheme.Version = manifestResult.Value.Version;
existingTheme.UpdatedOnUtc = DateTime.UtcNow;
existingTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description);
@@ -103,10 +101,7 @@ internal static class ThemeSynchronizer
Version = manifestResult.Value.Version, Version = manifestResult.Value.Version,
PreviewPath = manifestResult.Value.Preview, PreviewPath = manifestResult.Value.Preview,
InstallSource = ThemeInstallSource.Bundled, InstallSource = ThemeInstallSource.Bundled,
InstalledAtUtc = DateTime.UtcNow, InstalledAtUtc = DateTime.UtcNow
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
}; };
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
@@ -174,8 +169,6 @@ internal static class ThemeSynchronizer
// A bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later. // A bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later.
brokenTheme.IsDeleted = true; brokenTheme.IsDeleted = true;
brokenTheme.IsCurrent = null; brokenTheme.IsCurrent = null;
brokenTheme.UpdatedOnUtc = DateTime.UtcNow;
brokenTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
@@ -227,8 +220,6 @@ internal static class ThemeSynchronizer
return; return;
defaultTheme.IsCurrent = true; defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
@@ -1,6 +1,9 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.MusicLibrary; using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
@@ -8,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -227,24 +231,31 @@ public class MusicArtworkRepositoryTests : IDisposable
{ {
// Arrange // Arrange
Guid ownerId = Guid.NewGuid(); Guid ownerId = Guid.NewGuid();
DateTime before = DateTime.UtcNow; Guid actingUserId = Guid.NewGuid();
DateTime insertedOnUtc = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
// The context is built with the auditing interceptor attached, so the cover insert is stamped exactly like in production.
using LuminaDbContext auditedContext = CreateAuditedContext(anchorConnection, actingUserId, insertedOnUtc);
MusicArtworkRepository sut = new(auditedContext);
// Act // Act
Result<Updated> result = await _sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None); Result<Updated> result = await sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
await _context.SaveChangesAsync(); await auditedContext.SaveChangesAsync();
// Assert // Assert
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value); Assert.Equal(Result.Updated, result.Value);
MusicArtworkEntity cover = Assert.Single(await _context.MusicArtwork.ToListAsync()); MusicArtworkEntity cover = Assert.Single(await auditedContext.MusicArtwork.ToListAsync());
Assert.Equal(MusicArtworkOwnerType.Album, cover.OwnerType); Assert.Equal(MusicArtworkOwnerType.Album, cover.OwnerType);
Assert.Equal(ownerId, cover.OwnerId); Assert.Equal(ownerId, cover.OwnerId);
Assert.Equal(ArtworkType.Cover, cover.ArtworkType); Assert.Equal(ArtworkType.Cover, cover.ArtworkType);
Assert.Equal(0, cover.Ordinal); Assert.Equal(0, cover.Ordinal);
Assert.Equal("covers/new.jpg", cover.FileName); Assert.Equal("covers/new.jpg", cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status); Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(Guid.Empty, cover.CreatedBy); Assert.Equal(insertedOnUtc, cover.CreatedOnUtc);
Assert.True(cover.CreatedOnUtc >= before); Assert.Equal(actingUserId, cover.CreatedBy);
Assert.Null(cover.UpdatedOnUtc);
Assert.Null(cover.UpdatedBy); Assert.Null(cover.UpdatedBy);
} }
@@ -468,6 +479,27 @@ public class MusicArtworkRepositoryTests : IDisposable
return context; return context;
} }
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <param name="userId">The Id of the user reported as the current user.</param>
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
{
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
currentUserService.UserId.Returns(userId);
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow.Returns(utcNow);
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary> /// <summary>
/// Disposes the database context and its underlying connection. /// Disposes the database context and its underlying connection.
/// </summary> /// </summary>
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Favorites; using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
@@ -372,6 +373,95 @@ public class UnitOfWorkTests
} }
} }
[Fact]
public async Task SaveChangesAsInitializationAsync_WhenExplicitAuditValuesAreProvided_ShouldPreserveThemThroughTheAuditInterceptor()
{
// Arrange
Guid userId = Guid.NewGuid();
DateTime currentUtcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime initializationUtcNow = new(2025, 1, 2, 12, 0, 0, DateTimeKind.Utc);
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateAuditedSqliteContext(userId, currentUtcNow);
using (anchorConnection)
{
using (dbContext)
{
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
role.CreatedOnUtc = initializationUtcNow;
role.CreatedBy = AuditIdentities.s_systemUserId;
role.UpdatedOnUtc = null;
role.UpdatedBy = null;
dbContext.Roles.Add(role);
// Act
Result<Success> result = await sut.SaveChangesAsInitializationAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
dbContext.ChangeTracker.Clear();
RoleEntity storedRole = await dbContext.Roles.AsNoTracking().SingleAsync(candidate => candidate.Id == role.Id);
Assert.Equal(initializationUtcNow, storedRole.CreatedOnUtc);
Assert.Equal(AuditIdentities.s_systemUserId, storedRole.CreatedBy);
Assert.Null(storedRole.UpdatedOnUtc);
Assert.Null(storedRole.UpdatedBy);
Assert.False(dbContext.IsInitializationSave);
RoleEntity normalRole = _roleEntityFixture.Create(roleName: "NormalRole");
dbContext.Roles.Add(normalRole);
Result<Success> normalSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
Assert.False(normalSaveResult.IsFailure);
dbContext.ChangeTracker.Clear();
RoleEntity storedNormalRole = await dbContext.Roles.AsNoTracking().SingleAsync(candidate => candidate.Id == normalRole.Id);
Assert.Equal(currentUtcNow, storedNormalRole.CreatedOnUtc);
Assert.Equal(userId, storedNormalRole.CreatedBy);
}
}
}
[Fact]
public async Task SaveChangesAsInitializationAsync_WhenSaveFails_ShouldResetTheFlagAndStampTheNextNormalSave()
{
// Arrange
Guid userId = Guid.NewGuid();
DateTime currentUtcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateAuditedSqliteContext(userId, currentUtcNow);
using (anchorConnection)
{
using (dbContext)
{
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity firstBook = _bookEntityFixture.Create();
firstBook.LibraryId = libraryId;
firstBook.Path = "/books/duplicate.epub";
BookEntity secondBook = _bookEntityFixture.Create();
secondBook.LibraryId = libraryId;
secondBook.Path = "/books/duplicate.epub";
dbContext.Books.AddRange(firstBook, secondBook);
// Act
Result<Success> result = await sut.SaveChangesAsInitializationAsync(CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
Assert.False(dbContext.IsInitializationSave);
dbContext.ChangeTracker.Clear();
RoleEntity role = _roleEntityFixture.Create(roleName: "NormalRole");
dbContext.Roles.Add(role);
Result<Success> normalSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
Assert.False(normalSaveResult.IsFailure);
dbContext.ChangeTracker.Clear();
RoleEntity storedRole = await dbContext.Roles.AsNoTracking().SingleAsync(candidate => candidate.Id == role.Id);
Assert.Equal(currentUtcNow, storedRole.CreatedOnUtc);
Assert.Equal(userId, storedRole.CreatedBy);
}
}
}
/// <summary> /// <summary>
/// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider. /// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider.
/// </summary> /// </summary>
@@ -138,9 +138,9 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
await dbContext.SaveChangesAsync(); await dbContext.SaveChangesAsync();
// Set up admin permissions and roles. // Set up admin permissions and roles.
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRolePermissionsAsync(CancellationToken.None);
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None); await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
// Authenticate user. // Authenticate user.
@@ -1,5 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
@@ -193,22 +195,34 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanViewUsers); Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanViewUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanDeleteUsers); Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanDeleteUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanRegisterUsers); Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
Assert.All(permissions, permission => Assert.Equal(AuditIdentities.s_systemUserId, permission.CreatedBy));
// Verify default roles. // Verify default roles.
List<RoleEntity> roles = await dbContext.Roles.ToListAsync(); List<RoleEntity> roles = await dbContext.Roles.ToListAsync();
RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == "Admin"); RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == "Admin");
Assert.NotNull(adminRole); Assert.NotNull(adminRole);
Assert.Equal(AuditIdentities.s_systemUserId, adminRole!.CreatedBy);
// Verify admin role permissions. // Verify admin role permissions.
List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions
.Where(rp => rp.RoleId == adminRole!.Id) .Where(rp => rp.RoleId == adminRole.Id)
.ToListAsync(); .ToListAsync();
Assert.NotEmpty(rolePermissions); Assert.NotEmpty(rolePermissions);
Assert.Contains(rolePermissions, rp => permissions.Any(p => p.Id == rp.PermissionId)); Assert.Contains(rolePermissions, rp => permissions.Any(p => p.Id == rp.PermissionId));
Assert.All(rolePermissions, rolePermission => Assert.Equal(AuditIdentities.s_systemUserId, rolePermission.CreatedBy));
// Verify user has admin role. // Verify user has admin role.
UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == adminRole!.Id); UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == adminRole.Id);
Assert.NotNull(userRole); Assert.NotNull(userRole);
Assert.Equal(AuditIdentities.s_systemUserId, userRole!.CreatedBy);
// Verify the admin account and the default scheduled jobs were created by the initialization flow, which is anonymous.
UserEntity? adminUser = await dbContext.Users.FirstOrDefaultAsync(user => user.Id == userId);
Assert.NotNull(adminUser);
Assert.Equal(AuditIdentities.s_systemUserId, adminUser!.CreatedBy);
List<ScheduledJobEntity> scheduledJobs = await dbContext.ScheduledJobs.ToListAsync();
Assert.NotEmpty(scheduledJobs);
Assert.All(scheduledJobs, scheduledJob => Assert.Equal(AuditIdentities.s_systemUserId, scheduledJob.CreatedBy));
} }
private async Task<UserEntity> CreateTestUser() private async Task<UserEntity> CreateTestUser()
@@ -413,7 +413,7 @@ public class StartConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaAp
{ {
using IServiceScope scope = _apiFactory.Services.CreateScope(); using IServiceScope scope = _apiFactory.Services.CreateScope();
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>(); IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
await dataSeedService.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
await dataSeedService.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); await dataSeedService.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
} }
@@ -26,7 +26,7 @@ public class FavoriteMappingTests
private readonly MediaItemIdFixture _mediaItemIdFixture = new(); private readonly MediaItemIdFixture _mediaItemIdFixture = new();
[Fact] [Fact]
public void ToRepositoryEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldAndTheAuditColumns() public void ToRepositoryEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldWithoutTheAuditColumns()
{ {
// Arrange // Arrange
Guid id = Guid.NewGuid(); Guid id = Guid.NewGuid();
@@ -50,10 +50,9 @@ public class FavoriteMappingTests
Assert.Equal(userId, entity.UserId); Assert.Equal(userId, entity.UserId);
Assert.Equal(FavoriteMediaKind.Book, entity.MediaKind); Assert.Equal(FavoriteMediaKind.Book, entity.MediaKind);
Assert.Equal(mediaItemId, entity.MediaItemId); Assert.Equal(mediaItemId, entity.MediaItemId);
Assert.Equal(createdOnUtc, entity.CreatedOnUtc); Assert.Equal(default, entity.CreatedOnUtc);
Assert.Equal(Guid.Empty, entity.CreatedBy); Assert.Equal(Guid.Empty, entity.CreatedBy);
Assert.True(entity.UpdatedOnUtc.HasValue); Assert.Null(entity.UpdatedOnUtc);
Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc.Value);
Assert.Null(entity.UpdatedBy); Assert.Null(entity.UpdatedBy);
} }
@@ -86,7 +86,7 @@ public class MediaConsumptionRecordMappingTests
Assert.Equal(0.75, result.LastProgressFraction); Assert.Equal(0.75, result.LastProgressFraction);
Assert.Equal(0, result.ConsecutivePagesRead); Assert.Equal(0, result.ConsecutivePagesRead);
Assert.Equal(1L, result.Version); Assert.Equal(1L, result.Version);
Assert.Equal(startedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
@@ -75,7 +75,7 @@ public class MediaResumePointMappingTests
Assert.Equal(0.6, result.LastProgressFraction); Assert.Equal(0.6, result.LastProgressFraction);
Assert.Equal(lastConsumedOnUtc, result.LastConsumedOnUtc); Assert.Equal(lastConsumedOnUtc, result.LastConsumedOnUtc);
Assert.Equal(1L, result.Version); Assert.Equal(1L, result.Version);
Assert.Equal(createdOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
@@ -69,7 +69,7 @@ public class AlbumMappingTests
Assert.Equal(album.MusicBrainzReleaseGroupId.HasValue ? album.MusicBrainzReleaseGroupId.Value.Value : null, result.MusicBrainzReleaseGroupId); Assert.Equal(album.MusicBrainzReleaseGroupId.HasValue ? album.MusicBrainzReleaseGroupId.Value.Value : null, result.MusicBrainzReleaseGroupId);
Assert.Equal(album.MusicBrainzReleaseArtistId.HasValue ? album.MusicBrainzReleaseArtistId.Value.Value : null, result.MusicBrainzReleaseArtistId); Assert.Equal(album.MusicBrainzReleaseArtistId.HasValue ? album.MusicBrainzReleaseArtistId.Value.Value : null, result.MusicBrainzReleaseArtistId);
Assert.Equal(album.Ratings.ToRepositoryEntities(), result.Ratings); Assert.Equal(album.Ratings.ToRepositoryEntities(), result.Ratings);
Assert.Equal(album.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
@@ -95,7 +95,7 @@ public class AlbumMappingTests
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
Assert.Equal(contributor.Role, contributorEntity.Role); Assert.Equal(contributor.Role, contributorEntity.Role);
Assert.Equal(album.Id.Value, contributorEntity.AlbumId); Assert.Equal(album.Id.Value, contributorEntity.AlbumId);
Assert.Equal(album.CreatedOnUtc, contributorEntity.CreatedOnUtc); Assert.Equal(default, contributorEntity.CreatedOnUtc);
Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); Assert.Equal(Guid.Empty, contributorEntity.CreatedBy);
Assert.Null(contributorEntity.UpdatedBy); Assert.Null(contributorEntity.UpdatedBy);
} }
@@ -43,7 +43,7 @@ public class ArtistMappingTests
Assert.Equal(artist.Name, result.Name); Assert.Equal(artist.Name, result.Name);
Assert.Equal(artist.Website.Value, result.Website); Assert.Equal(artist.Website.Value, result.Website);
Assert.Equal(artist.MusicBrainzArtistId.Value.Value, result.MusicBrainzArtistId); Assert.Equal(artist.MusicBrainzArtistId.Value.Value, result.MusicBrainzArtistId);
Assert.Equal(artist.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
@@ -67,7 +67,7 @@ public class ArtistMappingTests
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
Assert.Equal(contributor.Role, contributorEntity.Role); Assert.Equal(contributor.Role, contributorEntity.Role);
Assert.Equal(artist.Id.Value, contributorEntity.ArtistId); Assert.Equal(artist.Id.Value, contributorEntity.ArtistId);
Assert.Equal(artist.CreatedOnUtc, contributorEntity.CreatedOnUtc); Assert.Equal(default, contributorEntity.CreatedOnUtc);
Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); Assert.Equal(Guid.Empty, contributorEntity.CreatedBy);
Assert.Null(contributorEntity.UpdatedBy); Assert.Null(contributorEntity.UpdatedBy);
} }
@@ -82,7 +82,7 @@ public class TrackMappingTests
Assert.Equal(track.Moods.ToRepositoryEntities(), result.Moods); Assert.Equal(track.Moods.ToRepositoryEntities(), result.Moods);
Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs); Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs);
Assert.Equal(track.Ratings.ToRepositoryEntities(), result.Ratings); Assert.Equal(track.Ratings.ToRepositoryEntities(), result.Ratings);
Assert.Equal(track.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
@@ -108,7 +108,7 @@ public class TrackMappingTests
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
Assert.Equal(contributor.Role, contributorEntity.Role); Assert.Equal(contributor.Role, contributorEntity.Role);
Assert.Equal(track.Id.Value, contributorEntity.TrackId); Assert.Equal(track.Id.Value, contributorEntity.TrackId);
Assert.Equal(track.CreatedOnUtc, contributorEntity.CreatedOnUtc); Assert.Equal(default, contributorEntity.CreatedOnUtc);
Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); Assert.Equal(Guid.Empty, contributorEntity.CreatedBy);
Assert.Null(contributorEntity.UpdatedOnUtc); Assert.Null(contributorEntity.UpdatedOnUtc);
Assert.Null(contributorEntity.UpdatedBy); Assert.Null(contributorEntity.UpdatedBy);
@@ -54,8 +54,8 @@ public class LibraryMappingTests
Assert.Equal(library.LibraryType, result.LibraryType); Assert.Equal(library.LibraryType, result.LibraryType);
Assert.Equal(library.ContentLocations.Select(l => l.Path), result.ContentLocations.Select(l => l.Path)); Assert.Equal(library.ContentLocations.Select(l => l.Path), result.ContentLocations.Select(l => l.Path));
Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage); Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage);
Assert.Equal(library.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(library.UpdatedOnUtc.HasValue ? library.UpdatedOnUtc.Value : null, result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.True(result.IsEnabled); Assert.True(result.IsEnabled);
Assert.False(result.IsLocked); Assert.False(result.IsLocked);
Assert.True(result.CanDownloadMetadataFromWeb); Assert.True(result.CanDownloadMetadataFromWeb);
@@ -68,8 +68,8 @@ public class BookMappingTests
Assert.Equal(book.AppleBooksId.HasValue ? book.AppleBooksId.Value : null, result.AppleBooksId); Assert.Equal(book.AppleBooksId.HasValue ? book.AppleBooksId.Value : null, result.AppleBooksId);
Assert.Equal(book.ISBNs.ToRepositoryEntities(), result.ISBNs); Assert.Equal(book.ISBNs.ToRepositoryEntities(), result.ISBNs);
Assert.Equal(book.Ratings.ToRepositoryEntities(), result.Ratings); Assert.Equal(book.Ratings.ToRepositoryEntities(), result.Ratings);
Assert.Equal(book.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(book.UpdatedOnUtc.HasValue ? book.UpdatedOnUtc.Value : null, result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
} }
[Fact] [Fact]
@@ -79,6 +79,8 @@ public class BookMappingTests
Book book = _bookFixture.Create(); Book book = _bookFixture.Create();
BookEntity entity = _bookEntityFixture.Create(); BookEntity entity = _bookEntityFixture.Create();
BookEntity expectedEntity = book.ToRepositoryEntity(); BookEntity expectedEntity = book.ToRepositoryEntity();
DateTime? initialUpdatedOnUtc = entity.UpdatedOnUtc;
Guid? initialUpdatedBy = entity.UpdatedBy;
// Act // Act
entity.ApplyMetadataToEntity(book); entity.ApplyMetadataToEntity(book);
@@ -113,8 +115,8 @@ public class BookMappingTests
Assert.Equal(expectedEntity.GoogleBooksId, entity.GoogleBooksId); Assert.Equal(expectedEntity.GoogleBooksId, entity.GoogleBooksId);
Assert.Equal(expectedEntity.BarnesAndNobleId, entity.BarnesAndNobleId); Assert.Equal(expectedEntity.BarnesAndNobleId, entity.BarnesAndNobleId);
Assert.Equal(expectedEntity.AppleBooksId, entity.AppleBooksId); Assert.Equal(expectedEntity.AppleBooksId, entity.AppleBooksId);
Assert.NotNull(entity.UpdatedOnUtc); Assert.Equal(initialUpdatedOnUtc, entity.UpdatedOnUtc);
Assert.NotNull(entity.UpdatedBy); Assert.Equal(initialUpdatedBy, entity.UpdatedBy);
} }
[Fact] [Fact]
@@ -25,13 +25,12 @@ public class UpdateBookCoverCommandMappingTests
public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork() public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
Guid bookId = Guid.NewGuid(); Guid bookId = Guid.NewGuid();
UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString()); UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString());
string storedCoverPath = "/media/books/cover.jpg"; string storedCoverPath = "/media/books/cover.jpg";
// Act // Act
BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath, userId); BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath);
// Assert // Assert
Assert.Equal(bookId, cover.BookId); Assert.Equal(bookId, cover.BookId);
@@ -39,8 +38,8 @@ public class UpdateBookCoverCommandMappingTests
Assert.Equal(0, cover.Ordinal); Assert.Equal(0, cover.Ordinal);
Assert.Equal(storedCoverPath, cover.FileName); Assert.Equal(storedCoverPath, cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status); Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(userId, cover.CreatedBy); Assert.Equal(Guid.Empty, cover.CreatedBy);
Assert.NotEqual(default, cover.CreatedOnUtc); Assert.Equal(default, cover.CreatedOnUtc);
Assert.Null(cover.UpdatedBy); Assert.Null(cover.UpdatedBy);
} }
@@ -48,21 +47,22 @@ public class UpdateBookCoverCommandMappingTests
public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover() public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
Guid bookId = Guid.NewGuid(); Guid bookId = Guid.NewGuid();
UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString()); UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString());
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg", status: ArtworkStatus.Pending); BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg", status: ArtworkStatus.Pending);
DateTime? initialUpdatedOnUtc = existingCover.UpdatedOnUtc;
Guid? initialUpdatedBy = existingCover.UpdatedBy;
string storedCoverPath = "/media/books/cover.jpg"; string storedCoverPath = "/media/books/cover.jpg";
// Act // Act
BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath, userId); BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath);
// Assert // Assert
Assert.Same(existingCover, cover); Assert.Same(existingCover, cover);
Assert.Equal(storedCoverPath, cover.FileName); Assert.Equal(storedCoverPath, cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status); Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(userId, cover.UpdatedBy); Assert.Equal(initialUpdatedOnUtc, cover.UpdatedOnUtc);
Assert.NotNull(cover.UpdatedOnUtc); Assert.Equal(initialUpdatedBy, cover.UpdatedBy);
Assert.NotNull(cover.LastUpdateUtc); Assert.NotNull(cover.LastUpdateUtc);
} }
} }
@@ -46,8 +46,8 @@ public class PlaylistMappingTests
Assert.Equal("Focus", result.Name); Assert.Equal("Focus", result.Name);
Assert.Equal("Deep work", result.Description); Assert.Equal("Deep work", result.Description);
Assert.Equal(PlaylistType.Music, result.Type); Assert.Equal(PlaylistType.Music, result.Type);
Assert.Equal(createdOnUtc, result.CreatedOnUtc); Assert.Equal(default, result.CreatedOnUtc);
Assert.Equal(updatedOnUtc, result.UpdatedOnUtc); Assert.Null(result.UpdatedOnUtc);
Assert.Equal(Guid.Empty, result.CreatedBy); Assert.Equal(Guid.Empty, result.CreatedBy);
Assert.Null(result.UpdatedBy); Assert.Null(result.UpdatedBy);
} }
@@ -1,13 +1,13 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.Seed;
using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Errors; using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Security;
@@ -49,6 +49,7 @@ public class SetupApplicationCommandHandlerTests
private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IValidator<SetupApplicationCommand> _mockValidator; private readonly IValidator<SetupApplicationCommand> _mockValidator;
private readonly SetupApplicationCommandHandler _sut; private readonly SetupApplicationCommandHandler _sut;
private readonly DateTime _fixedUtcNow;
private readonly UserEntityFixture _userEntityFixture = new(); private readonly UserEntityFixture _userEntityFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new();
@@ -61,7 +62,7 @@ public class SetupApplicationCommandHandlerTests
public SetupApplicationCommandHandlerTests() public SetupApplicationCommandHandlerTests()
{ {
_mockUnitOfWork = Substitute.For<IUnitOfWork>(); _mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success); _mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockHashService = Substitute.For<IPasswordHashService>(); _mockHashService = Substitute.For<IPasswordHashService>();
_mockCryptographyService = Substitute.For<ICryptographyService>(); _mockCryptographyService = Substitute.For<ICryptographyService>();
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>(); _mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
@@ -70,6 +71,7 @@ public class SetupApplicationCommandHandlerTests
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>(); _mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>(); _mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDataSeedService = Substitute.For<IDataSeedService>(); _mockDataSeedService = Substitute.For<IDataSeedService>();
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>(); _mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>(); _mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>()) _mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
@@ -77,7 +79,7 @@ public class SetupApplicationCommandHandlerTests
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()) _mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
@@ -101,18 +103,20 @@ public class SetupApplicationCommandHandlerTests
// Arrange // Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false }; SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false };
string hashedPassword = Uri.EscapeDataString("hashedPassword"); string hashedPassword = Uri.EscapeDataString("hashedPassword");
UserEntity? insertedUser = null;
_mockUserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()) _mockUserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockHashService.HashString(command.Password!) _mockHashService.HashString(command.Password!)
.Returns(hashedPassword); .Returns(hashedPassword);
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created)
.AndDoes(info => insertedUser = info.Arg<UserEntity>());
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -125,10 +129,41 @@ public class SetupApplicationCommandHandlerTests
Assert.NotNull(result.Value); Assert.NotNull(result.Value);
Assert.Equal(command.Username, result.Value.Username); Assert.Equal(command.Username, result.Value.Username);
Assert.Null(result.Value.TotpSecret); Assert.Null(result.Value.TotpSecret);
Assert.NotNull(insertedUser);
Assert.Equal(AuditIdentities.s_systemUserId, insertedUser!.CreatedBy);
Assert.Equal(_fixedUtcNow, insertedUser.CreatedOnUtc);
Assert.Null(insertedUser.UpdatedBy);
Assert.Null(insertedUser.UpdatedOnUtc);
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnErrorAndNotSeedDefaults()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false };
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
_mockUserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockHashService.HashString(command.Password!)
.Returns("hashedPassword");
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -153,11 +188,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(encryptedSecret); .Returns(encryptedSecret);
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -173,7 +208,7 @@ public class SetupApplicationCommandHandlerTests
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -195,7 +230,7 @@ public class SetupApplicationCommandHandlerTests
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -217,7 +252,7 @@ public class SetupApplicationCommandHandlerTests
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -241,7 +276,7 @@ public class SetupApplicationCommandHandlerTests
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -255,7 +290,7 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(error); .Returns(error);
// Act // Act
@@ -265,8 +300,8 @@ public class SetupApplicationCommandHandlerTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError); Assert.Equal(error, result.FirstError);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -280,9 +315,9 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(error); .Returns(error);
// Act // Act
@@ -292,9 +327,9 @@ public class SetupApplicationCommandHandlerTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError); Assert.Equal(error, result.FirstError);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -308,11 +343,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(error); .Returns(error);
// Act // Act
@@ -322,9 +357,9 @@ public class SetupApplicationCommandHandlerTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError); Assert.Equal(error, result.FirstError);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.DidNotReceive().SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
} }
@@ -339,11 +374,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error); .Returns(error);
@@ -355,9 +390,9 @@ public class SetupApplicationCommandHandlerTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError); Assert.Equal(error, result.FirstError);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.DidNotReceive().SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
} }
@@ -373,11 +408,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -405,11 +440,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -422,9 +457,9 @@ public class SetupApplicationCommandHandlerTests
Assert.NotNull(result.Value); Assert.NotNull(result.Value);
Assert.Equal(command.Username, result.Value.Username); Assert.Equal(command.Username, result.Value.Username);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
} }
@@ -442,11 +477,11 @@ public class SetupApplicationCommandHandlerTests
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -492,11 +527,11 @@ public class SetupApplicationCommandHandlerTests
.Returns("hashedPassword"); .Returns("hashedPassword");
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>()) _mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>()) _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
@@ -529,7 +529,6 @@ public class ReportConsumptionProgressCommandHandlerTests
await _mockMediaResumePointRepository.Received(1).UpsertForUserAsync( await _mockMediaResumePointRepository.Received(1).UpsertForUserAsync(
Arg.Is<MediaResumePointEntity>(resumePoint => Arg.Is<MediaResumePointEntity>(resumePoint =>
resumePoint.Id == existingResumePoint.Id && resumePoint.Id == existingResumePoint.Id &&
resumePoint.CreatedOnUtc == existingResumePoint.CreatedOnUtc &&
resumePoint.LastPositionTimeOffsetMilliseconds == 600_000 && resumePoint.LastPositionTimeOffsetMilliseconds == 600_000 &&
resumePoint.LastProgressFraction == 0.4), resumePoint.LastProgressFraction == 0.4),
_userId, _userId,
@@ -145,7 +145,6 @@ public class UpdateBookCoverCommandHandlerTests
Assert.Single(existingBook.Artwork); Assert.Single(existingBook.Artwork);
Assert.Equal(result.Value.CoverPath, existingCover.FileName); Assert.Equal(result.Value.CoverPath, existingCover.FileName);
Assert.Equal(ArtworkStatus.Enriched, existingCover.Status); Assert.Equal(ArtworkStatus.Enriched, existingCover.Status);
Assert.Equal(_userId, existingCover.UpdatedBy);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
} }
@@ -267,7 +267,7 @@ public class DeleteThemeCommandHandlerTests
// Assert // Assert
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).UpdateAsync( await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()); await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -202,9 +202,7 @@ public class InstallThemeCommandHandlerTests
theme.Version == manifest.Version && theme.Version == manifest.Version &&
theme.PreviewPath == manifest.Preview && theme.PreviewPath == manifest.Preview &&
theme.InstallSource == ThemeInstallSource.Uploaded && theme.InstallSource == ThemeInstallSource.Uploaded &&
theme.IsDeleted == false && theme.IsDeleted == false),
theme.CreatedBy == _userId &&
theme.UpdatedBy == _userId),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()); await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -268,10 +266,7 @@ public class InstallThemeCommandHandlerTests
theme.Name == manifest.Name && theme.Name == manifest.Name &&
theme.InstallSource == existingTheme.InstallSource && theme.InstallSource == existingTheme.InstallSource &&
theme.IsCurrent == existingTheme.IsCurrent && theme.IsCurrent == existingTheme.IsCurrent &&
theme.IsDeleted == false && theme.IsDeleted == false),
theme.CreatedOnUtc == existingTheme.CreatedOnUtc &&
theme.CreatedBy == existingTheme.CreatedBy &&
theme.UpdatedBy == _userId),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()); await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -235,7 +235,7 @@ public class RestoreThemeCommandHandlerTests
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>()); await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync( await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && !entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && !entity.IsDeleted && entity.IsCurrent == null),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
} }
@@ -238,7 +238,7 @@ public class SetCurrentThemeCommandHandlerTests
Arg.Is<ThemeEntity>(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null), Arg.Is<ThemeEntity>(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync( await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
} }
@@ -290,7 +290,7 @@ public class SetCurrentThemeCommandHandlerTests
Assert.Equal(theme.Id, result.Value.Id); Assert.Equal(theme.Id, result.Value.Id);
Assert.True(result.Value.IsCurrent); Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync( await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
} }
@@ -5,7 +5,6 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors; using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
@@ -33,7 +32,6 @@ public class RegisterUserCommandHandlerTests
private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly IQRCodeGenerator _mockQRCodeGenerator; private readonly IQRCodeGenerator _mockQRCodeGenerator;
private readonly IUserRepository _mockUserRepository; private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly RegisterUserCommandHandler _sut; private readonly RegisterUserCommandHandler _sut;
private readonly RegisterUserCommandFixture _registerUserCommandFixture = new(); private readonly RegisterUserCommandFixture _registerUserCommandFixture = new();
private readonly UserEntityFixture _userEntityFixture = new(); private readonly UserEntityFixture _userEntityFixture = new();
@@ -50,10 +48,8 @@ public class RegisterUserCommandHandlerTests
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>(); _mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>(); _mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
_mockUserRepository = Substitute.For<IUserRepository>(); _mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>(); IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
mockValidator.Validate(Arg.Any<RegisterUserCommand>()) mockValidator.Validate(Arg.Any<RegisterUserCommand>())
@@ -64,7 +60,6 @@ public class RegisterUserCommandHandlerTests
_mockCryptographyService, _mockCryptographyService,
_mockTotpTokenGenerator, _mockTotpTokenGenerator,
_mockQRCodeGenerator, _mockQRCodeGenerator,
_mockDateTimeProvider,
mockValidator); mockValidator);
} }
@@ -1,4 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
@@ -83,7 +84,7 @@ public class UpdateAuditableEntitiesInterceptorTests
} }
[Fact] [Fact]
public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldUseGuidEmptyForCreationAndSystemUserForModification() public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldLeaveCreationAndModificationUnattributed()
{ {
// Arrange // Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null); _mockCurrentUserService.UserId.Returns((Guid?)null);
@@ -98,10 +99,35 @@ public class UpdateAuditableEntitiesInterceptorTests
// Assert // Assert
Assert.Equal(Guid.Empty, book.CreatedBy); Assert.Equal(Guid.Empty, book.CreatedBy);
Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), book.UpdatedBy); Assert.Equal(Guid.Empty, book.UpdatedBy);
Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc); Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc);
} }
[Fact]
public async Task SavingChangesAsync_WhenInitializationSave_ShouldPreserveTheExplicitAuditValues()
{
// Arrange
LuminaDbContext context = CreateContext();
BookEntity book = _bookEntityFixture.Create();
DateTime initializationUtcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
book.CreatedOnUtc = initializationUtcNow;
book.CreatedBy = AuditIdentities.s_systemUserId;
book.UpdatedOnUtc = null;
book.UpdatedBy = null;
// Act
context.IsInitializationSave = true;
context.Books.Add(book);
await context.SaveChangesAsync();
context.IsInitializationSave = false;
// Assert
Assert.Equal(initializationUtcNow, book.CreatedOnUtc);
Assert.Equal(AuditIdentities.s_systemUserId, book.CreatedBy);
Assert.Null(book.UpdatedOnUtc);
Assert.Null(book.UpdatedBy);
}
[Fact] [Fact]
public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties() public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties()
{ {
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization;
@@ -49,10 +50,10 @@ public class DataSeedServiceTests
public DataSeedServiceTests() public DataSeedServiceTests()
{ {
_mockUnitOfWork = Substitute.For<IUnitOfWork>(); _mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success); _mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>(); _mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockPermissionRepository = Substitute.For<IPermissionRepository>(); _mockPermissionRepository = Substitute.For<IPermissionRepository>();
_fixedUtcNow = DateTime.UtcNow; _fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository); _mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
@@ -64,13 +65,12 @@ public class DataSeedServiceTests
public async Task SetDefaultAuthorizationPermissionsAsync_WhenSuccessful_ShouldInsertAllPermissionsAndReturnCreated() public async Task SetDefaultAuthorizationPermissionsAsync_WhenSuccessful_ShouldInsertAllPermissionsAndReturnCreated()
{ {
// Arrange // Arrange
Guid adminId = Guid.NewGuid();
_mockPermissionRepository _mockPermissionRepository
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>()) .InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created); .Returns(Result.Created);
// Act // Act
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
@@ -80,38 +80,36 @@ public class DataSeedServiceTests
.Received(4) .Received(4)
.InsertAsync( .InsertAsync(
Arg.Is<PermissionEntity>(p => Arg.Is<PermissionEntity>(p =>
p.CreatedBy == adminId && p.CreatedBy == AuditIdentities.s_systemUserId &&
p.CreatedOnUtc == _fixedUtcNow), p.CreatedOnUtc == _fixedUtcNow),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetDefaultAuthorizationPermissionsAsync_WhenInsertFails_ShouldReturnError() public async Task SetDefaultAuthorizationPermissionsAsync_WhenInsertFails_ShouldReturnError()
{ {
// Arrange // Arrange
Guid adminId = Guid.NewGuid();
Error expectedError = Error.Conflict("Permission.Conflict", "Permission already exists"); Error expectedError = Error.Conflict("Permission.Conflict", "Permission already exists");
_mockPermissionRepository _mockPermissionRepository
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>()) .InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
.Returns(expectedError); .Returns(expectedError);
// Act // Act
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetDefaultAuthorizationPermissionsAsync_ShouldCreateAllDefaultPermissions() public async Task SetDefaultAuthorizationPermissionsAsync_ShouldCreateAllDefaultPermissions()
{ {
// Arrange // Arrange
Guid adminId = Guid.NewGuid();
List<AuthorizationPermission> capturedPermissions = []; List<AuthorizationPermission> capturedPermissions = [];
_mockPermissionRepository _mockPermissionRepository
@@ -120,7 +118,7 @@ public class DataSeedServiceTests
.AndDoes(info => capturedPermissions.Add(info.Arg<PermissionEntity>().PermissionName)); .AndDoes(info => capturedPermissions.Add(info.Arg<PermissionEntity>().PermissionName));
// Act // Act
await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None); await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.Equal(new[] Assert.Equal(new[]
@@ -136,7 +134,6 @@ public class DataSeedServiceTests
public async Task SetDefaultAuthorizationRolesAsync_WhenSuccessful_ShouldInsertAllRolesAndReturnCreated() public async Task SetDefaultAuthorizationRolesAsync_WhenSuccessful_ShouldInsertAllRolesAndReturnCreated()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository mockRoleRepository
@@ -144,7 +141,7 @@ public class DataSeedServiceTests
.Returns(Result.Created); .Returns(Result.Created);
// Act // Act
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
// Assert // Assert
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
@@ -154,19 +151,18 @@ public class DataSeedServiceTests
.Received(1) .Received(1)
.InsertAsync( .InsertAsync(
Arg.Is<RoleEntity>(r => Arg.Is<RoleEntity>(r =>
r.CreatedBy == userId && r.CreatedBy == AuditIdentities.s_systemUserId &&
r.CreatedOnUtc == _fixedUtcNow && r.CreatedOnUtc == _fixedUtcNow &&
r.RoleName == "Admin"), r.RoleName == "Admin"),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetDefaultAuthorizationRolesAsync_WhenInsertFails_ShouldReturnError() public async Task SetDefaultAuthorizationRolesAsync_WhenInsertFails_ShouldReturnError()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
@@ -176,20 +172,19 @@ public class DataSeedServiceTests
.Returns(expectedError); .Returns(expectedError);
// Act // Act
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldCreateDefaultAdminRole() public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldCreateDefaultAdminRole()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
List<string> capturedRoleNames = []; List<string> capturedRoleNames = [];
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
@@ -201,17 +196,16 @@ public class DataSeedServiceTests
.AndDoes(info => capturedRoleNames.Add(info.Arg<RoleEntity>().RoleName)); .AndDoes(info => capturedRoleNames.Add(info.Arg<RoleEntity>().RoleName));
// Act // Act
await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
// Assert // Assert
Assert.Equal(new[] { "Admin" }, capturedRoleNames); Assert.Equal(new[] { "Admin" }, capturedRoleNames);
} }
[Fact] [Fact]
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldSetCorrectAuditProperties() public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldSetTheSystemAuditProperties()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
RoleEntity? capturedRole = null; RoleEntity? capturedRole = null;
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
@@ -223,11 +217,11 @@ public class DataSeedServiceTests
.AndDoes(info => capturedRole = info.Arg<RoleEntity>()); .AndDoes(info => capturedRole = info.Arg<RoleEntity>());
// Act // Act
await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None); await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
// Assert // Assert
Assert.NotNull(capturedRole); Assert.NotNull(capturedRole);
Assert.Equal(userId, capturedRole!.CreatedBy); Assert.Equal(AuditIdentities.s_systemUserId, capturedRole!.CreatedBy);
Assert.Equal(_fixedUtcNow, capturedRole.CreatedOnUtc); Assert.Equal(_fixedUtcNow, capturedRole.CreatedOnUtc);
Assert.Null(capturedRole.UpdatedBy); Assert.Null(capturedRole.UpdatedBy);
Assert.Null(capturedRole.UpdatedOnUtc); Assert.Null(capturedRole.UpdatedOnUtc);
@@ -237,7 +231,6 @@ public class DataSeedServiceTests
public async Task SetAdminRolePermissionsAsync_WhenSuccessful_ShouldAssignAllPermissionsToAdminRole() public async Task SetAdminRolePermissionsAsync_WhenSuccessful_ShouldAssignAllPermissionsToAdminRole()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
List<PermissionEntity> permissions = List<PermissionEntity> permissions =
[ [
@@ -267,7 +260,7 @@ public class DataSeedServiceTests
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created); mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act // Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.False(result.IsFailure); Assert.False(result.IsFailure);
@@ -278,18 +271,17 @@ public class DataSeedServiceTests
.InsertAsync( .InsertAsync(
Arg.Is<RolePermissionEntity>(rp => Arg.Is<RolePermissionEntity>(rp =>
rp.RoleId == adminRole.Id && rp.RoleId == adminRole.Id &&
rp.CreatedBy == userId && rp.CreatedBy == AuditIdentities.s_systemUserId &&
rp.CreatedOnUtc == _fixedUtcNow), rp.CreatedOnUtc == _fixedUtcNow),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetAdminRolePermissionsAsync_WhenAdminRoleNotFound_ShouldReturnError() public async Task SetAdminRolePermissionsAsync_WhenAdminRoleNotFound_ShouldReturnError()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
@@ -298,19 +290,18 @@ public class DataSeedServiceTests
.Returns((RoleEntity?)null); .Returns((RoleEntity?)null);
// Act // Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError); Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetAdminRolePermissionsAsync_WhenGetPermissionsFails_ShouldReturnError() public async Task SetAdminRolePermissionsAsync_WhenGetPermissionsFails_ShouldReturnError()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
Error expectedError = Error.Failure("Permissions.NotFound", "Failed to retrieve permissions"); Error expectedError = Error.Failure("Permissions.NotFound", "Failed to retrieve permissions");
@@ -324,20 +315,19 @@ public class DataSeedServiceTests
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(expectedError); mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(expectedError);
// Act // Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetAdminRolePermissionsAsync_WhenInsertRolePermissionFails_ShouldReturnError() public async Task SetAdminRolePermissionsAsync_WhenInsertRolePermissionFails_ShouldReturnError()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)]; List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)];
Error expectedError = Error.Failure("RolePermission.InsertFailed", "Failed to insert role permission"); Error expectedError = Error.Failure("RolePermission.InsertFailed", "Failed to insert role permission");
@@ -363,20 +353,19 @@ public class DataSeedServiceTests
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(expectedError); mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(expectedError);
// Act // Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
public async Task SetAdminRolePermissionsAsync_WhenGetAdminRoleFails_ShouldReturnError() public async Task SetAdminRolePermissionsAsync_WhenGetAdminRoleFails_ShouldReturnError()
{ {
// Arrange // Arrange
Guid userId = Guid.NewGuid();
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role"); Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>(); IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
@@ -387,13 +376,13 @@ public class DataSeedServiceTests
.Returns(expectedError); .Returns(expectedError);
// Act // Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -431,11 +420,11 @@ public class DataSeedServiceTests
Arg.Is<UserRoleEntity>(ur => Arg.Is<UserRoleEntity>(ur =>
ur.UserId == userId && ur.UserId == userId &&
ur.RoleId == adminRole.Id && ur.RoleId == adminRole.Id &&
ur.CreatedBy == userId && ur.CreatedBy == AuditIdentities.s_systemUserId &&
ur.CreatedOnUtc == _fixedUtcNow), ur.CreatedOnUtc == _fixedUtcNow),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -456,7 +445,7 @@ public class DataSeedServiceTests
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.AdminRoleNotFound, result.FirstError); Assert.Equal(Errors.Authorization.AdminRoleNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -482,7 +471,7 @@ public class DataSeedServiceTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError); Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -514,7 +503,7 @@ public class DataSeedServiceTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -538,7 +527,7 @@ public class DataSeedServiceTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -565,7 +554,7 @@ public class DataSeedServiceTests
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
} }
[Fact] [Fact]
@@ -589,7 +578,7 @@ public class DataSeedServiceTests
Assert.Equal(6, capturedScheduledJobs.Count); Assert.Equal(6, capturedScheduledJobs.Count);
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status));
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId));
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.CreatedBy)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(AuditIdentities.s_systemUserId, scheduledJob.CreatedBy));
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc));
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0);
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
@@ -599,7 +588,7 @@ public class DataSeedServiceTests
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()); await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
await mockScheduledJobRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()); await mockScheduledJobRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
} }
@@ -620,6 +609,135 @@ public class DataSeedServiceTests
// Assert // Assert
Assert.True(result.IsFailure); Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError); Assert.Equal(expectedError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetDefaultAuthorizationPermissionsAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
_mockPermissionRepository
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockUnitOfWork
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
[Fact]
public async Task SetDefaultAuthorizationRolesAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockUnitOfWork
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
[Fact]
public async Task SetAdminRolePermissionsAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)];
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockPermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(new PaginatedResultDto<PermissionEntity>
{
Data = permissions,
CurrentPage = 1,
PerPage = permissions.Count,
Count = permissions.Count,
NumberOfPages = 1
});
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockUnitOfWork
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
[Fact]
public async Task SetAdminRoleToAdministratorAccount_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
UserEntity adminUser = _userEntityFixture.Create();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockUserRepository.GetByIdAsync(adminUser.Id, cancellationToken: Arg.Any<CancellationToken>()).Returns(adminUser);
mockUserRoleRepository.InsertAsync(Arg.Any<UserRoleEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockUnitOfWork
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetAdminRoleToAdministratorAccount(adminUser.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
Error expectedError = Error.Failure("Persistence.SaveFailed", "The changes could not be saved.");
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
mockScheduledJobRepository
.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockUnitOfWork
.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
} }
} }
@@ -113,6 +113,45 @@ public class UnitOfWorkTests
await dbContext.Received(1).SaveChangesAsync(cancellationToken); await dbContext.Received(1).SaveChangesAsync(cancellationToken);
} }
[Fact]
public async Task SaveChangesAsInitializationAsync_WhenCalled_ShouldResetTheFlagAfterTheSave()
{
// Arrange
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
LuminaDbContext dbContext = new(options);
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
dbContext.Roles.Add(_roleEntityFixture.Create(roleName: "TestRole"));
// Act
Result<Success> result = await unitOfWork.SaveChangesAsInitializationAsync(CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(Result.Success, result.Value);
Assert.False(dbContext.IsInitializationSave);
}
[Fact]
public async Task SaveChangesAsInitializationAsync_WhenSaveIsCancelled_ShouldResetTheFlag()
{
// Arrange
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
LuminaDbContext dbContext = new(options);
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
dbContext.Roles.Add(_roleEntityFixture.Create(roleName: "TestRole"));
CancellationToken cancellationToken = new(canceled: true);
// Act
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => unitOfWork.SaveChangesAsInitializationAsync(cancellationToken));
// Assert
Assert.False(dbContext.IsInitializationSave);
}
[Fact] [Fact]
public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities() public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities()
{ {
@@ -461,8 +461,7 @@ public class ScheduledJobSchedulerJobTests
scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup &&
scheduledJob.ScheduleType == ScheduleType.OnceAtStartup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup &&
scheduledJob.Status == ScheduledJobStatus.Active && scheduledJob.Status == ScheduledJobStatus.Active &&
scheduledJob.OwnerUserId == ownerUserId && scheduledJob.OwnerUserId == ownerUserId),
scheduledJob.CreatedBy == ownerUserId),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
} }
@@ -443,7 +443,7 @@ public class ThemeSynchronizerTests : IDisposable
} }
[Fact] [Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersionTimestampAndUpdater() public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersion()
{ {
// Arrange // Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0"); ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0");
@@ -458,6 +458,8 @@ public class ThemeSynchronizerTests : IDisposable
updatedOnUtc: DateTime.UtcNow.AddDays(-1), updatedOnUtc: DateTime.UtcNow.AddDays(-1),
includeUpdatedBy: true, includeUpdatedBy: true,
updatedBy: Guid.NewGuid()); updatedBy: Guid.NewGuid());
DateTime? initialUpdatedOnUtc = installedTheme.UpdatedOnUtc;
Guid? initialUpdatedBy = installedTheme.UpdatedBy;
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile(); string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
@@ -470,8 +472,8 @@ public class ThemeSynchronizerTests : IDisposable
// Assert // Assert
Assert.Equal("3.0.0", installedTheme.Version); Assert.Equal("3.0.0", installedTheme.Version);
Assert.NotNull(installedTheme.UpdatedOnUtc); Assert.Equal(initialUpdatedOnUtc, installedTheme.UpdatedOnUtc);
Assert.Null(installedTheme.UpdatedBy); Assert.Equal(initialUpdatedBy, installedTheme.UpdatedBy);
await _mockThemeRepository.Received(1).UpdateAsync( await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"), Arg.Is<ThemeEntity>(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());