diff --git a/README.md b/README.md
index 35eeace9..f7754981 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ For those with technical curiosities, here are some goodies to browse through:
4. [3.2 Component API Server diagram](./docs/technical/architecture/3.2%20component-api-server-diagram.svg)
5. [4.1 Code media library scanning diagram](./docs/technical/architecture/4.1%20code-media-library-scanning-diagram.svg)
6. [4.2 Code book reading diagram](./docs/technical/architecture/4.2%20code-book-reading-diagram.svg)
+7. [4.3 Code scheduled jobs diagram](./docs/technical/architecture/4.3%20code-scheduler-diagram.svg)
- Also for Software Architects, you might want to take a look at the Architecture Decision Log, where you may find important stories from the past of Lumina's development, like [this one](./docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md), and others like it.
## Telemetry and Observability
diff --git a/docs/technical/api/scheduling/Api.Scheduling.md b/docs/technical/api/scheduling/Api.Scheduling.md
new file mode 100644
index 00000000..fcc99550
--- /dev/null
+++ b/docs/technical/api/scheduling/Api.Scheduling.md
@@ -0,0 +1,297 @@
+# Lumina API
+
+- [Lumina API](#lumina-api)
+ - [Scheduled Jobs](#scheduled-jobs)
+ - [Add Scheduled Job](#add-scheduled-job)
+ - [Add Scheduled Job Request](#add-scheduled-job-request)
+ - [Add Scheduled Job Response](#add-scheduled-job-response)
+ - [Get Scheduled Jobs](#get-scheduled-jobs)
+ - [Get Scheduled Jobs Request](#get-scheduled-jobs-request)
+ - [Get Scheduled Jobs Response](#get-scheduled-jobs-response)
+ - [Get Scheduled Job History](#get-scheduled-job-history)
+ - [Get Scheduled Job History Request](#get-scheduled-job-history-request)
+ - [Get Scheduled Job History Response](#get-scheduled-job-history-response)
+ - [Remove Scheduled Job](#remove-scheduled-job)
+ - [Remove Scheduled Job Request](#remove-scheduled-job-request)
+ - [Remove Scheduled Job Response](#remove-scheduled-job-response)
+ - [Start Scheduled Job](#start-scheduled-job)
+ - [Start Scheduled Job Request](#start-scheduled-job-request)
+ - [Start Scheduled Job Response](#start-scheduled-job-response)
+ - [Stop Scheduled Job](#stop-scheduled-job)
+ - [Stop Scheduled Job Request](#stop-scheduled-job-request)
+ - [Stop Scheduled Job Response](#stop-scheduled-job-response)
+ - [Fire Scheduled Job](#fire-scheduled-job)
+ - [Fire Scheduled Job Request](#fire-scheduled-job-request)
+ - [Fire Scheduled Job Response](#fire-scheduled-job-response)
+ - [Get Scheduler Display Preferences](#get-scheduler-display-preferences)
+ - [Get Scheduler Display Preferences Request](#get-scheduler-display-preferences-request)
+ - [Get Scheduler Display Preferences Response](#get-scheduler-display-preferences-response)
+ - [Update Scheduler Display Preferences](#update-scheduler-display-preferences)
+ - [Update Scheduler Display Preferences Request](#update-scheduler-display-preferences-request)
+ - [Update Scheduler Display Preferences Response](#update-scheduler-display-preferences-response)
+
+## Scheduled Jobs
+
+### Add Scheduled Job
+
+#### Add Scheduled Job Request
+
+```js
+POST api/v1/scheduled-jobs
+```
+
+```json
+{
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0
+}
+```
+
+#### Add Scheduled Job Response
+
+```js
+200 Ok
+```
+
+```json
+{
+ "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0,
+ "status": "Active",
+ "lastStartedOnUtc": null,
+ "lastCompletedOnUtc": null
+}
+```
+
+### Get Scheduler Display Preferences
+
+#### Get Scheduler Display Preferences Request
+
+```js
+GET api/v1/scheduled-jobs/display-preferences
+```
+
+#### Get Scheduler Display Preferences Response
+
+```js
+200 Ok
+```
+
+```json
+{
+ "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f",
+ "jobTypeFilter": "ScanMediaLibraries",
+ "displayTimeSpan": 10,
+ "displayTimeUnit": "Minutes"
+}
+```
+
+### Update Scheduler Display Preferences
+
+#### Update Scheduler Display Preferences Request
+
+```js
+PUT api/v1/scheduled-jobs/display-preferences
+```
+
+```json
+{
+ "jobTypeFilter": "ScanMediaLibraries",
+ "displayTimeSpan": 10,
+ "displayTimeUnit": "Minutes"
+}
+```
+
+#### Update Scheduler Display Preferences Response
+
+```js
+200 Ok
+```
+
+### Get Scheduled Jobs
+
+#### Get Scheduled Jobs Request
+
+```js
+GET api/v1/scheduled-jobs
+```
+
+#### Get Scheduled Jobs Response
+
+```js
+200 Ok
+```
+
+```json
+[
+ {
+ "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0,
+ "status": "Active",
+ "lastStartedOnUtc": "2026-09-02T03:00:00.0000000Z",
+ "lastCompletedOnUtc": "2026-09-02T03:00:42.0000000Z"
+ },
+ {
+ "id": "8c3f7b2e-1a4d-4f9c-b8e6-7d2a5f1c9e4b",
+ "name": "Clean temporary files",
+ "taskType": "CleanTemporaryFiles",
+ "scheduleType": "WithIntervalInMinutes",
+ "intervalMinutes": 60,
+ "hour": null,
+ "minute": null,
+ "status": "Added",
+ "lastStartedOnUtc": null,
+ "lastCompletedOnUtc": null
+ }
+]
+```
+
+### Get Scheduled Job History
+
+#### Get Scheduled Job History Request
+
+```js
+GET api/v1/scheduled-jobs/history?from=2026-09-02T00:00:00.0000000Z&to=2026-09-03T00:00:00.0000000Z
+```
+
+#### Get Scheduled Job History Response
+
+```js
+200 Ok
+```
+
+```json
+[
+ {
+ "id": "e5a1c9d4-6b7f-4a2e-9d3c-8f4b1a6c2d5e",
+ "scheduledJobId": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "taskType": "ScanMediaLibraries",
+ "isCycleRun": true,
+ "startedOnUtc": "2026-09-02T03:00:00.0000000Z",
+ "completedOnUtc": "2026-09-02T03:00:42.0000000Z"
+ },
+ {
+ "id": "7f2d4e8a-3c5b-4f1a-9b6e-2a8c4d7e1f3b",
+ "scheduledJobId": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "taskType": "ScanMediaLibraries",
+ "isCycleRun": false,
+ "startedOnUtc": "2026-09-02T08:15:00.0000000Z",
+ "completedOnUtc": "2026-09-02T08:15:55.0000000Z"
+ }
+]
+```
+
+### Remove Scheduled Job
+
+#### Remove Scheduled Job Request
+
+```js
+DELETE api/v1/scheduled-jobs/{scheduledJobId}
+```
+
+#### Remove Scheduled Job Response
+
+```js
+200 Ok
+```
+
+### Start Scheduled Job
+
+#### Start Scheduled Job Request
+
+```js
+PUT api/v1/scheduled-jobs/{scheduledJobId}/start
+```
+
+#### Start Scheduled Job Response
+
+```js
+200 Ok
+```
+
+```json
+{
+ "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0,
+ "status": "Active",
+ "lastStartedOnUtc": null,
+ "lastCompletedOnUtc": null
+}
+```
+
+### Stop Scheduled Job
+
+#### Stop Scheduled Job Request
+
+```js
+PUT api/v1/scheduled-jobs/{scheduledJobId}/stop
+```
+
+#### Stop Scheduled Job Response
+
+```js
+200 Ok
+```
+
+```json
+{
+ "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0,
+ "status": "Added",
+ "lastStartedOnUtc": "2026-09-02T03:00:00.0000000Z",
+ "lastCompletedOnUtc": "2026-09-02T03:00:42.0000000Z"
+}
+```
+
+### Fire Scheduled Job
+
+#### Fire Scheduled Job Request
+
+```js
+PUT api/v1/scheduled-jobs/{scheduledJobId}/fire
+```
+
+#### Fire Scheduled Job Response
+
+```js
+200 Ok
+```
+
+```json
+{
+ "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d",
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0,
+ "status": "Active",
+ "lastStartedOnUtc": null,
+ "lastCompletedOnUtc": null
+}
+```
diff --git a/docs/technical/architecture/2 container-diagram.puml b/docs/technical/architecture/2 container-diagram.puml
index b39ac302..93e4f19f 100644
--- a/docs/technical/architecture/2 container-diagram.puml
+++ b/docs/technical/architecture/2 container-diagram.puml
@@ -8,11 +8,11 @@ Person(user, "Home User", "A person who wants to manage and stream their persona
Person(admin, "Administrator", "A person who manages the media library system")
System_Boundary(c1, "Lumina 1.1") {
- Container(webapp, "Web Application Client 2.1", "ASP.NET Core MVC", "Delivers server-rendered views with dynamic client-side functionality for media management and playback [detailed in '3.1 component-web-client-diagram.puml']")
+ Container(webapp, "Web Application Client 2.1", "ASP.NET Core MVC", "Delivers server-rendered views with dynamic client-side functionality for media management, playback, and the scheduled jobs dashboard [detailed in '3.1 component-web-client-diagram.puml']")
- Container(api, "API Server 2.2", "ASP.NET Core", "Provides media management functionality via a REST API, processes media tasks, manages metadata synchronization, and serves books for reading through format plugins [detailed in '3.2 component-api-server-diagram.puml']")
+ Container(api, "API Server 2.2", "ASP.NET Core", "Provides media management functionality via a REST API, processes media tasks, manages metadata synchronization, serves books for reading through format plugins, and runs the scheduled jobs that maintain the system [detailed in '3.2 component-api-server-diagram.puml']")
- ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, automated jobs information, etc")
+ ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, scheduled jobs and their executions, automated jobs information, etc")
Container(filestore, "Media Store", "File System", "Stores the actual media files")
diff --git a/docs/technical/architecture/2 container-diagram.svg b/docs/technical/architecture/2 container-diagram.svg
index 00c22baa..57082e40 100644
--- a/docs/technical/architecture/2 container-diagram.svg
+++ b/docs/technical/architecture/2 container-diagram.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.puml b/docs/technical/architecture/3.1 component-web-client-diagram.puml
index 4c047f64..ce28b718 100644
--- a/docs/technical/architecture/3.1 component-web-client-diagram.puml
+++ b/docs/technical/architecture/3.1 component-web-client-diagram.puml
@@ -13,11 +13,13 @@ Container_Boundary(wb, "Web Application 2.1") {
Component(bookReader, "Book Reading", "FastEndpoints + JavaScript", "Serves the book reader view and proxies the reading manifest, section and resource endpoints to the API")
+ Component(scheduler, "Scheduler", "FastEndpoints + JavaScript", "Serves the scheduled jobs dashboard, proxies the scheduled job endpoints to the API, and plots the executions of the scheduled job tasks over time")
+
Component(admin, "Administration", "ASP.NET MVC Controllers", "Handles system administration and configuration")
Component(users, "User Management", "ASP.NET MVC Controllers", "Handles authentication and user management")
- Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates, persistent media playback, and the book reader (table of contents, page navigation, font size)")
+ Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates, persistent media playback, the book reader (table of contents, page navigation, font size), and the scheduled jobs dashboard (job type filters, execution graph, live hub updates)")
Component(httpClient, "API HTTP Client", "C# TypedHttpClient", "Handles communication with the API server")
}
@@ -25,14 +27,17 @@ Container_Boundary(wb, "Web Application 2.1") {
Rel(fileSystem, httpClient, "Uses")
Rel(library, httpClient, "Uses")
Rel(bookReader, httpClient, "Uses")
+Rel(scheduler, httpClient, "Uses")
Rel(admin, httpClient, "Uses")
Rel(users, httpClient, "Uses")
Rel(httpClient, api, "Makes API calls to", "JSON/HTTPS")
Rel(clientJs, fileSystem, "Makes AJAX calls to")
Rel(clientJs, library, "Makes AJAX calls to")
Rel(clientJs, bookReader, "Makes AJAX calls to")
+Rel(clientJs, scheduler, "Makes AJAX calls to")
Rel(clientJs, admin, "Makes AJAX calls to")
Rel(clientJs, users, "Makes AJAX calls to")
+Rel(clientJs, api, "Receives scheduled jobs and execution updates from the scheduled jobs hub", "SignalR")
caption [Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web)
diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.svg b/docs/technical/architecture/3.1 component-web-client-diagram.svg
index 1a888bea..367a34a5 100644
--- a/docs/technical/architecture/3.1 component-web-client-diagram.svg
+++ b/docs/technical/architecture/3.1 component-web-client-diagram.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.puml b/docs/technical/architecture/3.2 component-api-server-diagram.puml
index c1edde0a..9b01eccf 100644
--- a/docs/technical/architecture/3.2 component-api-server-diagram.puml
+++ b/docs/technical/architecture/3.2 component-api-server-diagram.puml
@@ -21,6 +21,8 @@ Container_Boundary(api, "API Server 2.2") {
Component(readerPlugins, "Book Reader Plugins", "Lumina.Plugins.Epub, Lumina.Plugins.Pdf", "Decode a book format into a normalized reading document (spine, table of contents, sections, resources), loaded into the host by the plugin loader [detailed in '4.2 code-book-reading-diagram.puml']")
+ Component(scheduledJobs, "Scheduled Jobs 3.2.3", "Application + Infrastructure services", "Lets administrators schedule the one off or recurring execution of maintenance tasks (media library scans, temporary files cleanup); a background scheduler runs the tasks on their schedules and the scheduled jobs hub broadcasts the jobs and their executions [detailed in '4.3 code-scheduler-diagram.puml']")
+
Component(repositories, "Repositories", "EF Core", "Provides data access abstraction for domain entities")
}
@@ -35,16 +37,20 @@ Rel(endpoints, mediaManagement, "Uses")
Rel(endpoints, userManagement, "Uses")
Rel(endpoints, fileSystem, "Uses")
Rel(endpoints, bookReading, "Uses")
+Rel(endpoints, scheduledJobs, "Uses")
Rel(mediaManagement, repositories, "Uses")
Rel(userManagement, repositories, "Uses")
Rel(fileSystem, repositories, "Uses")
Rel(backgroundServices, mediaManagement, "Uses")
+Rel(scheduledJobs, repositories, "Uses")
Rel(repositories, db, "Reads from and writes to", "SQL")
Rel(mediaManagement, metadataServices, "Retrieves metadata from", "HTTPS")
Rel(bookReading, readerPlugins, "Resolves and invokes")
Rel(bookReading, repositories, "Reads the per-library reader enablement")
Rel(bookReading, readCache, "Extracts into and serves from", "File system")
Rel(readerPlugins, readCache, "Extracts into", "File system")
+Rel(scheduledJobs, backgroundServices, "Queues the media library scans of its ScanMediaLibraries task")
+Rel(scheduledJobs, readCache, "Empties with its CleanTemporaryFiles task", "File system")
caption [Component] Lumina - API Server 2.2 (Lumina.Presentation.Api)
diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.svg b/docs/technical/architecture/3.2 component-api-server-diagram.svg
index e424f40b..8d389fae 100644
--- a/docs/technical/architecture/3.2 component-api-server-diagram.svg
+++ b/docs/technical/architecture/3.2 component-api-server-diagram.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.puml b/docs/technical/architecture/4.3 code-scheduler-diagram.puml
new file mode 100644
index 00000000..0f31d592
--- /dev/null
+++ b/docs/technical/architecture/4.3 code-scheduler-diagram.puml
@@ -0,0 +1,442 @@
+@startuml Scheduled Jobs Code
+!include
+
+LAYOUT_WITH_LEGEND()
+title Code diagram for Scheduled Jobs 3.2.3
+
+skinparam class {
+ BackgroundColor White
+ BorderColor Black
+}
+
+' ============================== DOMAIN AGGREGATE ==============================
+
+class ScheduledJob {
+ - _currentExecutionRunId: Optional
+ + Name: string
+ + TaskType: ScheduledTaskType
+ + Schedule: Schedule
+ + Status: ScheduledJobStatus
+ + OwnerUserId: UserId
+ + LastStartedOnUtc: Optional
+ + LastCompletedOnUtc: Optional
+ + {static} Create(name: string, taskType: ScheduledTaskType, schedule: Schedule, ownerUserId: UserId): Result
+ + Add(): Result
+ + StartCycle(): Result
+ + StopCycle(): Result
+ + Fire(): Result
+ + Remove(): Result
+ + MarkExecutionStarted(isCycleRun: bool): Result
+ + MarkExecutionCompleted(isCycleRun: bool): Result
+}
+
+note right of ScheduledJob
+ Aggregate root of the scheduling bounded context. Drives the
+ life cycle of a scheduled job and of each execution of its task
+ through domain events. The private _currentExecutionRunId tracks
+ the run of the task currently executing, so that only the worker
+ that marked the run as started can complete it.
+end note
+
+' ============================== DOMAIN VALUE OBJECTS AND EVENTS ==============================
+
+abstract class Schedule {
+ + ScheduleType: ScheduleType
+ + {abstract} GetDelayUntilNextExecution(utcNow: DateTime, timeZone: TimeZoneInfo): TimeSpan
+}
+
+class IntervalSchedule {
+ + IntervalMinutes: int
+ + {static} Create(intervalMinutes: int): Result
+}
+
+class DailySchedule {
+ + Hour: int
+ + Minute: int
+ + {static} Create(hour: int, minute: int): Result
+}
+
+class ScheduledJobId {
+ + Value: Guid
+ + {static} CreateUnique(): ScheduledJobId
+ + {static} Create(value: Guid): ScheduledJobId
+}
+
+class ScheduledJobAddedDomainEvent
+class ScheduledJobCycleStartedDomainEvent
+class ScheduledJobCycleStoppedDomainEvent
+class ScheduledJobExecutionStartedDomainEvent {
+ + RunId: Guid
+ + TaskType: ScheduledTaskType
+ + IsCycleRun: bool
+ + StartedOnUtc: DateTime
+}
+class ScheduledJobExecutionCompletedDomainEvent {
+ + RunId: Guid
+ + IsCycleRun: bool
+ + CompletedOnUtc: DateTime
+}
+class ScheduledJobExecutionStoppedDomainEvent
+class ScheduledJobFiredDomainEvent
+class ScheduledJobRemovedDomainEvent
+
+' ============================== APPLICATION CONTRACTS ==============================
+
+interface IScheduledJobScheduler {
+ + StartCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+ + StopCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+ + RunOnceAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+}
+
+interface IScheduledJobNotifier {
+ + SendScheduledJobsAsync(scheduledJobs: IReadOnlyList, token: CancellationToken): Task
+ + SendScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
+ + SendScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
+}
+
+interface IScheduledJobRepository {
+ + GetByIdAsync(id: Guid, token: CancellationToken): Task>
+ + GetAllAsync(token: CancellationToken): Task>>
+ + GetActiveOrRunningAsync(token: CancellationToken): Task>>
+ + InsertAsync(entity: ScheduledJobEntity, token: CancellationToken): Task>
+ + UpdateAsync(entity: ScheduledJobEntity, token: CancellationToken): Task>
+ + DeleteByIdAsync(id: Guid, token: CancellationToken): Task>
+}
+
+interface IScheduledJobExecutionRepository {
+ + GetByIdAsync(id: Guid, token: CancellationToken): Task>
+ + GetOpenByScheduledJobIdAsync(scheduledJobId: Guid, token: CancellationToken): Task>
+ + GetByTimeRangeAsync(fromUtc: DateTime, toUtc: DateTime, token: CancellationToken): Task>>
+ + InsertAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task>
+ + UpdateAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task>
+ + DeleteByScheduledJobIdAsync(scheduledJobId: Guid, token: CancellationToken): Task>
+}
+
+' ============================== APPLICATION HANDLERS ==============================
+
+class AddScheduledJobCommandHandler {
+ + HandleAsync(command: AddScheduledJobCommand, token: CancellationToken): Task>
+}
+
+class StartScheduledJobCommandHandler {
+ + HandleAsync(command: StartScheduledJobCommand, token: CancellationToken): Task>
+}
+
+class StopScheduledJobCommandHandler {
+ + HandleAsync(command: StopScheduledJobCommand, token: CancellationToken): Task>
+}
+
+class FireScheduledJobCommandHandler {
+ + HandleAsync(command: FireScheduledJobCommand, token: CancellationToken): Task>
+}
+
+class RemoveScheduledJobCommandHandler {
+ + HandleAsync(command: RemoveScheduledJobCommand, token: CancellationToken): Task>
+}
+
+class GetScheduledJobsQueryHandler {
+ + HandleAsync(query: GetScheduledJobsQuery, token: CancellationToken): Task>>
+}
+
+class GetScheduledJobHistoryQueryHandler {
+ + HandleAsync(query: GetScheduledJobHistoryQuery, token: CancellationToken): Task>>
+}
+
+' ============================== DOMAIN EVENT HANDLERS ==============================
+
+class ScheduledJobAddedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobAddedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobCycleStartedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobCycleStartedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobCycleStoppedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobCycleStoppedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobExecutionStartedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobExecutionStartedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobExecutionCompletedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobExecutionCompletedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobExecutionStoppedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobExecutionStoppedDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobFiredDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobFiredDomainEvent, token: CancellationToken): ValueTask
+}
+
+class ScheduledJobRemovedDomainEventHandler {
+ + HandleAsync(domainEvent: ScheduledJobRemovedDomainEvent, token: CancellationToken): ValueTask
+}
+
+note bottom of ScheduledJobExecutionStartedDomainEventHandler
+ Updates the scheduled job to Running, inserts the open execution
+ history row, and notifies the SignalR clients about the started
+ execution.
+end note
+
+note bottom of ScheduledJobExecutionCompletedDomainEventHandler
+ Returns the scheduled job to Active after a cycle run, or completes
+ it after a one time execution, closes the execution history row,
+ and notifies the SignalR clients about the completed execution.
+end note
+
+' ============================== INFRASTRUCTURE - SCHEDULER ==============================
+
+class ScheduledJobSchedulerJob {
+ - _serviceScopeFactory: IServiceScopeFactory
+ - _runtimeRegistry: IScheduledJobRuntimeRegistry
+ - _logger: ILogger
+ + StartCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+ + StopCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+ + RunOnceAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task
+ + ExecuteAsync(stoppingToken: CancellationToken): Task
+ - ResumeActiveCyclesAsync(token: CancellationToken): Task
+ - RunCycleWorkerAsync(scheduledJobId: ScheduledJobId, runImmediately: bool, stoppingToken: CancellationToken): Task
+ - RunScheduledJobAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): Task
+ - ExecuteScheduledJobRunAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): Task
+}
+
+note right of ScheduledJobSchedulerJob
+ Background service (registered as IScheduledJobScheduler and hosted)
+ that resumes the active execution cycles at startup, runs each cycle
+ worker on its schedule through PeriodicTimer, guards each execution
+ against overlapping runs, and publishes the started and completed
+ domain events of every run through the EventualConsistencyMiddleware.
+end note
+
+interface IScheduledJobRuntimeRegistry {
+ + TryStartCycle(scheduledJobId: ScheduledJobId, cycleCancellationTokenSource: CancellationTokenSource): bool
+ + StopCycle(scheduledJobId: ScheduledJobId)
+ + TryAcquireRunSlot(scheduledJobId: ScheduledJobId): bool
+ + ReleaseRunSlot(scheduledJobId: ScheduledJobId)
+}
+
+class ScheduledJobRuntimeRegistry {
+ - _runtimeStates: ConcurrentDictionary
+}
+
+note right of ScheduledJobRuntimeRegistry
+ Holds the live runtime state of the scheduled jobs in memory: one
+ cancellation token source per execution cycle and one run slot per
+ scheduled job, so no two executions of the same task overlap.
+end note
+
+' ============================== INFRASTRUCTURE - TASK EXECUTORS ==============================
+
+interface IScheduledTaskExecutorFactory {
+ + CreateExecutor(taskType: ScheduledTaskType): IScheduledTaskExecutor
+}
+
+class ScheduledTaskExecutorFactory {
+ - _serviceProvider: IServiceProvider
+ + CreateExecutor(taskType: ScheduledTaskType): IScheduledTaskExecutor
+}
+
+interface IScheduledTaskExecutor {
+ + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task>
+}
+
+class MediaLibraryScanTaskExecutor {
+ - _unitOfWork: IUnitOfWork
+ - _domainEventPublisher: IDomainEventPublisher
+ + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task>
+}
+
+note right of MediaLibraryScanTaskExecutor
+ Executes the ScanMediaLibraries task on behalf of the owner of the
+ scheduled job: queues a media library scan for every enabled and
+ unlocked library that is not already being scanned, and lets the
+ media library scanning subsystem process them.
+end note
+
+class TemporaryFilesCleanupTaskExecutor {
+ + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task>
+}
+
+note right of TemporaryFilesCleanupTaskExecutor
+ Executes the CleanTemporaryFiles task: empties the temporary reading
+ cache directory of the application, failing closed when the directory
+ cannot be resolved safely inside the application base directory.
+end note
+
+' ============================== INFRASTRUCTURE - NOTIFICATIONS ==============================
+
+class ScheduledJobNotifier {
+ - _hubContext: IHubContext
+ + SendScheduledJobsAsync(scheduledJobs: IReadOnlyList, token: CancellationToken): Task
+ + SendScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
+ + SendScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
+}
+
+class ScheduledJobsHub {
+ - _serviceScopeFactory: IServiceScopeFactory
+ + OnConnectedAsync(): Task
+}
+
+note top of ScheduledJobsHub
+ SignalR hub that broadcasts the state of the scheduled jobs and of
+ their executions to the connected administrator clients. Every
+ connection must belong to an administrator account, and is aborted
+ otherwise.
+end note
+
+interface IScheduledJobsClient {
+ + ReceiveScheduledJobsAsync(scheduledJobs: IReadOnlyList): Task
+ + ScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse): Task
+ + ScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse): Task
+}
+
+' ============================== DATA ACCESS - REPOSITORY IMPLEMENTATIONS ==============================
+
+interface IUnitOfWork {
+ + ScheduledJobRepository: IScheduledJobRepository
+ + ScheduledJobExecutionRepository: IScheduledJobExecutionRepository
+ + SaveChangesAsync(token: CancellationToken): Task
+}
+
+class ScheduledJobRepository
+
+class ScheduledJobExecutionRepository
+
+' ============================== STORAGE MODEL ==============================
+
+class ScheduledJobEntity {
+ + Id: Guid
+ + Name: string
+ + TaskType: ScheduledTaskType
+ + ScheduleType: ScheduleType
+ + IntervalMinutes: int?
+ + Hour: int?
+ + Minute: int?
+ + Status: ScheduledJobStatus
+ + OwnerUserId: Guid
+ + LastStartedOnUtc: DateTime?
+ + LastCompletedOnUtc: DateTime?
+}
+
+class ScheduledJobExecutionEntity {
+ + Id: Guid
+ + ScheduledJobId: Guid
+ + TaskType: ScheduledTaskType
+ + IsCycleRun: bool
+ + StartedOnUtc: DateTime
+ + CompletedOnUtc: DateTime?
+}
+
+note bottom of ScheduledJobEntity
+ Stored in the ScheduledJobs table, whose enums are persisted as
+ strings and which is indexed by status so the scheduler can quickly
+ find the active and running cycles at startup.
+end note
+
+note bottom of ScheduledJobExecutionEntity
+ Stored in the ScheduledJobExecutions table, indexed by the started
+ time and the scheduled job id for fast history queries and cleanup.
+end note
+
+' ============================== AGGREGATE AND VALUE OBJECT RELATIONSHIPS ==============================
+
+Schedule <|-- IntervalSchedule : inherits
+Schedule <|-- DailySchedule : inherits
+
+ScheduledJob *-- Schedule : has one
+ScheduledJob o-- ScheduledJobId : identified by
+
+ScheduledJob ..> ScheduledJobAddedDomainEvent : raises
+ScheduledJob ..> ScheduledJobCycleStartedDomainEvent : raises
+ScheduledJob ..> ScheduledJobCycleStoppedDomainEvent : raises
+ScheduledJob ..> ScheduledJobExecutionStartedDomainEvent : raises
+ScheduledJob ..> ScheduledJobExecutionCompletedDomainEvent : raises
+ScheduledJob ..> ScheduledJobExecutionStoppedDomainEvent : raises
+ScheduledJob ..> ScheduledJobFiredDomainEvent : raises
+ScheduledJob ..> ScheduledJobRemovedDomainEvent : raises
+
+' ============================== APPLICATION CONTRACT RELATIONSHIPS ==============================
+
+IScheduledJobScheduler <|.. ScheduledJobSchedulerJob : implements
+IScheduledJobNotifier <|.. ScheduledJobNotifier : implements
+IScheduledJobRepository <|.. ScheduledJobRepository : implements
+IScheduledJobExecutionRepository <|.. ScheduledJobExecutionRepository : implements
+
+' ============================== COMMAND AND QUERY HANDLER RELATIONSHIPS ==============================
+
+AddScheduledJobCommandHandler --> IScheduledJobRepository : inserts
+AddScheduledJobCommandHandler --> Schedule : creates
+AddScheduledJobCommandHandler ..> ScheduledJob : creates
+
+StartScheduledJobCommandHandler --> IScheduledJobRepository : updates status
+StartScheduledJobCommandHandler ..> ScheduledJob : starts the cycle
+StopScheduledJobCommandHandler --> IScheduledJobRepository : updates status
+StopScheduledJobCommandHandler ..> ScheduledJob : stops the cycle
+StopScheduledJobCommandHandler --> IScheduledJobScheduler : stops the running cycle
+FireScheduledJobCommandHandler --> IScheduledJobRepository : reads the job
+FireScheduledJobCommandHandler ..> ScheduledJob : fires the task once
+RemoveScheduledJobCommandHandler --> IScheduledJobRepository : deletes the job
+RemoveScheduledJobCommandHandler --> IScheduledJobExecutionRepository : deletes the executions
+RemoveScheduledJobCommandHandler --> IScheduledJobScheduler : stops the running cycle
+
+GetScheduledJobsQueryHandler --> IScheduledJobRepository : reads all
+GetScheduledJobHistoryQueryHandler --> IScheduledJobExecutionRepository : reads by time range
+
+' ============================== DOMAIN EVENT HANDLER RELATIONSHIPS ==============================
+
+ScheduledJobAddedDomainEventHandler --> IScheduledJobNotifier : notifies
+ScheduledJobCycleStartedDomainEventHandler --> IScheduledJobScheduler : starts the cycle
+ScheduledJobCycleStartedDomainEventHandler --> IScheduledJobNotifier : notifies
+ScheduledJobCycleStoppedDomainEventHandler --> IScheduledJobNotifier : notifies
+ScheduledJobFiredDomainEventHandler --> IScheduledJobScheduler : fires the task once
+ScheduledJobRemovedDomainEventHandler --> IScheduledJobNotifier : notifies
+
+ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobRepository : updates to Running
+ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobExecutionRepository : inserts the execution
+ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobNotifier : notifies the started execution
+ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobRepository : restores or completes
+ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobExecutionRepository : closes the execution
+ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobNotifier : notifies the completed execution
+ScheduledJobExecutionStoppedDomainEventHandler --> IScheduledJobExecutionRepository : closes the open execution
+ScheduledJobExecutionStoppedDomainEventHandler --> IScheduledJobNotifier : notifies
+
+' ============================== SCHEDULER EXECUTION RELATIONSHIPS ==============================
+
+ScheduledJobSchedulerJob --> IScheduledJobRuntimeRegistry : tracks cycles and run slots
+ScheduledJobSchedulerJob --> IScheduledJobRepository : loads jobs and schedules
+ScheduledJobSchedulerJob ..> ScheduledJobExecutionStartedDomainEvent : publishes
+ScheduledJobSchedulerJob ..> ScheduledJobExecutionCompletedDomainEvent : publishes
+ScheduledJobSchedulerJob ..> ScheduledJob : marks the execution started and completed
+
+IScheduledJobRuntimeRegistry <|.. ScheduledJobRuntimeRegistry : implements
+
+ScheduledJobSchedulerJob --> IScheduledTaskExecutorFactory : creates the task executor
+IScheduledTaskExecutorFactory <|.. ScheduledTaskExecutorFactory : implements
+
+ScheduledTaskExecutorFactory ..> MediaLibraryScanTaskExecutor : creates for ScanMediaLibraries
+ScheduledTaskExecutorFactory ..> TemporaryFilesCleanupTaskExecutor : creates for CleanTemporaryFiles
+
+IScheduledTaskExecutor <|.. MediaLibraryScanTaskExecutor : implements
+IScheduledTaskExecutor <|.. TemporaryFilesCleanupTaskExecutor : implements
+
+MediaLibraryScanTaskExecutor --> IUnitOfWork : queues the library scans of the owner
+
+' ============================== NOTIFICATION RELATIONSHIPS ==============================
+
+IScheduledJobNotifier <|.. ScheduledJobNotifier : implements
+ScheduledJobNotifier --> ScheduledJobsHub : broadcasts to SignalR clients
+ScheduledJobsHub --> IScheduledJobsClient : typed client contract
+
+' ============================== STORAGE RELATIONSHIPS ==============================
+
+ScheduledJobRepository --> ScheduledJobEntity : persists
+ScheduledJobExecutionRepository --> ScheduledJobExecutionEntity : persists
+
+caption [Code] Lumina - Scheduled Jobs 3.2.3
+
+footer The code diagram for the Scheduled Jobs 3.2.3 - created with PlantUML
+@enduml
diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.svg b/docs/technical/architecture/4.3 code-scheduler-diagram.svg
new file mode 100644
index 00000000..65824eac
--- /dev/null
+++ b/docs/technical/architecture/4.3 code-scheduler-diagram.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/technical/requests/scheduling/AddScheduledJob.http b/docs/technical/requests/scheduling/AddScheduledJob.http
new file mode 100644
index 00000000..11a44fdc
--- /dev/null
+++ b/docs/technical/requests/scheduling/AddScheduledJob.http
@@ -0,0 +1,12 @@
+POST {{host}}/api/v1/scheduled-jobs
+Authorization: Bearer {{ACCESS_TOKEN}}
+Content-Type: application/json
+
+{
+ "name": "Rescan media libraries",
+ "taskType": "ScanMediaLibraries",
+ "scheduleType": "DailyAtHourAndMinute",
+ "intervalMinutes": null,
+ "hour": 3,
+ "minute": 0
+}
diff --git a/docs/technical/requests/scheduling/FireScheduledJob.http b/docs/technical/requests/scheduling/FireScheduledJob.http
new file mode 100644
index 00000000..dd619c4a
--- /dev/null
+++ b/docs/technical/requests/scheduling/FireScheduledJob.http
@@ -0,0 +1,2 @@
+PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/fire
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/GetScheduledJobHistory.http b/docs/technical/requests/scheduling/GetScheduledJobHistory.http
new file mode 100644
index 00000000..2868c025
--- /dev/null
+++ b/docs/technical/requests/scheduling/GetScheduledJobHistory.http
@@ -0,0 +1,2 @@
+GET {{host}}/api/v1/scheduled-jobs/history?from=2026-09-02T00%3A00%3A00.0000000Z&to=2026-09-03T00%3A00%3A00.0000000Z
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/GetScheduledJobs.http b/docs/technical/requests/scheduling/GetScheduledJobs.http
new file mode 100644
index 00000000..806227a5
--- /dev/null
+++ b/docs/technical/requests/scheduling/GetScheduledJobs.http
@@ -0,0 +1,2 @@
+GET {{host}}/api/v1/scheduled-jobs
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/GetSchedulerDisplayPreferences.http b/docs/technical/requests/scheduling/GetSchedulerDisplayPreferences.http
new file mode 100644
index 00000000..99e15c76
--- /dev/null
+++ b/docs/technical/requests/scheduling/GetSchedulerDisplayPreferences.http
@@ -0,0 +1,2 @@
+GET {{host}}/api/v1/scheduled-jobs/display-preferences
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/RemoveScheduledJob.http b/docs/technical/requests/scheduling/RemoveScheduledJob.http
new file mode 100644
index 00000000..3477d56c
--- /dev/null
+++ b/docs/technical/requests/scheduling/RemoveScheduledJob.http
@@ -0,0 +1,2 @@
+DELETE {{host}}/api/v1/scheduled-jobs/{{$guid}}
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/StartScheduledJob.http b/docs/technical/requests/scheduling/StartScheduledJob.http
new file mode 100644
index 00000000..507327a1
--- /dev/null
+++ b/docs/technical/requests/scheduling/StartScheduledJob.http
@@ -0,0 +1,2 @@
+PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/start
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/StopScheduledJob.http b/docs/technical/requests/scheduling/StopScheduledJob.http
new file mode 100644
index 00000000..8da586ed
--- /dev/null
+++ b/docs/technical/requests/scheduling/StopScheduledJob.http
@@ -0,0 +1,2 @@
+PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/stop
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http b/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http
new file mode 100644
index 00000000..16d64d14
--- /dev/null
+++ b/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http
@@ -0,0 +1,9 @@
+PUT {{host}}/api/v1/scheduled-jobs/display-preferences
+Authorization: Bearer {{ACCESS_TOKEN}}
+Content-Type: application/json
+
+{
+ "jobTypeFilter": "ScanMediaLibraries",
+ "displayTimeSpan": 10,
+ "displayTimeUnit": "Minutes"
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs
new file mode 100644
index 00000000..5bf2c72d
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs
@@ -0,0 +1,90 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
+
+///
+/// Repository entity for a scheduled job.
+///
+[DebuggerDisplay("Id: {Id}, Status: {Status}")]
+public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets the Id of the scheduled job.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets the name of the scheduled job.
+ ///
+ public required string Name { get; init; }
+
+ ///
+ /// Gets the type of the task executed by the scheduled job.
+ ///
+ public required ScheduledTaskType TaskType { get; init; }
+
+ ///
+ /// Gets the type of the schedule of the scheduled job.
+ ///
+ public required ScheduleType ScheduleType { get; init; }
+
+ ///
+ /// Gets the interval in minutes of the schedule of the scheduled job, when its is .
+ ///
+ public int? IntervalMinutes { get; init; }
+
+ ///
+ /// Gets the hour of the schedule of the scheduled job, when its is .
+ ///
+ public int? Hour { get; init; }
+
+ ///
+ /// Gets the minute of the schedule of the scheduled job, when its is .
+ ///
+ public int? Minute { get; init; }
+
+ ///
+ /// Gets the status of the scheduled job.
+ ///
+ public required ScheduledJobStatus Status { get; init; }
+
+ ///
+ /// Gets the Id of the user that owns the scheduled job.
+ ///
+ public required Guid OwnerUserId { get; init; }
+
+ ///
+ /// Gets the optional date and time when the task of the scheduled job last started its execution.
+ ///
+ public DateTime? LastStartedOnUtc { get; init; }
+
+ ///
+ /// Gets the optional date and time when the task of the scheduled job last completed its execution.
+ ///
+ public DateTime? LastCompletedOnUtc { get; init; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs
new file mode 100644
index 00000000..5bf05e66
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs
@@ -0,0 +1,75 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
+
+///
+/// Repository entity for an execution of the task of a scheduled job.
+///
+[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
+public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets the Id of the execution of the task of a scheduled job.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets the Id of the scheduled job whose task was executed.
+ ///
+ public required Guid ScheduledJobId { get; init; }
+
+ ///
+ /// Gets the type of the task that was executed.
+ ///
+ public required ScheduledTaskType TaskType { get; init; }
+
+ ///
+ /// Gets a value indicating whether the execution was triggered by the execution cycle of the scheduled job, or it was a one time execution.
+ ///
+ public required bool IsCycleRun { get; init; }
+
+ ///
+ /// Gets the date and time when the execution started.
+ ///
+ public required DateTime StartedOnUtc { get; init; }
+
+ ///
+ /// Gets the optional date and time when the execution completed.
+ ///
+ public DateTime? CompletedOnUtc { get; init; }
+
+ ///
+ /// Gets a value indicating whether the execution cycle of the scheduled job was active when the execution started.
+ ///
+ ///
+ /// A job whose execution cycle is active stays in its active state while a manually fired one time execution runs, so an
+ /// interrupted execution of such a job must return it to its active state at the next startup; the flag keeps that fact
+ /// separate from , which records how the execution was triggered for the audit trail.
+ ///
+ public required bool WasCycleActive { get; init; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs
new file mode 100644
index 00000000..7cdfea0d
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
+
+///
+/// Repository entity for the display preferences of the scheduler page of a user.
+///
+[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan}")]
+public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets or sets the Id of the display preferences.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets or sets the Id of the user that owns the display preferences.
+ ///
+ public required Guid UserId { get; set; }
+
+ ///
+ /// Gets or sets the type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown.
+ ///
+ public ScheduledTaskType? JobTypeFilter { get; set; }
+
+ ///
+ /// Gets or sets the time span, expressed in , that the scheduler page shows.
+ ///
+ public required int DisplayTimeSpan { get; set; }
+
+ ///
+ /// Gets or sets the unit in which the displayed time span of the scheduler page is expressed.
+ ///
+ public required SchedulerDisplayTimeUnit DisplayTimeUnit { get; set; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs
new file mode 100644
index 00000000..a01a7f7e
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
+
+///
+/// Interface for the repository for the executions of the tasks of scheduled jobs.
+///
+public interface IScheduledJobExecutionRepository : IRepository,
+ IGetByIdRepositoryAction,
+ IInsertRepositoryAction,
+ IUpdateRepositoryAction
+{
+ ///
+ /// Gets the most recent execution of the task of a scheduled job identified by that is still running, from the storage medium.
+ ///
+ /// The Id of the scheduled job whose running execution is retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the running execution of the scheduled job, or .
+ Task> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Gets the executions of the tasks of scheduled jobs that started in the interval between and , from the storage medium.
+ ///
+ /// The inclusive lower bound of the interval, in UTC.
+ /// The inclusive upper bound of the interval, in UTC.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken);
+
+ ///
+ /// Removes all the executions of the task of a scheduled job identified by , from the storage medium.
+ ///
+ /// The Id of the scheduled job whose executions are removed.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Removes all the executions of the tasks of scheduled jobs that started before , from the storage medium.
+ ///
+ /// The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs
new file mode 100644
index 00000000..84138240
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs
@@ -0,0 +1,39 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
+
+///
+/// Interface for the repository for scheduled jobs.
+///
+public interface IScheduledJobRepository : IRepository,
+ IGetByIdRepositoryAction,
+ IGetAllRepositoryAction,
+ IInsertRepositoryAction,
+ IUpdateRepositoryAction,
+ IDeleteByIdRepositoryAction
+{
+ ///
+ /// Gets a scheduled job identified by from the storage medium, without tracking it.
+ ///
+ /// The id of the scheduled job to get.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a identified by , or an error.
+ Task> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken);
+
+ ///
+ /// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetActiveOrRunningAsync(CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs
new file mode 100644
index 00000000..c574e898
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
+
+///
+/// Interface for the repository for the display preferences of the scheduler page.
+///
+public interface ISchedulerDisplayPreferencesRepository : IRepository
+{
+ ///
+ /// Gets the display preferences of the scheduler page of the user identified by , if they exist.
+ ///
+ /// The Id of the user whose display preferences are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the display preferences of the user, or an error.
+ Task> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken);
+
+ ///
+ /// Inserts the display preferences of the scheduler page of a user, or updates them when they already exist.
+ ///
+ /// The display preferences to insert or update.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> UpsertAsync(SchedulerDisplayPreferencesEntity preferences, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs
index da3303cb..4314abbe 100644
--- a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs
+++ b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs
@@ -43,4 +43,12 @@ public interface IDataSeedService
/// Cancellation token that can be used to stop the execution.
/// An representing either a successful operation, or an error.
Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken);
+
+ ///
+ /// Sets up the default scheduled jobs, owned by the administrator account.
+ ///
+ /// The unique identifier of the administrator account that owns the default scheduled jobs.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken);
}
diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
index f748d5dd..9c4c7407 100644
--- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
+++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
+using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using System.Threading;
@@ -87,6 +88,21 @@ public interface IUnitOfWork
///
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
+ ///
+ /// Gets the scheduled job repository.
+ ///
+ IScheduledJobRepository ScheduledJobRepository { get; }
+
+ ///
+ /// Gets the scheduled job execution repository.
+ ///
+ IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get; }
+
+ ///
+ /// Gets the scheduler display preferences repository.
+ ///
+ ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository { get; }
+
///
/// Gets the plugin repository.
///
diff --git a/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs
new file mode 100644
index 00000000..15828b20
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Scheduling;
+
+///
+/// Interface for the service that schedules and executes the tasks of scheduled jobs.
+///
+public interface IScheduledJobScheduler
+{
+ ///
+ /// Starts the execution cycle of the scheduled job identified by .
+ ///
+ /// The object representing the unique identifier of the scheduled job whose execution cycle is started.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Stops the execution cycle of the scheduled job identified by .
+ ///
+ /// The object representing the unique identifier of the scheduled job whose execution cycle is stopped.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+
+ ///
+ /// Fires the task of the scheduled job identified by once, without affecting its execution cycle.
+ ///
+ /// The object representing the unique identifier of the scheduled job whose task is fired.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..9bba28d0
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class AddScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static AddScheduledJobCommand ToCommand(this AddScheduledJobRequest request)
+ {
+ return new AddScheduledJobCommand(
+ request.Name,
+ request.TaskType,
+ request.ScheduleType,
+ request.IntervalMinutes,
+ request.Hour,
+ request.Minute
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..d00d8df1
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class FireScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static FireScheduledJobCommand ToCommand(this FireScheduledJobRequest request)
+ {
+ return new FireScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs
new file mode 100644
index 00000000..0a3ae563
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class GetScheduledJobHistoryRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetScheduledJobHistoryQuery ToQuery(this GetScheduledJobHistoryRequest request)
+ {
+ return new GetScheduledJobHistoryQuery(
+ request.From,
+ request.To
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..ea6432a9
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class RemoveScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static RemoveScheduledJobCommand ToCommand(this RemoveScheduledJobRequest request)
+ {
+ return new RemoveScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
new file mode 100644
index 00000000..23734cb6
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs
@@ -0,0 +1,110 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobEntityMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ ///
+ /// An containing either a converted , or an error message.
+ ///
+ public static Result ToDomainEntity(this ScheduledJobEntity repositoryEntity)
+ {
+ Result scheduleResult = CreateSchedule(repositoryEntity);
+ if (scheduleResult.IsFailure)
+ return scheduleResult.Errors;
+
+ return ScheduledJob.Create(
+ ScheduledJobId.Create(repositoryEntity.Id),
+ repositoryEntity.Name,
+ repositoryEntity.TaskType,
+ scheduleResult.Value,
+ UserId.Create(repositoryEntity.OwnerUserId),
+ repositoryEntity.Status,
+ Optional.FromNullable(repositoryEntity.LastStartedOnUtc),
+ Optional.FromNullable(repositoryEntity.LastCompletedOnUtc)
+ );
+ }
+
+ ///
+ /// Converts to a collection of .
+ ///
+ /// The repository entities to be converted.
+ ///
+ /// An containing either a collection of converted , or an error message.
+ ///
+ public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities)
+ {
+ return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity());
+ }
+
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The converted scheduled job response.
+ public static ScheduledJobResponse ToResponse(this ScheduledJobEntity repositoryEntity)
+ {
+ return new ScheduledJobResponse(
+ repositoryEntity.Id,
+ repositoryEntity.Name,
+ repositoryEntity.TaskType,
+ repositoryEntity.ScheduleType,
+ repositoryEntity.IntervalMinutes,
+ repositoryEntity.Hour,
+ repositoryEntity.Minute,
+ repositoryEntity.Status,
+ repositoryEntity.LastStartedOnUtc,
+ repositoryEntity.LastCompletedOnUtc
+ );
+ }
+
+ ///
+ /// Creates the schedule of from its flattened schedule properties.
+ ///
+ /// The repository entity whose schedule is created.
+ ///
+ /// An containing either a created , or an error message.
+ ///
+ private static Result CreateSchedule(ScheduledJobEntity repositoryEntity)
+ {
+ if (repositoryEntity.ScheduleType == ScheduleType.WithIntervalInMinutes)
+ {
+ Result intervalScheduleResult = IntervalSchedule.Create(repositoryEntity.IntervalMinutes ?? 0);
+ if (intervalScheduleResult.IsFailure)
+ return intervalScheduleResult.Errors;
+ return Result.From(intervalScheduleResult.Value);
+ }
+
+ if (repositoryEntity.ScheduleType == ScheduleType.OnceAtStartup)
+ {
+ Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
+ if (onceAtStartupScheduleResult.IsFailure)
+ return onceAtStartupScheduleResult.Errors;
+ return Result.From(onceAtStartupScheduleResult.Value);
+ }
+
+ Result dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0);
+ if (dailyScheduleResult.IsFailure)
+ return dailyScheduleResult.Errors;
+ return Result.From(dailyScheduleResult.Value);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
new file mode 100644
index 00000000..2ac77c66
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobExecutionEntityMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The converted execution response.
+ public static ScheduledJobExecutionResponse ToResponse(this ScheduledJobExecutionEntity repositoryEntity)
+ {
+ return new ScheduledJobExecutionResponse(
+ repositoryEntity.Id,
+ repositoryEntity.ScheduledJobId,
+ repositoryEntity.TaskType,
+ repositoryEntity.IsCycleRun,
+ repositoryEntity.StartedOnUtc,
+ repositoryEntity.CompletedOnUtc
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs
new file mode 100644
index 00000000..3099ea14
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs
@@ -0,0 +1,93 @@
+#region ========================================================================= USING =====================================================================================
+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;
+
+///
+/// Extension methods for converting .
+///
+public static class ScheduledJobMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The domain entity to be converted.
+ /// The converted repository entity.
+ public static ScheduledJobEntity ToRepositoryEntity(this ScheduledJob domainEntity)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = domainEntity.Id.Value,
+ Name = domainEntity.Name,
+ TaskType = domainEntity.TaskType,
+ ScheduleType = domainEntity.Schedule.ScheduleType,
+ IntervalMinutes = GetIntervalMinutes(domainEntity),
+ Hour = GetHour(domainEntity),
+ Minute = GetMinute(domainEntity),
+ 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,
+ UpdatedBy = Guid.Empty
+ };
+ }
+
+ ///
+ /// Converts to .
+ ///
+ /// The domain entity to be converted.
+ /// The converted scheduled job response.
+ public static ScheduledJobResponse ToResponse(this ScheduledJob domainEntity)
+ {
+ return new ScheduledJobResponse(
+ domainEntity.Id.Value,
+ domainEntity.Name,
+ domainEntity.TaskType,
+ domainEntity.Schedule.ScheduleType,
+ GetIntervalMinutes(domainEntity),
+ GetHour(domainEntity),
+ GetMinute(domainEntity),
+ domainEntity.Status,
+ domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
+ domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null
+ );
+ }
+
+ ///
+ /// Gets the interval in minutes of the schedule of , when it is an interval schedule.
+ ///
+ /// The scheduled job whose schedule interval is retrieved.
+ /// The interval in minutes of the schedule, or when the schedule is not an interval schedule.
+ private static int? GetIntervalMinutes(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is IntervalSchedule intervalSchedule ? intervalSchedule.IntervalMinutes : null;
+ }
+
+ ///
+ /// Gets the hour of the schedule of , when it is a daily schedule.
+ ///
+ /// The scheduled job whose schedule hour is retrieved.
+ /// The hour of the schedule, or when the schedule is not a daily schedule.
+ private static int? GetHour(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Hour : null;
+ }
+
+ ///
+ /// Gets the minute of the schedule of , when it is a daily schedule.
+ ///
+ /// The scheduled job whose schedule minute is retrieved.
+ /// The minute of the schedule, or when the schedule is not a daily schedule.
+ private static int? GetMinute(ScheduledJob domainEntity)
+ {
+ return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Minute : null;
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs
new file mode 100644
index 00000000..0e01d898
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class SchedulerDisplayPreferencesEntityMapping
+{
+ private const int DEFAULT_DISPLAY_TIME_SPAN = 10;
+ private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes;
+
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The converted response.
+ public static SchedulerDisplayPreferencesResponse ToResponse(this SchedulerDisplayPreferencesEntity repositoryEntity)
+ {
+ return new SchedulerDisplayPreferencesResponse(
+ repositoryEntity.UserId,
+ repositoryEntity.JobTypeFilter,
+ repositoryEntity.DisplayTimeSpan,
+ repositoryEntity.DisplayTimeUnit
+ );
+ }
+
+ ///
+ /// Converts the lack of stored display preferences to the default of the user identified by .
+ ///
+ /// The missing repository entity, which is .
+ /// The Id of the user that owns the display preferences.
+ /// The converted response with the default display preferences.
+ public static SchedulerDisplayPreferencesResponse ToDefaultResponse(this SchedulerDisplayPreferencesEntity? repositoryEntity, Guid userId)
+ {
+ return new SchedulerDisplayPreferencesResponse(
+ userId,
+ null,
+ DEFAULT_DISPLAY_TIME_SPAN,
+ DEFAULT_DISPLAY_TIME_UNIT
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..067665ec
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class StartScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static StartScheduledJobCommand ToCommand(this StartScheduledJobRequest request)
+ {
+ return new StartScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs
new file mode 100644
index 00000000..488a699a
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class StopScheduledJobRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static StopScheduledJobCommand ToCommand(this StopScheduledJobRequest request)
+ {
+ return new StopScheduledJobCommand(
+ request.ScheduledJobId
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs
new file mode 100644
index 00000000..f0e74408
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
+using Lumina.Contracts.Requests.Scheduling;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.Scheduling;
+
+///
+/// Extension methods for converting .
+///
+public static class UpdateSchedulerDisplayPreferencesRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static UpdateSchedulerDisplayPreferencesCommand ToCommand(this UpdateSchedulerDisplayPreferencesRequest request)
+ {
+ return new UpdateSchedulerDisplayPreferencesCommand(
+ request.JobTypeFilter,
+ request.DisplayTimeSpan,
+ request.DisplayTimeUnit
+ );
+ }
+}
diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs
index fdc1df53..47a8a836 100644
--- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs
+++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs
@@ -1,16 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Seed;
using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
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 Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -32,6 +37,7 @@ public class SetupApplicationCommandHandler : ICommandHandler _validator;
///
@@ -44,6 +50,7 @@ public class SetupApplicationCommandHandler : ICommandHandlerInjected service for generating QR codes.
/// Injected service for time related concerns.
/// Injected service for the initial persistence medium data seed.
+ /// Injected service for the queue of domain events.
/// Injected validator for application validation rules.
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
@@ -53,6 +60,7 @@ public class SetupApplicationCommandHandler : ICommandHandler validator)
{
_unitOfWork = unitOfWork;
@@ -62,6 +70,7 @@ public class SetupApplicationCommandHandler : ICommandHandler 0)
return validationResult;
- // check if any users already exists (admin account is only set once!)
+ // Check if any users already exists (admin account is only set once!).
Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (selectUsersResult.IsFailure)
return selectUsersResult.Errors;
@@ -100,23 +109,23 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (insertUserResult.IsFailure)
return insertUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
- // set the default permissions, roles, roles permissions
+ // Set the default permissions, roles, roles permissions.
Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false);
if (setPermissionsResult.IsFailure)
return setPermissionsResult.Errors;
@@ -133,8 +142,23 @@ public class SetupApplicationCommandHandler : ICommandHandler setDefaultScheduledJobsResult = await _dataSeedService.SetDefaultScheduledJobsAsync(id, cancellationToken).ConfigureAwait(false);
+ if (setDefaultScheduledJobsResult.IsFailure)
+ return setDefaultScheduledJobsResult.Errors;
+
+ // The default jobs were seeded with an active execution cycle, so a cycle started event is queued for each of them; the
+ // queued events are published only after the setup transaction commits, because a cycle worker started inside the request
+ // would try to read the scheduled jobs while the still open setup transaction locks the storage medium.
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ return getScheduledJobsResult.Errors;
+ foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value)
+ if (scheduledJob.Status == ScheduledJobStatus.Active)
+ _domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow));
+
+ // TODO: insert the default admin profile preferences when they are implemented.
+ // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
return new RegistrationResponse(user.Id, user.Username, totpSecret);
}
}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs
new file mode 100644
index 00000000..becfb43d
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Command for adding a scheduled job.
+///
+/// The name of the scheduled job.
+/// The type of the task executed by the scheduled job.
+/// The type of the schedule of the scheduled job.
+/// The interval in minutes of the schedule, when the schedule type is .
+/// The hour of the schedule, when the schedule type is .
+/// The minute of the schedule, when the schedule type is .
+[DebuggerDisplay("Name: {Name}")]
+public record AddScheduledJobCommand(
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..02151efa
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs
@@ -0,0 +1,129 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Handler for the command to add a scheduled job.
+///
+public class AddScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public AddScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to add a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a successfully created , or an error message.
+ ///
+ public async Task> HandleAsync(AddScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can schedule jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Create the schedule of the scheduled job, based on its type.
+ Result scheduleResult;
+ if (command.ScheduleType == ScheduleType.WithIntervalInMinutes)
+ {
+ Result intervalScheduleResult = IntervalSchedule.Create(command.IntervalMinutes ?? 0);
+ if (intervalScheduleResult.IsFailure)
+ return intervalScheduleResult.Errors;
+ scheduleResult = Result.From(intervalScheduleResult.Value);
+ }
+ else if (command.ScheduleType == ScheduleType.DailyAtHourAndMinute)
+ {
+ Result dailyScheduleResult = DailySchedule.Create(command.Hour ?? 0, command.Minute ?? 0);
+ if (dailyScheduleResult.IsFailure)
+ return dailyScheduleResult.Errors;
+ scheduleResult = Result.From(dailyScheduleResult.Value);
+ }
+ else if (command.ScheduleType == ScheduleType.OnceAtStartup)
+ {
+ Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
+ if (onceAtStartupScheduleResult.IsFailure)
+ return onceAtStartupScheduleResult.Errors;
+ scheduleResult = Result.From(onceAtStartupScheduleResult.Value);
+ }
+ else
+ return DomainErrors.Scheduling.InvalidScheduleType;
+
+ // Create a domain scheduled job object.
+ Result createScheduledJobResult = ScheduledJob.Create(command.Name, command.TaskType, scheduleResult.Value, UserId.Create(userId));
+ if (createScheduledJobResult.IsFailure)
+ return createScheduledJobResult.Errors;
+ createScheduledJobResult.Value.Add();
+
+ // Convert the domain scheduled job to a repository entity, insert it, and save the changes.
+ ScheduledJobEntity persistenceScheduledJob = createScheduledJobResult.Value.ToRepositoryEntity();
+ Result insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (insertScheduledJobResult.IsFailure)
+ return insertScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return createScheduledJobResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..04a30b31
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs
@@ -0,0 +1,64 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class AddScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public AddScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.Name)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty)
+ .MaximumLength(80)
+ .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
+
+ RuleFor(command => command.TaskType)
+ .IsInEnum()
+ .WithError(Errors.Scheduling.InvalidScheduleType);
+
+ RuleFor(command => command.ScheduleType)
+ .IsInEnum()
+ .WithError(Errors.Scheduling.InvalidScheduleType);
+
+ RuleFor(command => command.IntervalMinutes)
+ .Must(intervalMinutes => intervalMinutes is null || intervalMinutes > 0)
+ .WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
+ .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
+
+ RuleFor(command => command.IntervalMinutes)
+ .Must(intervalMinutes => intervalMinutes is not null)
+ .WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
+ .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
+
+ RuleFor(command => command.Hour)
+ .Must(hour => hour is not null)
+ .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Minute)
+ .Must(minute => minute is not null)
+ .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Hour)
+ .InclusiveBetween(0, 23)
+ .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+
+ RuleFor(command => command.Minute)
+ .InclusiveBetween(0, 59)
+ .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
+ .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs
new file mode 100644
index 00000000..f10430d1
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Command for firing the task of a scheduled job once, without affecting its execution cycle.
+///
+/// The unique identifier of the scheduled job whose task is fired.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record FireScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..86585082
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Handler for the command to fire the task of a scheduled job once.
+///
+public class FireScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public FireScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to fire the task of a scheduled job once.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(FireScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can fire scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and guard the fire against a currently running task.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result fireResult = scheduledJobDomainResult.Value.Fire();
+ if (fireResult.IsFailure)
+ return fireResult.Errors;
+
+ // Queue the domain event that requests a one time execution of the task of the scheduled job.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..425b31ee
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class FireScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public FireScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs
new file mode 100644
index 00000000..ff0e74c8
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Command for removing a scheduled job.
+///
+/// The unique identifier of the scheduled job to remove.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record RemoveScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..ba19721c
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Handler for the command to remove a scheduled job.
+///
+public class RemoveScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public RemoveScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IScheduledJobScheduler scheduledJobScheduler,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to remove a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An representing either a successful operation, or an error.
+ ///
+ public async Task> HandleAsync(RemoveScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can remove scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Stop the execution cycle of the scheduled job, if it has one.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
+
+ // Remove the executions and the scheduled job itself from the storage medium.
+ Result deleteExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (deleteExecutionsResult.IsFailure)
+ return deleteExecutionsResult.Errors;
+ Result deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (deleteScheduledJobResult.IsFailure)
+ return deleteScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ scheduledJobDomainResult.Value.Remove();
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..8980ee94
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class RemoveScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public RemoveScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs
new file mode 100644
index 00000000..14b8203b
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Command for starting the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is started.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StartScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..f5c0be2f
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs
@@ -0,0 +1,109 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Handler for the command to start the execution cycle of a scheduled job.
+///
+public class StartScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public StartScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to start the execution cycle of a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(StartScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can start scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and start its execution cycle.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result startCycleResult = scheduledJobDomainResult.Value.StartCycle();
+ if (startCycleResult.IsFailure)
+ return startCycleResult.Errors;
+
+ // Persist the new status of the scheduled job.
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ return updateScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..2b09e00b
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StartScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StartScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs
new file mode 100644
index 00000000..2ee36eed
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Command for stopping the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is stopped.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StopScheduledJobCommand(
+ Guid ScheduledJobId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs
new file mode 100644
index 00000000..177e0865
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs
@@ -0,0 +1,116 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Handler for the command to stop the execution cycle of a scheduled job.
+///
+public class StopScheduledJobCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public StopScheduledJobCommandHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IScheduledJobScheduler scheduledJobScheduler,
+ IUnitOfWork unitOfWork,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to stop the execution cycle of a scheduled job.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a , or an error message.
+ ///
+ public async Task> HandleAsync(StopScheduledJobCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can stop scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled job from the storage medium.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ return getScheduledJobResult.Errors;
+ if (getScheduledJobResult.Value is null)
+ return DomainErrors.Scheduling.ScheduledJobNotFound;
+
+ // Convert the repository entity to a domain entity, and stop its execution cycle.
+ Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
+ if (scheduledJobDomainResult.IsFailure)
+ return scheduledJobDomainResult.Errors;
+ Result stopCycleResult = scheduledJobDomainResult.Value.StopCycle();
+ if (stopCycleResult.IsFailure)
+ return stopCycleResult.Errors;
+
+ // Persist the new status of the scheduled job.
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ return updateScheduledJobResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Stop the execution cycle in the scheduler service.
+ await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
+
+ // Queue any domain events.
+ foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
+ _domainEventsQueue.Enqueue(domainEvent);
+
+ return scheduledJobDomainResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs
new file mode 100644
index 00000000..03681f46
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StopScheduledJobCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StopScheduledJobCommandValidator()
+ {
+ RuleFor(command => command.ScheduledJobId)
+ .NotEmpty()
+ .WithError(Errors.Scheduling.ScheduledJobNotFound);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs
new file mode 100644
index 00000000..2115f817
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
+
+///
+/// Command for updating the display preferences of the scheduler page of the current user.
+///
+/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown.
+/// The time span, expressed in , that the scheduler page shows.
+/// The unit in which the displayed time span of the scheduler page is expressed.
+[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
+public record UpdateSchedulerDisplayPreferencesCommand(
+ ScheduledTaskType? JobTypeFilter,
+ int DisplayTimeSpan,
+ SchedulerDisplayTimeUnit DisplayTimeUnit
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs
new file mode 100644
index 00000000..54c6fa4b
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
+
+///
+/// Handler for the command to update the display preferences of the scheduler page of the current user.
+///
+public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler>
+{
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public UpdateSchedulerDisplayPreferencesCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
+ {
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _unitOfWork = unitOfWork;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to update the display preferences of the scheduler page of the current user.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An representing either a successful update, or an error.
+ ///
+ public async Task> HandleAsync(UpdateSchedulerDisplayPreferencesCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can use the scheduler page.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Upsert the display preferences of the scheduler page of the current user.
+ SchedulerDisplayPreferencesEntity displayPreferences = new()
+ {
+ Id = Guid.NewGuid(),
+ UserId = userId,
+ JobTypeFilter = command.JobTypeFilter,
+ DisplayTimeSpan = command.DisplayTimeSpan,
+ DisplayTimeUnit = command.DisplayTimeUnit,
+ CreatedOnUtc = default,
+ CreatedBy = default,
+ UpdatedOnUtc = null,
+ UpdatedBy = null
+ };
+ Result upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false);
+ if (upsertResult.IsFailure)
+ return upsertResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ return Result.Updated;
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs
new file mode 100644
index 00000000..6dea97e1
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
+
+///
+/// Validates the needed validation rules for .
+///
+public class UpdateSchedulerDisplayPreferencesCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateSchedulerDisplayPreferencesCommandValidator()
+ {
+ RuleFor(command => command.DisplayTimeSpan)
+ .GreaterThan(0)
+ .WithError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs
new file mode 100644
index 00000000..4a523bd2
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when a scheduled job is added.
+///
+public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when a scheduled job is added.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs
new file mode 100644
index 00000000..974f02ed
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution cycle of a scheduled job is started.
+///
+public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobCycleStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IScheduledJobScheduler scheduledJobScheduler, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ _scheduledJobScheduler = scheduledJobScheduler;
+ }
+
+ ///
+ /// Handles the event raised when the execution cycle of a scheduled job is started.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobCycleStartedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Start the execution cycle in the scheduler service, which runs the task of the scheduled job once immediately and then on its schedule.
+ await _scheduledJobScheduler.StartCycleAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs
new file mode 100644
index 00000000..a04da146
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution cycle of a scheduled job is stopped.
+///
+public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobCycleStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the execution cycle of a scheduled job is stopped.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs
new file mode 100644
index 00000000..6d2df8ee
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs
@@ -0,0 +1,148 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job completes its execution.
+///
+public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionCompletedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job completes its execution.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Get the scheduled job from the repository.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
+ if (getScheduledJobResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
+ ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
+
+ // A cycle run returns the scheduled job to its active status, a one time execution completes it.
+ ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed;
+ ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc);
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
+
+ // Mark the execution of the task of the scheduled job as completed.
+ Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false);
+ if (getExecutionResult.IsFailure)
+ throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors);
+ if (getExecutionResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound);
+ ScheduledJobExecutionEntity execution = getExecutionResult.Value;
+ ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc);
+ Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
+ if (updateExecutionResult.IsFailure)
+ throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Notify the SignalR clients about the current scheduled jobs and the completed execution.
+ await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
+ await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Creates a copy of with the provided status and timestamps.
+ ///
+ /// The scheduled job to copy.
+ /// The status of the copy.
+ /// The last start time of the copy.
+ /// The last completion time of the copy.
+ /// The copy of the scheduled job.
+ private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = scheduledJob.Id,
+ Name = scheduledJob.Name,
+ TaskType = scheduledJob.TaskType,
+ ScheduleType = scheduledJob.ScheduleType,
+ IntervalMinutes = scheduledJob.IntervalMinutes,
+ Hour = scheduledJob.Hour,
+ Minute = scheduledJob.Minute,
+ Status = status,
+ OwnerUserId = scheduledJob.OwnerUserId,
+ LastStartedOnUtc = lastStartedOnUtc,
+ LastCompletedOnUtc = lastCompletedOnUtc,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
+ UpdatedBy = scheduledJob.UpdatedBy
+ };
+ }
+
+ ///
+ /// Creates a copy of with the provided completion time.
+ ///
+ /// The execution to copy.
+ /// The completion time of the copy.
+ /// The copy of the execution.
+ private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
+ {
+ return new ScheduledJobExecutionEntity
+ {
+ Id = execution.Id,
+ ScheduledJobId = execution.ScheduledJobId,
+ TaskType = execution.TaskType,
+ IsCycleRun = execution.IsCycleRun,
+ WasCycleActive = execution.WasCycleActive,
+ StartedOnUtc = execution.StartedOnUtc,
+ CompletedOnUtc = completedOnUtc,
+ CreatedOnUtc = execution.CreatedOnUtc,
+ CreatedBy = execution.CreatedBy,
+ UpdatedOnUtc = execution.UpdatedOnUtc,
+ UpdatedBy = execution.UpdatedBy
+ };
+ }
+
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs
new file mode 100644
index 00000000..2e81591f
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs
@@ -0,0 +1,133 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job starts its execution.
+///
+public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job starts its execution.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Get the scheduled job from the repository.
+ Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
+ if (getScheduledJobResult.Value is null)
+ throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
+ ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
+ // The execution cycle is active when the scheduled job was in its active state before this execution started; the
+ // status is read before the scheduled job is updated to its running state below.
+ bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active;
+
+ // Update the scheduled job with its running status and the start time of the execution.
+ ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc);
+ Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
+ if (updateScheduledJobResult.IsFailure)
+ throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
+
+ // Insert the execution of the task of the scheduled job into the repository.
+ ScheduledJobExecutionEntity execution = new()
+ {
+ Id = domainEvent.RunId,
+ ScheduledJobId = scheduledJob.Id,
+ TaskType = scheduledJob.TaskType,
+ IsCycleRun = domainEvent.IsCycleRun,
+ WasCycleActive = wasCycleActive,
+ StartedOnUtc = domainEvent.StartedOnUtc,
+ CompletedOnUtc = null,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = null,
+ UpdatedBy = null
+ };
+ Result insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false);
+ if (insertExecutionResult.IsFailure)
+ throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors);
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ // Notify the SignalR clients about the current scheduled jobs and the started execution.
+ await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
+ await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Creates a copy of with the provided status and timestamps.
+ ///
+ /// The scheduled job to copy.
+ /// The status of the copy.
+ /// The last start time of the copy.
+ /// The last completion time of the copy.
+ /// The copy of the scheduled job.
+ private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
+ {
+ return new ScheduledJobEntity
+ {
+ Id = scheduledJob.Id,
+ Name = scheduledJob.Name,
+ TaskType = scheduledJob.TaskType,
+ ScheduleType = scheduledJob.ScheduleType,
+ IntervalMinutes = scheduledJob.IntervalMinutes,
+ Hour = scheduledJob.Hour,
+ Minute = scheduledJob.Minute,
+ Status = status,
+ OwnerUserId = scheduledJob.OwnerUserId,
+ LastStartedOnUtc = lastStartedOnUtc,
+ LastCompletedOnUtc = lastCompletedOnUtc,
+ CreatedOnUtc = scheduledJob.CreatedOnUtc,
+ CreatedBy = scheduledJob.CreatedBy,
+ UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
+ UpdatedBy = scheduledJob.UpdatedBy
+ };
+ }
+
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs
new file mode 100644
index 00000000..cc735453
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs
@@ -0,0 +1,80 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the execution of the task of a scheduled job is stopped while it is running.
+///
+public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobExecutionStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when the execution of the task of a scheduled job is stopped while it is running.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobExecutionStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Close the execution history row of the stopped execution, if it exists.
+ Result getOpenExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository
+ .GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
+ if (getOpenExecutionResult.IsFailure)
+ throw new EventualConsistencyException(getOpenExecutionResult.FirstError, getOpenExecutionResult.Errors);
+ if (getOpenExecutionResult.Value is not null)
+ {
+ ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value;
+ ScheduledJobExecutionEntity updatedExecution = new()
+ {
+ Id = execution.Id,
+ ScheduledJobId = execution.ScheduledJobId,
+ TaskType = execution.TaskType,
+ IsCycleRun = execution.IsCycleRun,
+ WasCycleActive = execution.WasCycleActive,
+ StartedOnUtc = execution.StartedOnUtc,
+ CompletedOnUtc = domainEvent.OccurredOnUtc,
+ CreatedOnUtc = execution.CreatedOnUtc,
+ CreatedBy = execution.CreatedBy,
+ UpdatedOnUtc = execution.UpdatedOnUtc,
+ UpdatedBy = execution.UpdatedBy
+ };
+ Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
+ if (updateExecutionResult.IsFailure)
+ throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ // Notify the SignalR clients about the current list of scheduled jobs.
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs
new file mode 100644
index 00000000..aa29481e
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when the task of a scheduled job is fired once.
+///
+public class ScheduledJobFiredDomainEventHandler : IDomainEventHandler
+{
+ private readonly IScheduledJobScheduler _scheduledJobScheduler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service that schedules and executes the tasks of scheduled jobs.
+ public ScheduledJobFiredDomainEventHandler(IScheduledJobScheduler scheduledJobScheduler)
+ {
+ _scheduledJobScheduler = scheduledJobScheduler;
+ }
+
+ ///
+ /// Handles the event raised when the task of a scheduled job is fired once.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobFiredDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ // Start a one time execution of the task of the scheduled job in the scheduler service.
+ await _scheduledJobScheduler.RunOnceAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs
new file mode 100644
index 00000000..892a64f4
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Application.Core.Scheduling.Notifications;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Exceptions;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Events;
+
+///
+/// Handler for the domain event raised when a scheduled job is removed.
+///
+public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandler
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IScheduledJobNotifier _scheduledJobNotifier;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for notifying the scheduled job changes to SignalR clients.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public ScheduledJobRemovedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _scheduledJobNotifier = scheduledJobNotifier;
+ }
+
+ ///
+ /// Handles the event raised when a scheduled job is removed.
+ ///
+ /// The domain event to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
+ IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
+ await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs
new file mode 100644
index 00000000..4251a142
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.Scheduling;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Notifications;
+
+///
+/// Interface for the class used to notify SignalR clients about the scheduled jobs and their executions.
+///
+public interface IScheduledJobNotifier
+{
+ ///
+ /// Notifies the SignalR clients about the current list of scheduled jobs.
+ ///
+ /// The current list of scheduled jobs.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken);
+
+ ///
+ /// Notifies the SignalR clients about an execution of the task of a scheduled job that started.
+ ///
+ /// The execution of the task of the scheduled job that started.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
+
+ ///
+ /// Notifies the SignalR clients about an execution of the task of a scheduled job that completed.
+ ///
+ /// The execution of the task of the scheduled job that completed.
+ /// Cancellation token that can be used to stop the execution.
+ Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs
new file mode 100644
index 00000000..edac9854
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+
+///
+/// Query for getting the history of the executions of the tasks of scheduled jobs.
+///
+/// The optional inclusive lower bound of the interval for which the history is requested.
+/// The optional inclusive upper bound of the interval for which the history is requested.
+[DebuggerDisplay("From: {From}, To: {To}")]
+public record GetScheduledJobHistoryQuery(
+ DateTime? From,
+ DateTime? To
+) : IQuery;
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs
new file mode 100644
index 00000000..bb9378e9
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs
@@ -0,0 +1,76 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
+
+///
+/// Handler for the query to get the history of the executions of the tasks of scheduled jobs.
+///
+public class GetScheduledJobHistoryQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public GetScheduledJobHistoryQueryHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the history of the executions of the tasks of scheduled jobs.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the execution history, or an error.
+ ///
+ public async Task>> HandleAsync(GetScheduledJobHistoryQuery query, CancellationToken cancellationToken)
+ {
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can get the history of scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // The lower bound defaults to one day before the upper bound, which defaults to now.
+ DateTime toUtc = query.To ?? DateTime.UtcNow;
+ DateTime fromUtc = query.From ?? toUtc.AddDays(-1);
+
+ // Get the executions from the storage medium.
+ Result> getExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByTimeRangeAsync(fromUtc, toUtc, cancellationToken).ConfigureAwait(false);
+ if (getExecutionsResult.IsFailure)
+ return getExecutionsResult.Errors;
+
+ return Result.From(getExecutionsResult.Value.Select(execution => execution.ToResponse()));
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs
new file mode 100644
index 00000000..99ca2129
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs
@@ -0,0 +1,12 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
+
+///
+/// Query for getting the list of scheduled jobs.
+///
+[DebuggerDisplay("GetScheduledJobsQuery")]
+public record GetScheduledJobsQuery : IQuery;
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs
new file mode 100644
index 00000000..9991ac07
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
+
+///
+/// Handler for the query to get the list of scheduled jobs.
+///
+public class GetScheduledJobsQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public GetScheduledJobsQueryHandler(
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the list of scheduled jobs.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the list of scheduled jobs, or an error.
+ ///
+ public async Task>> HandleAsync(GetScheduledJobsQuery query, CancellationToken cancellationToken)
+ {
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can get the list of scheduled jobs.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the scheduled jobs from the storage medium.
+ Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getScheduledJobsResult.IsFailure)
+ return getScheduledJobsResult.Errors;
+
+ return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse()));
+ }
+}
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs
new file mode 100644
index 00000000..6f12960a
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs
@@ -0,0 +1,10 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
+
+///
+/// Query for getting the display preferences of the scheduler page of the current user.
+///
+public record GetSchedulerDisplayPreferencesQuery : IQuery;
diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs
new file mode 100644
index 00000000..eeaaff89
--- /dev/null
+++ b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Mapping.Scheduling;
+using Lumina.Contracts.Responses.Scheduling;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
+
+///
+/// Handler for the query to get the display preferences of the scheduler page of the current user.
+///
+public class GetSchedulerDisplayPreferencesQueryHandler : IQueryHandler>
+{
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IUnitOfWork _unitOfWork;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ public GetSchedulerDisplayPreferencesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ {
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _unitOfWork = unitOfWork;
+ }
+
+ ///
+ /// Handles the query to get the display preferences of the scheduler page of the current user.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the display preferences of the scheduler page of the current user, or an error.
+ ///
+ public async Task> HandleAsync(GetSchedulerDisplayPreferencesQuery query, CancellationToken cancellationToken)
+ {
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Only administrators can view the scheduler page.
+ if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Get the display preferences of the scheduler page of the current user from the repository.
+ Result getDisplayPreferencesResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
+ if (getDisplayPreferencesResult.IsFailure)
+ return getDisplayPreferencesResult.Errors;
+
+ // When no display preferences are stored for the current user yet, return the default display preferences.
+ if (getDisplayPreferencesResult.Value is null)
+ return getDisplayPreferencesResult.Value.ToDefaultResponse(userId);
+
+ return getDisplayPreferencesResult.Value.ToResponse();
+ }
+}
diff --git a/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs
new file mode 100644
index 00000000..e80fafb5
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to add a scheduled job.
+///
+/// The name of the scheduled job. Required.
+/// The type of the task executed by the scheduled job. Required.
+/// The type of the schedule of the scheduled job. Required.
+/// The interval in minutes of the schedule, required when is .
+/// The hour of the schedule, required when is .
+/// The minute of the schedule, required when is .
+[DebuggerDisplay("Name: {Name}")]
+public record AddScheduledJobRequest(
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs
new file mode 100644
index 00000000..53187070
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to fire the task of a scheduled job once, without affecting its execution cycle.
+///
+/// The unique identifier of the scheduled job whose task is fired. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record FireScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs
new file mode 100644
index 00000000..e95b9f94
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to get the history of the executions of the tasks of scheduled jobs.
+///
+/// The inclusive lower bound of the interval for which the history is requested. Optional.
+/// The inclusive upper bound of the interval for which the history is requested. Optional.
+[DebuggerDisplay("From: {From}, To: {To}")]
+public record GetScheduledJobHistoryRequest(
+ DateTime? From,
+ DateTime? To
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs
new file mode 100644
index 00000000..5b3dd987
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to remove a scheduled job.
+///
+/// The unique identifier of the scheduled job to remove. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record RemoveScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs
new file mode 100644
index 00000000..63448b47
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to start the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is started. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StartScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs
new file mode 100644
index 00000000..36c3f0af
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to stop the execution cycle of a scheduled job.
+///
+/// The unique identifier of the scheduled job whose execution cycle is stopped. Required.
+[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
+public record StopScheduledJobRequest(
+ Guid ScheduledJobId
+);
diff --git a/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs
new file mode 100644
index 00000000..ff546221
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs
@@ -0,0 +1,19 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Scheduling;
+
+///
+/// Represents a request to update the display preferences of the scheduler page of the current user.
+///
+/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown.
+/// The time span, expressed in , that the scheduler page shows. Required.
+/// The unit in which the displayed time span of the scheduler page is expressed. Required.
+[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
+public sealed record UpdateSchedulerDisplayPreferencesRequest(
+ ScheduledTaskType? JobTypeFilter,
+ int DisplayTimeSpan,
+ SchedulerDisplayTimeUnit DisplayTimeUnit
+);
diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs
new file mode 100644
index 00000000..4f33a189
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.Scheduling;
+
+///
+/// Represents an execution of the task of a scheduled job.
+///
+/// The unique identifier of the execution.
+/// The unique identifier of the scheduled job whose task was executed.
+/// The type of the task that was executed.
+/// when the execution was triggered by the execution cycle of the scheduled job, when it was a one time execution.
+/// The date and time when the execution started.
+/// The optional date and time when the execution completed.
+[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
+public record ScheduledJobExecutionResponse(
+ Guid Id,
+ Guid ScheduledJobId,
+ ScheduledTaskType TaskType,
+ bool IsCycleRun,
+ DateTime StartedOnUtc,
+ DateTime? CompletedOnUtc
+);
diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs
new file mode 100644
index 00000000..c1c53a2b
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs
@@ -0,0 +1,34 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.Scheduling;
+
+///
+/// Represents a scheduled job response.
+///
+/// The unique identifier of the scheduled job.
+/// The name of the scheduled job.
+/// The type of the task executed by the scheduled job.
+/// The type of the schedule of the scheduled job.
+/// The interval in minutes of the schedule of the scheduled job, when its is .
+/// The hour of the schedule of the scheduled job, when its is .
+/// The minute of the schedule of the scheduled job, when its is .
+/// The status of the scheduled job.
+/// The optional date and time when the task of the scheduled job last started its execution.
+/// The optional date and time when the task of the scheduled job last completed its execution.
+[DebuggerDisplay("Id: {Id}, Name: {Name}, Status: {Status}")]
+public record ScheduledJobResponse(
+ Guid Id,
+ string Name,
+ ScheduledTaskType TaskType,
+ ScheduleType ScheduleType,
+ int? IntervalMinutes,
+ int? Hour,
+ int? Minute,
+ ScheduledJobStatus Status,
+ DateTime? LastStartedOnUtc,
+ DateTime? LastCompletedOnUtc
+);
diff --git a/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs
new file mode 100644
index 00000000..d762eccf
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.Scheduling;
+
+///
+/// Represents the display preferences of the scheduler page of a user.
+///
+/// The unique identifier of the user that owns the display preferences.
+/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown.
+/// The time span, expressed in , that the scheduler page shows.
+/// The unit in which the displayed time span of the scheduler page is expressed.
+[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
+public sealed record SchedulerDisplayPreferencesResponse(
+ Guid UserId,
+ ScheduledTaskType? JobTypeFilter,
+ int DisplayTimeSpan,
+ SchedulerDisplayTimeUnit DisplayTimeUnit
+);
diff --git a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs
new file mode 100644
index 00000000..84b984f5
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs
@@ -0,0 +1,85 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using System;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class ScheduledJobConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("ScheduledJobs");
+ builder.HasKey(scheduledJob => scheduledJob.Id);
+ builder.Property(scheduledJob => scheduledJob.Id)
+ .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
+ .HasColumnOrder(0);
+
+ builder.Property(scheduledJob => scheduledJob.Name)
+ .IsRequired()
+ .HasColumnOrder(1);
+
+ builder.Property(scheduledJob => scheduledJob.TaskType)
+ .IsRequired()
+ .HasConversion()
+ .HasColumnOrder(2);
+
+ builder.Property(scheduledJob => scheduledJob.ScheduleType)
+ .IsRequired()
+ .HasConversion()
+ .HasColumnOrder(3);
+
+ builder.Property(scheduledJob => scheduledJob.IntervalMinutes)
+ .HasColumnOrder(4);
+
+ builder.Property(scheduledJob => scheduledJob.Hour)
+ .HasColumnOrder(5);
+
+ builder.Property(scheduledJob => scheduledJob.Minute)
+ .HasColumnOrder(6);
+
+ builder.Property(scheduledJob => scheduledJob.Status)
+ .IsRequired()
+ .HasConversion()
+ .HasColumnOrder(7);
+
+ builder.Property(scheduledJob => scheduledJob.OwnerUserId)
+ .IsRequired()
+ .HasColumnOrder(8);
+
+ builder.Property(scheduledJob => scheduledJob.LastStartedOnUtc)
+ .HasColumnOrder(9);
+
+ builder.Property(scheduledJob => scheduledJob.LastCompletedOnUtc)
+ .HasColumnOrder(10);
+
+ // Audit.
+ builder.Property(scheduledJob => scheduledJob.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(11);
+
+ builder.Property(scheduledJob => scheduledJob.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(12);
+
+ builder.Property(scheduledJob => scheduledJob.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(13);
+
+ builder.Property(scheduledJob => scheduledJob.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(14);
+
+ // Enables fast lookup of the scheduled jobs whose execution cycle is active, at scheduler startup.
+ builder.HasIndex(scheduledJob => scheduledJob.Status);
+ }
+}
diff --git a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs
new file mode 100644
index 00000000..64053b4a
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using System;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class ScheduledJobExecutionConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("ScheduledJobExecutions");
+ builder.HasKey(execution => execution.Id);
+ builder.Property(execution => execution.Id)
+ .ValueGeneratedNever()
+ .HasColumnOrder(0);
+
+ builder.Property(execution => execution.ScheduledJobId)
+ .IsRequired()
+ .HasColumnOrder(1);
+
+ builder.Property(execution => execution.TaskType)
+ .IsRequired()
+ .HasConversion()
+ .HasColumnOrder(2);
+
+ builder.Property(execution => execution.IsCycleRun)
+ .IsRequired()
+ .HasColumnOrder(3);
+
+ builder.Property(execution => execution.StartedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(4);
+
+ builder.Property(execution => execution.CompletedOnUtc)
+ .HasColumnOrder(5);
+
+ builder.Property(execution => execution.WasCycleActive)
+ .IsRequired()
+ .HasColumnOrder(6);
+
+ // Audit.
+ builder.Property(execution => execution.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(7);
+
+ builder.Property(execution => execution.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(8);
+
+ builder.Property(execution => execution.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(9);
+
+ builder.Property(execution => execution.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(10);
+
+ // Enables fast queries of the execution history of scheduled jobs by their time range, and the cleanup of the executions of a removed scheduled job.
+ builder.HasIndex(execution => new { execution.StartedOnUtc, execution.ScheduledJobId });
+ builder.HasIndex(execution => execution.ScheduledJobId);
+ }
+}
diff --git a/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs
new file mode 100644
index 00000000..698aaac7
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Scheduling;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using System;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class SchedulerDisplayPreferencesConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("SchedulerDisplayPreferences");
+ builder.HasKey(preferences => preferences.Id);
+ builder.Property(preferences => preferences.Id)
+ .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
+ .HasColumnOrder(0);
+
+ builder.Property(preferences => preferences.UserId)
+ .IsRequired()
+ .HasColumnOrder(1);
+
+ builder.Property(preferences => preferences.JobTypeFilter)
+ .HasConversion()
+ .HasColumnOrder(2);
+
+ builder.Property(preferences => preferences.DisplayTimeSpan)
+ .IsRequired()
+ .HasColumnOrder(3);
+
+ builder.Property(preferences => preferences.DisplayTimeUnit)
+ .IsRequired()
+ .HasConversion()
+ .HasColumnOrder(4);
+
+ // Audit.
+ builder.Property(preferences => preferences.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(5);
+
+ builder.Property(preferences => preferences.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(6);
+
+ builder.Property(preferences => preferences.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(7);
+
+ builder.Property(preferences => preferences.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(8);
+
+ // One user has at most one set of scheduler page display preferences.
+ builder.HasIndex(preferences => preferences.UserId)
+ .IsUnique();
+ }
+}
diff --git a/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs
new file mode 100644
index 00000000..699b7ca3
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs
@@ -0,0 +1,1741 @@
+// .
+using System;
+using Lumina.DataAccess.Core.UoW;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace Lumina.DataAccess.Common.Migrations
+{
+ [DbContext(typeof(LuminaDbContext))]
+ [Migration("20260903054819_AddsScheduledJobsTables")]
+ partial class AddsScheduledJobsTables
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.11");
+
+ modelBuilder.Entity("BookGenres", b =>
+ {
+ b.Property("BookId")
+ .HasColumnType("TEXT");
+
+ b.Property("GenreId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("BookId", "GenreId");
+
+ b.HasIndex("GenreId");
+
+ b.ToTable("BookGenres", (string)null);
+ });
+
+ modelBuilder.Entity("BookTags", b =>
+ {
+ b.Property("BookId")
+ .HasColumnType("TEXT");
+
+ b.Property("TagId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("BookId", "TagId");
+
+ b.HasIndex("TagId");
+
+ b.ToTable("BookTags", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("PermissionName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.HasKey("Id");
+
+ b.ToTable("Permissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("RoleName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.HasKey("Id");
+
+ b.ToTable("Roles", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
+ {
+ b.Property("RoleId")
+ .HasColumnType("TEXT");
+
+ b.Property("PermissionId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("RoleId", "PermissionId");
+
+ b.HasIndex("PermissionId");
+
+ b.HasIndex("RoleId", "PermissionId")
+ .IsUnique();
+
+ b.ToTable("RolePermissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
+ {
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("PermissionId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("UserId", "PermissionId");
+
+ b.HasIndex("PermissionId");
+
+ b.HasIndex("UserId", "PermissionId")
+ .IsUnique();
+
+ b.ToTable("UserPermissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
+ {
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("RoleId")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("UserId");
+
+ b.HasIndex("RoleId");
+
+ b.HasIndex("UserId", "RoleId")
+ .IsUnique();
+
+ b.ToTable("UserRoles", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
+ {
+ b.Property("Name")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Name");
+
+ b.ToTable("Genres", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
+ {
+ b.Property("Name")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Name");
+
+ b.ToTable("Tags", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("BookId")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.Property("MediaContributorId")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("RoleCategory")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("RoleName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(8);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(7);
+
+ b.HasKey("Id");
+
+ b.HasIndex("MediaContributorId");
+
+ b.HasIndex("BookId", "MediaContributorId");
+
+ b.ToTable("BookContributors", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("Biography")
+ .HasMaxLength(2000)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(7);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("DateOfBirth")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("DateOfDeath")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.Property("DisplayName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1)
+ .UseCollation("NOCASE");
+
+ b.Property("LegalName")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(9);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(8);
+
+ b.HasKey("Id");
+
+ b.HasIndex("DisplayName")
+ .IsUnique();
+
+ b.ToTable("MediaContributors", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b =>
+ {
+ b.Property