mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
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:
1 parent
b56fabf5df
commit
7253f1507c
98 files changed
+731
-516
No files matched your search
+8
@@ -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.
|
||||
|
||||
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.
|
||||
+4
@@ -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.
|
||||
|
||||
**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>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -55,5 +55,5 @@ public class FavoriteEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -99,12 +99,12 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -114,5 +114,5 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -73,12 +73,12 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -88,5 +88,5 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -46,12 +46,12 @@ public class MediaContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -61,5 +61,5 @@ public class MediaContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+2
-2
@@ -37,12 +37,12 @@ public class AlbumContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
|
||||
+3
-3
@@ -245,12 +245,12 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -260,5 +260,5 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+2
-2
@@ -37,12 +37,12 @@ public class ArtistContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
|
||||
+3
-3
@@ -164,12 +164,12 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -179,5 +179,5 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -72,12 +72,12 @@ public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -87,5 +87,5 @@ public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+2
-2
@@ -37,12 +37,12 @@ public class TrackContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
|
||||
+3
-3
@@ -305,12 +305,12 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -320,5 +320,5 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -121,12 +121,12 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -136,5 +136,5 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -53,12 +53,12 @@ public class LibraryScanEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -68,5 +68,5 @@ public class LibraryScanEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -50,12 +50,12 @@ public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -65,5 +65,5 @@ public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -65,12 +65,12 @@ public class BookArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -80,5 +80,5 @@ public class BookArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+2
-2
@@ -37,12 +37,12 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
|
||||
+3
-3
@@ -241,12 +241,12 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -256,5 +256,5 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -61,12 +61,12 @@ public class PlaylistEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -76,5 +76,5 @@ public class PlaylistEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -40,12 +40,12 @@ public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAudita
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -55,5 +55,5 @@ public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAudita
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -35,12 +35,12 @@ public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEn
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -50,5 +50,5 @@ public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEn
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -40,12 +40,12 @@ public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAudit
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -55,5 +55,5 @@ public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAudit
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -56,12 +56,12 @@ public class PluginEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -71,5 +71,5 @@ public class PluginEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -71,12 +71,12 @@ public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -86,5 +86,5 @@ public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -56,12 +56,12 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -71,5 +71,5 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+3
-3
@@ -41,12 +41,12 @@ public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntit
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -56,5 +56,5 @@ public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntit
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -71,12 +71,12 @@ public class ThemeEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
@@ -86,5 +86,5 @@ public class ThemeEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -15,26 +15,23 @@ public interface IDataSeedService
|
||||
/// <summary>
|
||||
/// Sets up default authorization permissions in the system.
|
||||
/// </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>
|
||||
/// <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>
|
||||
/// Sets up default authorization roles in the system.
|
||||
/// </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>
|
||||
/// <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>
|
||||
/// Assigns admin role permissions to the admin user.
|
||||
/// </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>
|
||||
/// <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>
|
||||
/// 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>
|
||||
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>
|
||||
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
@@ -23,11 +22,7 @@ public static class FavoriteMapping
|
||||
Id = domainEntity.Id.Value,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
MediaKind = domainEntity.MediaKind,
|
||||
MediaItemId = domainEntity.MediaItemId.Value,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = null
|
||||
MediaItemId = domainEntity.MediaItemId.Value
|
||||
};
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -44,12 +44,7 @@ public static class MediaConsumptionRecordMapping
|
||||
: null,
|
||||
LastProgressFraction = domainEntity.LastProgressFraction,
|
||||
ConsecutivePagesRead = domainEntity.ConsecutivePagesRead,
|
||||
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
|
||||
Version = 1
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -37,12 +37,7 @@ public static class MediaResumePointMapping
|
||||
: null,
|
||||
LastProgressFraction = domainEntity.LastProgressFraction,
|
||||
LastConsumedOnUtc = domainEntity.LastConsumedOnUtc,
|
||||
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
|
||||
Version = 1
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+2
-10
@@ -69,18 +69,10 @@ public static class AlbumMapping
|
||||
Id = Guid.CreateVersion7(),
|
||||
AlbumId = domainEntity.Id.Value,
|
||||
MediaContributorId = contributor.ContributorId.Value,
|
||||
Role = contributor.Role,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
Role = contributor.Role
|
||||
})],
|
||||
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
|
||||
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
|
||||
Tracks = [.. domainEntity.Tracks.Select(track => track.ToRepositoryEntity(domainEntity.Id.Value, libraryId))]
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-10
@@ -51,17 +51,9 @@ public static class ArtistMapping
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArtistId = domainEntity.Id.Value,
|
||||
MediaContributorId = contributor.ContributorId.Value,
|
||||
Role = contributor.Role,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
Role = contributor.Role
|
||||
})],
|
||||
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
|
||||
Albums = [.. domainEntity.Albums.Select(album => album.ToRepositoryEntity(domainEntity.Id.Value, domainEntity.LibraryId.Value))]
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-10
@@ -75,10 +75,7 @@ public static class TrackMapping
|
||||
Id = Guid.CreateVersion7(),
|
||||
TrackId = domainEntity.Id.Value,
|
||||
MediaContributorId = contributor.ContributorId.Value,
|
||||
Role = contributor.Role,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
Role = contributor.Role
|
||||
})],
|
||||
Moods = [.. domainEntity.Moods.ToRepositoryEntities()],
|
||||
Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()],
|
||||
@@ -88,12 +85,7 @@ public static class TrackMapping
|
||||
WorkIswcs = domainEntity.Work.HasValue
|
||||
? [.. domainEntity.Work.Value.Iswcs.Select(iswc => new TrackWorkIswcEntity(iswc))]
|
||||
: [],
|
||||
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
|
||||
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()]
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
@@ -51,16 +50,8 @@ public static class LibraryMapping
|
||||
UserId = domainEntity.UserId.Value, // Rest of properties will be populated by EF Core.
|
||||
Status = default,
|
||||
User = 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
|
||||
Library = null!
|
||||
})]
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
@@ -25,11 +24,7 @@ public static class LibraryScanMapping
|
||||
LibraryId = domainEntity.LibraryId.Value,
|
||||
Status = domainEntity.Status,
|
||||
User = null!,
|
||||
Library = null!,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = Guid.Empty
|
||||
Library = null!
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-12
@@ -63,17 +63,9 @@ public static class BookMapping
|
||||
Id = Guid.CreateVersion7(),
|
||||
BookId = domainEntity.Id.Value,
|
||||
MediaContributorId = contributor.ContributorId.Value,
|
||||
Role = contributor.Role,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
Role = contributor.Role
|
||||
})],
|
||||
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,
|
||||
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()]
|
||||
};
|
||||
}
|
||||
|
||||
@@ -114,7 +106,5 @@ public static class BookMapping
|
||||
entity.GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null;
|
||||
entity.BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null;
|
||||
entity.AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null;
|
||||
entity.UpdatedOnUtc = DateTime.UtcNow;
|
||||
entity.UpdatedBy = Guid.CreateVersion7();
|
||||
}
|
||||
}
|
||||
+2
-8
@@ -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="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="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>
|
||||
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)
|
||||
{
|
||||
@@ -34,18 +33,13 @@ public static class UpdateBookCoverCommandMapping
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = storedCoverPath,
|
||||
Status = ArtworkStatus.Enriched,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
UpdatedBy = null
|
||||
Status = ArtworkStatus.Enriched
|
||||
};
|
||||
}
|
||||
|
||||
existingCover.FileName = storedCoverPath;
|
||||
existingCover.Status = ArtworkStatus.Enriched;
|
||||
existingCover.LastUpdateUtc = DateTime.UtcNow;
|
||||
existingCover.UpdatedOnUtc = DateTime.UtcNow;
|
||||
existingCover.UpdatedBy = userId;
|
||||
return existingCover;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
@@ -30,11 +29,7 @@ public static class PlaylistMapping
|
||||
.OrderBy(entry => entry.Position)
|
||||
.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.
|
||||
EntryCount = domainEntity.Entries.Count,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = null
|
||||
EntryCount = domainEntity.Entries.Count
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -99,11 +99,7 @@ public static class ScheduledJobEntityMapping
|
||||
Status = status,
|
||||
OwnerUserId = repositoryEntity.OwnerUserId,
|
||||
LastStartedOnUtc = lastStartedOnUtc,
|
||||
LastCompletedOnUtc = lastCompletedOnUtc,
|
||||
CreatedOnUtc = repositoryEntity.CreatedOnUtc,
|
||||
CreatedBy = repositoryEntity.CreatedBy,
|
||||
UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
|
||||
UpdatedBy = repositoryEntity.UpdatedBy
|
||||
LastCompletedOnUtc = lastCompletedOnUtc
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-5
@@ -44,11 +44,7 @@ public static class ScheduledJobExecutionEntityMapping
|
||||
IsCycleRun = repositoryEntity.IsCycleRun,
|
||||
WasCycleActive = repositoryEntity.WasCycleActive,
|
||||
StartedOnUtc = repositoryEntity.StartedOnUtc,
|
||||
CompletedOnUtc = completedOnUtc,
|
||||
CreatedOnUtc = repositoryEntity.CreatedOnUtc,
|
||||
CreatedBy = repositoryEntity.CreatedBy,
|
||||
UpdatedOnUtc = repositoryEntity.UpdatedOnUtc,
|
||||
UpdatedBy = repositoryEntity.UpdatedBy
|
||||
CompletedOnUtc = completedOnUtc
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
@@ -32,11 +31,7 @@ public static class ScheduledJobMapping
|
||||
Status = domainEntity.Status,
|
||||
OwnerUserId = domainEntity.OwnerUserId.Value,
|
||||
LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.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
|
||||
LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+6
-5
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
@@ -107,7 +108,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = id,
|
||||
CreatedBy = AuditIdentities.s_systemUserId,
|
||||
LibraryScans = [],
|
||||
};
|
||||
// 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);
|
||||
if (insertUserResult.IsFailure)
|
||||
return insertUserResult.Errors;
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
// 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)
|
||||
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)
|
||||
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)
|
||||
return setRolePermissionResult.Errors;
|
||||
|
||||
|
||||
+1
-1
@@ -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.
|
||||
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)
|
||||
existingBook.Artwork.Add(coverArtwork);
|
||||
|
||||
|
||||
+1
-5
@@ -71,11 +71,7 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler<U
|
||||
UserId = userId,
|
||||
JobTypeFilter = command.JobTypeFilter,
|
||||
DisplayTimeSpan = command.DisplayTimeSpan,
|
||||
DisplayTimeUnit = command.DisplayTimeUnit,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
DisplayTimeUnit = command.DisplayTimeUnit
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
|
||||
+1
-5
@@ -72,11 +72,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle
|
||||
IsCycleRun = domainEvent.IsCycleRun,
|
||||
WasCycleActive = wasCycleActive,
|
||||
StartedOnUtc = domainEvent.StartedOnUtc,
|
||||
CompletedOnUtc = null,
|
||||
CreatedOnUtc = scheduledJob.CreatedOnUtc,
|
||||
CreatedBy = scheduledJob.CreatedBy,
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
CompletedOnUtc = null
|
||||
};
|
||||
Result<Created> insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false);
|
||||
if (insertExecutionResult.IsFailure)
|
||||
|
||||
-2
@@ -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.
|
||||
theme.IsDeleted = true;
|
||||
theme.IsCurrent = null;
|
||||
theme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
theme.UpdatedBy = userId;
|
||||
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
|
||||
+2
-9
@@ -103,11 +103,7 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
|
||||
IsCurrent = existingTheme.IsCurrent,
|
||||
// Reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again.
|
||||
IsDeleted = false,
|
||||
InstalledAtUtc = DateTime.UtcNow,
|
||||
CreatedOnUtc = existingTheme.CreatedOnUtc,
|
||||
CreatedBy = existingTheme.CreatedBy,
|
||||
UpdatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = userId
|
||||
InstalledAtUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(themeEntity, cancellationToken).ConfigureAwait(false);
|
||||
@@ -126,10 +122,7 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
|
||||
Version = manifest.Version,
|
||||
PreviewPath = manifest.Preview,
|
||||
InstallSource = ThemeInstallSource.Uploaded,
|
||||
InstalledAtUtc = DateTime.UtcNow,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
UpdatedBy = userId
|
||||
InstalledAtUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
-2
@@ -93,8 +93,6 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
|
||||
|
||||
theme.IsDeleted = false;
|
||||
theme.IsCurrent = null;
|
||||
theme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
theme.UpdatedBy = userId;
|
||||
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
-2
@@ -96,8 +96,6 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
|
||||
|
||||
// Activate the requested theme and persist its update.
|
||||
theme.IsCurrent = true;
|
||||
theme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
theme.UpdatedBy = userId;
|
||||
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
-7
@@ -7,7 +7,6 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using System;
|
||||
@@ -28,7 +27,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly ITotpTokenGenerator _totpTokenGenerator;
|
||||
private readonly IQRCodeGenerator _qRCodeGenerator;
|
||||
private readonly IDateTimeProvider _dateTimeProvider;
|
||||
private readonly IValidator<RegisterUserCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
@@ -39,7 +37,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
/// <param name="cryptographyService">Injected service for cryptographic functionality.</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="dateTimeProvider">Injected service for time related concerns.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public RegisterUserCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
@@ -47,7 +44,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
ICryptographyService cryptographyService,
|
||||
ITotpTokenGenerator totpTokenGenerator,
|
||||
IQRCodeGenerator qRCodeGenerator,
|
||||
IDateTimeProvider dateTimeProvider,
|
||||
IValidator<RegisterUserCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
@@ -55,7 +51,6 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
_cryptographyService = cryptographyService;
|
||||
_totpTokenGenerator = totpTokenGenerator;
|
||||
_qRCodeGenerator = qRCodeGenerator;
|
||||
_dateTimeProvider = dateTimeProvider;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
@@ -88,11 +83,9 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
Id = id,
|
||||
Username = command.Username!,
|
||||
Password = Uri.EscapeDataString(_hashService.HashString(command.Password!)),
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = id,
|
||||
LibraryScans = [],
|
||||
};
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
@@ -64,6 +65,9 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
{
|
||||
if (context is null)
|
||||
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;
|
||||
DateTime utcNow = _dateTimeProvider.UtcNow;
|
||||
@@ -106,6 +110,6 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
|
||||
// Set modification properties.
|
||||
entry.Entity.UpdatedOnUtc = utcNow;
|
||||
entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id.
|
||||
entry.Entity.UpdatedBy = userId ?? default;
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -89,10 +89,7 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
DisplayName = displayName,
|
||||
LegalName = legalName,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
LegalName = legalName
|
||||
};
|
||||
_luminaDbContext.MediaContributors.Add(contributor);
|
||||
return contributor;
|
||||
|
||||
@@ -173,12 +173,7 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = fileName,
|
||||
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
|
||||
Status = ArtworkStatus.Enriched
|
||||
});
|
||||
}
|
||||
else
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Seed;
|
||||
@@ -41,18 +42,17 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Sets up default authorization permissions in the system.
|
||||
/// </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>
|
||||
/// <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.
|
||||
PermissionEntity[] defaultPermissions =
|
||||
[
|
||||
new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }
|
||||
new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId }
|
||||
];
|
||||
foreach (PermissionEntity permission in defaultPermissions)
|
||||
{
|
||||
@@ -60,7 +60,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertPermissionResult.IsFailure)
|
||||
return insertPermissionResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -69,15 +69,14 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Sets up default authorization roles in the system.
|
||||
/// </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>
|
||||
/// <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.
|
||||
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)
|
||||
{
|
||||
@@ -85,7 +84,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertRoleResult.IsFailure)
|
||||
return insertRoleResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -94,10 +93,9 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Assigns admin role permissions to the admin user.
|
||||
/// </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>
|
||||
/// <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.
|
||||
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
|
||||
@@ -121,14 +119,14 @@ public class DataSeedService : IDataSeedService
|
||||
PermissionId = permission.Id,
|
||||
Role = getAdminRoleResult.Value,
|
||||
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);
|
||||
if (insertRolePermissionResult.IsFailure)
|
||||
return insertRolePermissionResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -161,18 +159,18 @@ public class DataSeedService : IDataSeedService
|
||||
// Add the admin role to the admin user.
|
||||
UserRoleEntity userRole = new()
|
||||
{
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Role = getAdminRoleResult.Value,
|
||||
RoleId = getAdminRoleResult.Value.Id,
|
||||
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);
|
||||
if (insertUserRoleResult.IsFailure)
|
||||
return insertUserRoleResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -208,7 +206,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertScheduledJobResult.IsFailure)
|
||||
return insertScheduledJobResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -241,9 +239,7 @@ public class DataSeedService : IDataSeedService
|
||||
LastStartedOnUtc = null,
|
||||
LastCompletedOnUtc = null,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
CreatedBy = adminUserId,
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
CreatedBy = AuditIdentities.s_systemUserId
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,12 @@ public class LuminaDbContext : DbContext
|
||||
/// </summary>
|
||||
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>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -467,6 +467,35 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
/// <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>> 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
|
||||
{
|
||||
|
||||
+1
-4
@@ -647,10 +647,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
ContentHash = contentHash,
|
||||
Status = status,
|
||||
Provider = provider,
|
||||
LastUpdateUtc = DateTime.UtcNow,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
LastUpdateUtc = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+3
-12
@@ -261,10 +261,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
|
||||
LibraryId = libraryId,
|
||||
Name = name,
|
||||
MusicBrainzArtistId = musicBrainzArtistId,
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
MetadataStatus = MetadataStatus.Pending
|
||||
};
|
||||
}
|
||||
|
||||
@@ -293,10 +290,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
|
||||
MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId,
|
||||
ReleaseTypes = firstStagedItem.ReleaseType is null ? [] : [new AlbumReleaseTypeEntity(firstStagedItem.ReleaseType.Value)],
|
||||
OriginalReleaseYear = firstStagedItem.ReleaseYear,
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
MetadataStatus = MetadataStatus.Pending
|
||||
};
|
||||
}
|
||||
|
||||
@@ -335,10 +329,7 @@ internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanI
|
||||
MusicBrainzTrackId = stagedItem.MusicBrainzTrackId,
|
||||
MusicBrainzWorkId = stagedItem.MusicBrainzWorkId,
|
||||
WorkTitle = stagedItem.WorkTitle,
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
MetadataStatus = MetadataStatus.Pending
|
||||
};
|
||||
}
|
||||
}
|
||||
-2
@@ -146,8 +146,6 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
library.PathTemplateFingerprint = pathTemplateFingerprint;
|
||||
library.UpdatedOnUtc = DateTime.UtcNow;
|
||||
library.UpdatedBy = Guid.CreateVersion7();
|
||||
|
||||
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
|
||||
+1
-12
@@ -209,8 +209,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
else
|
||||
{
|
||||
coverArtwork.Status = ArtworkStatus.Failed;
|
||||
coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
|
||||
coverArtwork.UpdatedBy = Guid.CreateVersion7();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -239,8 +237,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
else
|
||||
{
|
||||
existingCoverArtwork.Status = ArtworkStatus.Failed;
|
||||
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
|
||||
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -261,8 +257,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
existingCoverArtwork.Status = ArtworkStatus.Enriched;
|
||||
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
|
||||
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
|
||||
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
|
||||
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -271,8 +265,6 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
existingCoverArtwork!.Status = ArtworkStatus.Enriched;
|
||||
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
|
||||
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
|
||||
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
|
||||
existingCoverArtwork.UpdatedBy = Guid.CreateVersion7();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,10 +332,7 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
|
||||
ContentHash = contentHash,
|
||||
Status = status,
|
||||
Provider = provider,
|
||||
LastUpdateUtc = lastUpdateUtc,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
LastUpdateUtc = lastUpdateUtc
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -176,10 +176,7 @@ internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanI
|
||||
Path = path,
|
||||
Title = title,
|
||||
VolumeNumber = volumeNumber,
|
||||
MetadataStatus = MetadataStatus.Pending,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
MetadataStatus = MetadataStatus.Pending
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-6
@@ -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.
|
||||
bookEntity.MetadataStatus = MetadataStatus.Failed;
|
||||
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
|
||||
bookEntity.UpdatedBy = Guid.CreateVersion7();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -247,10 +245,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
|
||||
Id = Guid.CreateVersion7(),
|
||||
BookId = bookEntity.Id,
|
||||
MediaContributorId = contributorEntity.Id,
|
||||
Role = role,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
Role = role
|
||||
});
|
||||
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
|
||||
}
|
||||
|
||||
@@ -295,9 +295,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -337,9 +334,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -389,9 +383,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
Rank = nextRank,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -442,9 +433,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
Rank = nextRank,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -484,9 +472,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
Rank = nextRank,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -526,9 +511,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = false,
|
||||
Rank = nextRank,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -583,9 +565,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = isEnabled,
|
||||
Rank = index + 1,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
configuration.IsEnabled = isEnabled;
|
||||
configuration.Rank = index + 1;
|
||||
@@ -641,9 +620,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
PluginId = pluginId,
|
||||
IsEnabled = isEnabled,
|
||||
Rank = index + 1,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
configuration.IsEnabled = isEnabled;
|
||||
configuration.Rank = index + 1;
|
||||
@@ -697,9 +673,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
|
||||
LibraryId = libraryId,
|
||||
PluginId = pluginId,
|
||||
IsEnabled = isEnabled,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
configuration.IsEnabled = isEnabled;
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -74,10 +74,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
||||
Author = plugin.Author,
|
||||
Version = plugin.Version.ToString(),
|
||||
Description = plugin.Description,
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
LoadStatus = PluginLoadStatus.Loaded
|
||||
};
|
||||
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
@@ -98,10 +95,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
|
||||
Version = string.Empty,
|
||||
Description = string.Empty,
|
||||
LoadStatus = PluginLoadStatus.FailedToLoad,
|
||||
LoadError = loadError.ErrorMessage,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
LoadError = loadError.ErrorMessage
|
||||
};
|
||||
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
|
||||
@@ -191,11 +191,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
|
||||
Status = ScheduledJobStatus.Active,
|
||||
OwnerUserId = ownerUserId,
|
||||
LastStartedOnUtc = null,
|
||||
LastCompletedOnUtc = null,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = ownerUserId,
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
LastCompletedOnUtc = null
|
||||
};
|
||||
Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false);
|
||||
if (insertScheduledJobResult.IsFailure)
|
||||
|
||||
@@ -84,8 +84,6 @@ internal static class ThemeSynchronizer
|
||||
if (!string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal))
|
||||
{
|
||||
existingTheme.Version = manifestResult.Value.Version;
|
||||
existingTheme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
existingTheme.UpdatedBy = default;
|
||||
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
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,
|
||||
PreviewPath = manifestResult.Value.Preview,
|
||||
InstallSource = ThemeInstallSource.Bundled,
|
||||
InstalledAtUtc = DateTime.UtcNow,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
InstalledAtUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
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.
|
||||
brokenTheme.IsDeleted = true;
|
||||
brokenTheme.IsCurrent = null;
|
||||
brokenTheme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
brokenTheme.UpdatedBy = default;
|
||||
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
|
||||
@@ -227,8 +220,6 @@ internal static class ThemeSynchronizer
|
||||
return;
|
||||
|
||||
defaultTheme.IsCurrent = true;
|
||||
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
|
||||
defaultTheme.UpdatedBy = default;
|
||||
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
|
||||
|
||||
+38
-6
@@ -1,6 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -8,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -227,24 +231,31 @@ public class MusicArtworkRepositoryTests : IDisposable
|
||||
{
|
||||
// Arrange
|
||||
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
|
||||
Result<Updated> result = await _sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
|
||||
await _context.SaveChangesAsync();
|
||||
Result<Updated> result = await sut.UpsertCoverAsync(MusicArtworkOwnerType.Album, ownerId, "covers/new.jpg", CancellationToken.None);
|
||||
await auditedContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
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(ownerId, cover.OwnerId);
|
||||
Assert.Equal(ArtworkType.Cover, cover.ArtworkType);
|
||||
Assert.Equal(0, cover.Ordinal);
|
||||
Assert.Equal("covers/new.jpg", cover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
Assert.Equal(Guid.Empty, cover.CreatedBy);
|
||||
Assert.True(cover.CreatedOnUtc >= before);
|
||||
Assert.Equal(insertedOnUtc, cover.CreatedOnUtc);
|
||||
Assert.Equal(actingUserId, cover.CreatedBy);
|
||||
Assert.Null(cover.UpdatedOnUtc);
|
||||
Assert.Null(cover.UpdatedBy);
|
||||
}
|
||||
|
||||
@@ -468,6 +479,27 @@ public class MusicArtworkRepositoryTests : IDisposable
|
||||
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>
|
||||
/// Disposes the database context and its underlying connection.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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>
|
||||
/// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider.
|
||||
/// </summary>
|
||||
|
||||
+3
-3
@@ -138,9 +138,9 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Set up admin permissions and roles.
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
||||
|
||||
// Authenticate user.
|
||||
|
||||
+16
-2
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
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.CanDeleteUsers);
|
||||
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
|
||||
Assert.All(permissions, permission => Assert.Equal(AuditIdentities.s_systemUserId, permission.CreatedBy));
|
||||
|
||||
// Verify default roles.
|
||||
List<RoleEntity> roles = await dbContext.Roles.ToListAsync();
|
||||
RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == "Admin");
|
||||
Assert.NotNull(adminRole);
|
||||
Assert.Equal(AuditIdentities.s_systemUserId, adminRole!.CreatedBy);
|
||||
|
||||
// Verify admin role permissions.
|
||||
List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions
|
||||
.Where(rp => rp.RoleId == adminRole!.Id)
|
||||
.Where(rp => rp.RoleId == adminRole.Id)
|
||||
.ToListAsync();
|
||||
Assert.NotEmpty(rolePermissions);
|
||||
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.
|
||||
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.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()
|
||||
|
||||
+1
-1
@@ -413,7 +413,7 @@ public class StartConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -26,7 +26,7 @@ public class FavoriteMappingTests
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldAndTheAuditColumns()
|
||||
public void ToRepositoryEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldWithoutTheAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
@@ -50,10 +50,9 @@ public class FavoriteMappingTests
|
||||
Assert.Equal(userId, entity.UserId);
|
||||
Assert.Equal(FavoriteMediaKind.Book, entity.MediaKind);
|
||||
Assert.Equal(mediaItemId, entity.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, entity.CreatedOnUtc);
|
||||
Assert.Equal(default, entity.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, entity.CreatedBy);
|
||||
Assert.True(entity.UpdatedOnUtc.HasValue);
|
||||
Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc.Value);
|
||||
Assert.Null(entity.UpdatedOnUtc);
|
||||
Assert.Null(entity.UpdatedBy);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ public class MediaConsumptionRecordMappingTests
|
||||
Assert.Equal(0.75, result.LastProgressFraction);
|
||||
Assert.Equal(0, result.ConsecutivePagesRead);
|
||||
Assert.Equal(1L, result.Version);
|
||||
Assert.Equal(startedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, result.CreatedBy);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ public class MediaResumePointMappingTests
|
||||
Assert.Equal(0.6, result.LastProgressFraction);
|
||||
Assert.Equal(lastConsumedOnUtc, result.LastConsumedOnUtc);
|
||||
Assert.Equal(1L, result.Version);
|
||||
Assert.Equal(createdOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, result.CreatedBy);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
|
||||
+2
-2
@@ -69,7 +69,7 @@ public class AlbumMappingTests
|
||||
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.Ratings.ToRepositoryEntities(), result.Ratings);
|
||||
Assert.Equal(album.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, result.CreatedBy);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
@@ -95,7 +95,7 @@ public class AlbumMappingTests
|
||||
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
|
||||
Assert.Equal(contributor.Role, contributorEntity.Role);
|
||||
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.Null(contributorEntity.UpdatedBy);
|
||||
}
|
||||
|
||||
+2
-2
@@ -43,7 +43,7 @@ public class ArtistMappingTests
|
||||
Assert.Equal(artist.Name, result.Name);
|
||||
Assert.Equal(artist.Website.Value, result.Website);
|
||||
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.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
@@ -67,7 +67,7 @@ public class ArtistMappingTests
|
||||
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
|
||||
Assert.Equal(contributor.Role, contributorEntity.Role);
|
||||
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.Null(contributorEntity.UpdatedBy);
|
||||
}
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ public class TrackMappingTests
|
||||
Assert.Equal(track.Moods.ToRepositoryEntities(), result.Moods);
|
||||
Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs);
|
||||
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.Null(result.UpdatedOnUtc);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
@@ -108,7 +108,7 @@ public class TrackMappingTests
|
||||
Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId);
|
||||
Assert.Equal(contributor.Role, contributorEntity.Role);
|
||||
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.Null(contributorEntity.UpdatedOnUtc);
|
||||
Assert.Null(contributorEntity.UpdatedBy);
|
||||
|
||||
+2
-2
@@ -54,8 +54,8 @@ public class LibraryMappingTests
|
||||
Assert.Equal(library.LibraryType, result.LibraryType);
|
||||
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.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(library.UpdatedOnUtc.HasValue ? library.UpdatedOnUtc.Value : null, result.UpdatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.True(result.IsEnabled);
|
||||
Assert.False(result.IsLocked);
|
||||
Assert.True(result.CanDownloadMetadataFromWeb);
|
||||
|
||||
+6
-4
@@ -68,8 +68,8 @@ public class BookMappingTests
|
||||
Assert.Equal(book.AppleBooksId.HasValue ? book.AppleBooksId.Value : null, result.AppleBooksId);
|
||||
Assert.Equal(book.ISBNs.ToRepositoryEntities(), result.ISBNs);
|
||||
Assert.Equal(book.Ratings.ToRepositoryEntities(), result.Ratings);
|
||||
Assert.Equal(book.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(book.UpdatedOnUtc.HasValue ? book.UpdatedOnUtc.Value : null, result.UpdatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -79,6 +79,8 @@ public class BookMappingTests
|
||||
Book book = _bookFixture.Create();
|
||||
BookEntity entity = _bookEntityFixture.Create();
|
||||
BookEntity expectedEntity = book.ToRepositoryEntity();
|
||||
DateTime? initialUpdatedOnUtc = entity.UpdatedOnUtc;
|
||||
Guid? initialUpdatedBy = entity.UpdatedBy;
|
||||
|
||||
// Act
|
||||
entity.ApplyMetadataToEntity(book);
|
||||
@@ -113,8 +115,8 @@ public class BookMappingTests
|
||||
Assert.Equal(expectedEntity.GoogleBooksId, entity.GoogleBooksId);
|
||||
Assert.Equal(expectedEntity.BarnesAndNobleId, entity.BarnesAndNobleId);
|
||||
Assert.Equal(expectedEntity.AppleBooksId, entity.AppleBooksId);
|
||||
Assert.NotNull(entity.UpdatedOnUtc);
|
||||
Assert.NotNull(entity.UpdatedBy);
|
||||
Assert.Equal(initialUpdatedOnUtc, entity.UpdatedOnUtc);
|
||||
Assert.Equal(initialUpdatedBy, entity.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+8
-8
@@ -25,13 +25,12 @@ public class UpdateBookCoverCommandMappingTests
|
||||
public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString());
|
||||
string storedCoverPath = "/media/books/cover.jpg";
|
||||
|
||||
// Act
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath, userId);
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(bookId, cover.BookId);
|
||||
@@ -39,8 +38,8 @@ public class UpdateBookCoverCommandMappingTests
|
||||
Assert.Equal(0, cover.Ordinal);
|
||||
Assert.Equal(storedCoverPath, cover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
Assert.Equal(userId, cover.CreatedBy);
|
||||
Assert.NotEqual(default, cover.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, cover.CreatedBy);
|
||||
Assert.Equal(default, cover.CreatedOnUtc);
|
||||
Assert.Null(cover.UpdatedBy);
|
||||
}
|
||||
|
||||
@@ -48,21 +47,22 @@ public class UpdateBookCoverCommandMappingTests
|
||||
public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
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);
|
||||
DateTime? initialUpdatedOnUtc = existingCover.UpdatedOnUtc;
|
||||
Guid? initialUpdatedBy = existingCover.UpdatedBy;
|
||||
string storedCoverPath = "/media/books/cover.jpg";
|
||||
|
||||
// Act
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath, userId);
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath);
|
||||
|
||||
// Assert
|
||||
Assert.Same(existingCover, cover);
|
||||
Assert.Equal(storedCoverPath, cover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
Assert.Equal(userId, cover.UpdatedBy);
|
||||
Assert.NotNull(cover.UpdatedOnUtc);
|
||||
Assert.Equal(initialUpdatedOnUtc, cover.UpdatedOnUtc);
|
||||
Assert.Equal(initialUpdatedBy, cover.UpdatedBy);
|
||||
Assert.NotNull(cover.LastUpdateUtc);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -46,8 +46,8 @@ public class PlaylistMappingTests
|
||||
Assert.Equal("Focus", result.Name);
|
||||
Assert.Equal("Deep work", result.Description);
|
||||
Assert.Equal(PlaylistType.Music, result.Type);
|
||||
Assert.Equal(createdOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(updatedOnUtc, result.UpdatedOnUtc);
|
||||
Assert.Equal(default, result.CreatedOnUtc);
|
||||
Assert.Null(result.UpdatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, result.CreatedBy);
|
||||
Assert.Null(result.UpdatedBy);
|
||||
}
|
||||
|
||||
+86
-51
@@ -1,13 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
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.DTO.Filtering;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
@@ -49,6 +49,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly IValidator<SetupApplicationCommand> _mockValidator;
|
||||
private readonly SetupApplicationCommandHandler _sut;
|
||||
private readonly DateTime _fixedUtcNow;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
|
||||
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new();
|
||||
@@ -61,7 +62,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
public SetupApplicationCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockHashService = Substitute.For<IPasswordHashService>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
@@ -70,6 +71,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockDataSeedService = Substitute.For<IDataSeedService>();
|
||||
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
|
||||
@@ -77,7 +79,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
_mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
@@ -101,18 +103,20 @@ public class SetupApplicationCommandHandlerTests
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false };
|
||||
string hashedPassword = Uri.EscapeDataString("hashedPassword");
|
||||
UserEntity? insertedUser = null;
|
||||
|
||||
_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)
|
||||
.AndDoes(info => insertedUser = info.Arg<UserEntity>());
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -125,10 +129,41 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(command.Username, result.Value.Username);
|
||||
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).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]
|
||||
@@ -153,11 +188,11 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns(encryptedSecret);
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -173,7 +208,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: 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]
|
||||
@@ -195,7 +230,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: 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]
|
||||
@@ -217,7 +252,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: 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]
|
||||
@@ -241,7 +276,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: 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]
|
||||
@@ -255,7 +290,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
@@ -265,8 +300,8 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -280,9 +315,9 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
@@ -292,9 +327,9 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -308,11 +343,11 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
@@ -322,9 +357,9 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(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)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
@@ -355,9 +390,9 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(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)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -405,11 +440,11 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -422,9 +457,9 @@ public class SetupApplicationCommandHandlerTests
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(command.Username, result.Value.Username);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(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).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)));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -492,11 +527,11 @@ public class SetupApplicationCommandHandlerTests
|
||||
.Returns("hashedPassword");
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
-1
@@ -529,7 +529,6 @@ public class ReportConsumptionProgressCommandHandlerTests
|
||||
await _mockMediaResumePointRepository.Received(1).UpsertForUserAsync(
|
||||
Arg.Is<MediaResumePointEntity>(resumePoint =>
|
||||
resumePoint.Id == existingResumePoint.Id &&
|
||||
resumePoint.CreatedOnUtc == existingResumePoint.CreatedOnUtc &&
|
||||
resumePoint.LastPositionTimeOffsetMilliseconds == 600_000 &&
|
||||
resumePoint.LastProgressFraction == 0.4),
|
||||
_userId,
|
||||
|
||||
-1
@@ -145,7 +145,6 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
Assert.Single(existingBook.Artwork);
|
||||
Assert.Equal(result.Value.CoverPath, existingCover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, existingCover.Status);
|
||||
Assert.Equal(_userId, existingCover.UpdatedBy);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -267,7 +267,7 @@ public class DeleteThemeCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
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>());
|
||||
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
|
||||
+2
-7
@@ -202,9 +202,7 @@ public class InstallThemeCommandHandlerTests
|
||||
theme.Version == manifest.Version &&
|
||||
theme.PreviewPath == manifest.Preview &&
|
||||
theme.InstallSource == ThemeInstallSource.Uploaded &&
|
||||
theme.IsDeleted == false &&
|
||||
theme.CreatedBy == _userId &&
|
||||
theme.UpdatedBy == _userId),
|
||||
theme.IsDeleted == false),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
@@ -268,10 +266,7 @@ public class InstallThemeCommandHandlerTests
|
||||
theme.Name == manifest.Name &&
|
||||
theme.InstallSource == existingTheme.InstallSource &&
|
||||
theme.IsCurrent == existingTheme.IsCurrent &&
|
||||
theme.IsDeleted == false &&
|
||||
theme.CreatedOnUtc == existingTheme.CreatedOnUtc &&
|
||||
theme.CreatedBy == existingTheme.CreatedBy &&
|
||||
theme.UpdatedBy == _userId),
|
||||
theme.IsDeleted == false),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
|
||||
+1
-1
@@ -235,7 +235,7 @@ public class RestoreThemeCommandHandlerTests
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
|
||||
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>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
+2
-2
@@ -238,7 +238,7 @@ public class SetCurrentThemeCommandHandlerTests
|
||||
Arg.Is<ThemeEntity>(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
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>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
@@ -290,7 +290,7 @@ public class SetCurrentThemeCommandHandlerTests
|
||||
Assert.Equal(theme.Id, result.Value.Id);
|
||||
Assert.True(result.Value.IsCurrent);
|
||||
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>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
-5
@@ -5,7 +5,6 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
@@ -33,7 +32,6 @@ public class RegisterUserCommandHandlerTests
|
||||
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
|
||||
private readonly IQRCodeGenerator _mockQRCodeGenerator;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly RegisterUserCommandHandler _sut;
|
||||
private readonly RegisterUserCommandFixture _registerUserCommandFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
@@ -50,10 +48,8 @@ public class RegisterUserCommandHandlerTests
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||
|
||||
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
|
||||
mockValidator.Validate(Arg.Any<RegisterUserCommand>())
|
||||
@@ -64,7 +60,6 @@ public class RegisterUserCommandHandlerTests
|
||||
_mockCryptographyService,
|
||||
_mockTotpTokenGenerator,
|
||||
_mockQRCodeGenerator,
|
||||
_mockDateTimeProvider,
|
||||
mockValidator);
|
||||
}
|
||||
|
||||
|
||||
+28
-2
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -83,7 +84,7 @@ public class UpdateAuditableEntitiesInterceptorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldUseGuidEmptyForCreationAndSystemUserForModification()
|
||||
public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldLeaveCreationAndModificationUnattributed()
|
||||
{
|
||||
// Arrange
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
@@ -98,10 +99,35 @@ public class UpdateAuditableEntitiesInterceptorTests
|
||||
|
||||
// Assert
|
||||
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);
|
||||
}
|
||||
|
||||
[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]
|
||||
public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties()
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Repositories.Authorization;
|
||||
@@ -49,10 +50,10 @@ public class DataSeedServiceTests
|
||||
public DataSeedServiceTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockPermissionRepository = Substitute.For<IPermissionRepository>();
|
||||
_fixedUtcNow = DateTime.UtcNow;
|
||||
_fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
|
||||
@@ -64,13 +65,12 @@ public class DataSeedServiceTests
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_WhenSuccessful_ShouldInsertAllPermissionsAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminId = Guid.NewGuid();
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -80,38 +80,36 @@ public class DataSeedServiceTests
|
||||
.Received(4)
|
||||
.InsertAsync(
|
||||
Arg.Is<PermissionEntity>(p =>
|
||||
p.CreatedBy == adminId &&
|
||||
p.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
p.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_WhenInsertFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminId = Guid.NewGuid();
|
||||
Error expectedError = Error.Conflict("Permission.Conflict", "Permission already exists");
|
||||
_mockPermissionRepository
|
||||
.InsertAsync(Arg.Any<PermissionEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationPermissionsAsync_ShouldCreateAllDefaultPermissions()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminId = Guid.NewGuid();
|
||||
List<AuthorizationPermission> capturedPermissions = [];
|
||||
|
||||
_mockPermissionRepository
|
||||
@@ -120,7 +118,7 @@ public class DataSeedServiceTests
|
||||
.AndDoes(info => capturedPermissions.Add(info.Arg<PermissionEntity>().PermissionName));
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationPermissionsAsync(adminId, CancellationToken.None);
|
||||
await _sut.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new[]
|
||||
@@ -136,7 +134,6 @@ public class DataSeedServiceTests
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenSuccessful_ShouldInsertAllRolesAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
mockRoleRepository
|
||||
@@ -144,7 +141,7 @@ public class DataSeedServiceTests
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -154,19 +151,18 @@ public class DataSeedServiceTests
|
||||
.Received(1)
|
||||
.InsertAsync(
|
||||
Arg.Is<RoleEntity>(r =>
|
||||
r.CreatedBy == userId &&
|
||||
r.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
r.CreatedOnUtc == _fixedUtcNow &&
|
||||
r.RoleName == "Admin"),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenInsertFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
@@ -176,20 +172,19 @@ public class DataSeedServiceTests
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldCreateDefaultAdminRole()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
List<string> capturedRoleNames = [];
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
@@ -201,17 +196,16 @@ public class DataSeedServiceTests
|
||||
.AndDoes(info => capturedRoleNames.Add(info.Arg<RoleEntity>().RoleName));
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new[] { "Admin" }, capturedRoleNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldSetCorrectAuditProperties()
|
||||
public async Task SetDefaultAuthorizationRolesAsync_WhenCalled_ShouldSetTheSystemAuditProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity? capturedRole = null;
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
@@ -223,11 +217,11 @@ public class DataSeedServiceTests
|
||||
.AndDoes(info => capturedRole = info.Arg<RoleEntity>());
|
||||
|
||||
// Act
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
await _sut.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedRole);
|
||||
Assert.Equal(userId, capturedRole!.CreatedBy);
|
||||
Assert.Equal(AuditIdentities.s_systemUserId, capturedRole!.CreatedBy);
|
||||
Assert.Equal(_fixedUtcNow, capturedRole.CreatedOnUtc);
|
||||
Assert.Null(capturedRole.UpdatedBy);
|
||||
Assert.Null(capturedRole.UpdatedOnUtc);
|
||||
@@ -237,7 +231,6 @@ public class DataSeedServiceTests
|
||||
public async Task SetAdminRolePermissionsAsync_WhenSuccessful_ShouldAssignAllPermissionsToAdminRole()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
List<PermissionEntity> permissions =
|
||||
[
|
||||
@@ -267,7 +260,7 @@ public class DataSeedServiceTests
|
||||
mockRolePermissionRepository.InsertAsync(Arg.Any<RolePermissionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -278,18 +271,17 @@ public class DataSeedServiceTests
|
||||
.InsertAsync(
|
||||
Arg.Is<RolePermissionEntity>(rp =>
|
||||
rp.RoleId == adminRole.Id &&
|
||||
rp.CreatedBy == userId &&
|
||||
rp.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
rp.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenAdminRoleNotFound_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
|
||||
|
||||
@@ -298,19 +290,18 @@ public class DataSeedServiceTests
|
||||
.Returns((RoleEntity?)null);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenGetPermissionsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
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);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenInsertRolePermissionFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
List<PermissionEntity> permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)];
|
||||
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);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAdminRolePermissionsAsync_WhenGetAdminRoleFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
|
||||
|
||||
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
|
||||
@@ -387,13 +376,13 @@ public class DataSeedServiceTests
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None);
|
||||
Result<Created> result = await _sut.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -431,11 +420,11 @@ public class DataSeedServiceTests
|
||||
Arg.Is<UserRoleEntity>(ur =>
|
||||
ur.UserId == userId &&
|
||||
ur.RoleId == adminRole.Id &&
|
||||
ur.CreatedBy == userId &&
|
||||
ur.CreatedBy == AuditIdentities.s_systemUserId &&
|
||||
ur.CreatedOnUtc == _fixedUtcNow),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -456,7 +445,7 @@ public class DataSeedServiceTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminRoleNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -482,7 +471,7 @@ public class DataSeedServiceTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Authorization.AdminAccountNotFound, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -514,7 +503,7 @@ public class DataSeedServiceTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -538,7 +527,7 @@ public class DataSeedServiceTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -565,7 +554,7 @@ public class DataSeedServiceTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsInitializationAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -589,7 +578,7 @@ public class DataSeedServiceTests
|
||||
Assert.Equal(6, capturedScheduledJobs.Count);
|
||||
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.CreatedBy));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(AuditIdentities.s_systemUserId, scheduledJob.CreatedBy));
|
||||
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.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
@@ -599,7 +588,7 @@ public class DataSeedServiceTests
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
|
||||
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>());
|
||||
}
|
||||
|
||||
@@ -620,6 +609,135 @@ public class DataSeedServiceTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
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);
|
||||
}
|
||||
|
||||
[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]
|
||||
public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities()
|
||||
{
|
||||
|
||||
+1
-2
@@ -461,8 +461,7 @@ public class ScheduledJobSchedulerJobTests
|
||||
scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup &&
|
||||
scheduledJob.ScheduleType == ScheduleType.OnceAtStartup &&
|
||||
scheduledJob.Status == ScheduledJobStatus.Active &&
|
||||
scheduledJob.OwnerUserId == ownerUserId &&
|
||||
scheduledJob.CreatedBy == ownerUserId),
|
||||
scheduledJob.OwnerUserId == ownerUserId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
+5
-3
@@ -443,7 +443,7 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersionTimestampAndUpdater()
|
||||
public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersion()
|
||||
{
|
||||
// Arrange
|
||||
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0");
|
||||
@@ -458,6 +458,8 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
updatedOnUtc: DateTime.UtcNow.AddDays(-1),
|
||||
includeUpdatedBy: true,
|
||||
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)));
|
||||
string archivePath = CreateArchiveFile();
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||
@@ -470,8 +472,8 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
|
||||
// Assert
|
||||
Assert.Equal("3.0.0", installedTheme.Version);
|
||||
Assert.NotNull(installedTheme.UpdatedOnUtc);
|
||||
Assert.Null(installedTheme.UpdatedBy);
|
||||
Assert.Equal(initialUpdatedOnUtc, installedTheme.UpdatedOnUtc);
|
||||
Assert.Equal(initialUpdatedBy, installedTheme.UpdatedBy);
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
Reference in new issue
Block a user