Scheduled jobs: SU screen to start, stop and time the three legacy jobs
- Jobs: activate-company-destinations, close-old-permits (new port of GRAINS_Close_Old_Permits.cfm), fill-company-shares - Interval (minutes/hours) or daily fixed times, run now, run history; database-row lock; tables from db/grains-jobs.sql - Scheduler loop (off in Development), SU-only JobsController, web page /jobs - Fix ORA-01745: no reserved words (BY, ROWS) as bind names; stale RUNNING marks heal themselves Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
eaf52d53d9
commit
025fbe9af8
|
|
@ -11,6 +11,7 @@ conventions: docs/MIGRATION.md. Table definitions: docs/schema/NTP.md and NAFITH
|
||||||
- `src/NTP.Infrastructure` Oracle + Dapper repositories (raw SQL), gateways (TCS, IVR, notifications), file store
|
- `src/NTP.Infrastructure` Oracle + Dapper repositories (raw SQL), gateways (TCS, IVR, notifications), file store
|
||||||
- `src/NTP.Domain` entities and rules; `tests/NTP.Tests` xUnit (283 tests at hand-over)
|
- `src/NTP.Domain` entities and rules; `tests/NTP.Tests` xUnit (283 tests at hand-over)
|
||||||
- `web/src/features/grains-{orders,permits,registry,reports}` screens (metadata-driven DataGrid / MetaForm in `web/src/components`), `web/src/shell` menu, header, home
|
- `web/src/features/grains-{orders,permits,registry,reports}` screens (metadata-driven DataGrid / MetaForm in `web/src/components`), `web/src/shell` menu, header, home
|
||||||
|
- `src/NTP.*/Jobs` + `web/src/features/jobs` scheduled jobs (SU screen `/jobs`; catalog in `JobCatalog`; tables from `db/grains-jobs.sql`)
|
||||||
- `db/*.sql` one-off permission / role scripts (run by hand per environment, not by the app); `deploy/` Docker + Jenkins (see `Jenkinsfile`)
|
- `db/*.sql` one-off permission / role scripts (run by hand per environment, not by the app); `deploy/` Docker + Jenkins (see `Jenkinsfile`)
|
||||||
|
|
||||||
## Commands (Windows; Git Bash or PowerShell)
|
## Commands (Windows; Git Bash or PowerShell)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
-- Scheduled jobs (screen "المهام المجدولة", SU only). Run once per database in the PRIMARY schema (NAFITHTCS). Safe to re-run; not run by the app.
|
||||||
|
-- Until this script has run the scheduler stays idle (one warning in the API log) and the screen shows a message.
|
||||||
|
--
|
||||||
|
-- GRAINS_JOBS one row per job: stopped / started, schedule, last run. Rows are created by the screen, nothing to seed.
|
||||||
|
-- GRAINS_JOB_RUNS history of every run (kept 90 days by the application).
|
||||||
|
--
|
||||||
|
-- Jobs (ports of the legacy jobs\*.cfm files): activate-company-destinations, close-old-permits, fill-company-shares.
|
||||||
|
-- Schedule: SCHEDULETYPE = 'INTERVAL' (INTERVALMINUTES) or 'DAILY' (DAILYTIMES = 'HH:mm,HH:mm', database server time).
|
||||||
|
|
||||||
|
DECLARE
|
||||||
|
PROCEDURE ddl(p_sql VARCHAR2) IS
|
||||||
|
BEGIN
|
||||||
|
EXECUTE IMMEDIATE p_sql;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN OTHERS THEN
|
||||||
|
-- already there: name in use (955), column list already indexed (1408)
|
||||||
|
IF SQLCODE NOT IN (-955, -1408) THEN RAISE; END IF;
|
||||||
|
END;
|
||||||
|
BEGIN
|
||||||
|
ddl('CREATE TABLE GRAINS_JOBS (
|
||||||
|
JOBKEY VARCHAR2(50) NOT NULL,
|
||||||
|
ENABLED NUMBER(1) DEFAULT 0 NOT NULL,
|
||||||
|
SCHEDULETYPE VARCHAR2(10),
|
||||||
|
INTERVALMINUTES NUMBER(8),
|
||||||
|
DAILYTIMES VARCHAR2(200),
|
||||||
|
LASTSTARTDATE DATE,
|
||||||
|
LASTENDDATE DATE,
|
||||||
|
LASTSTATUS VARCHAR2(20),
|
||||||
|
LASTMESSAGE VARCHAR2(500),
|
||||||
|
LASTCOUNT NUMBER(10),
|
||||||
|
UPDATEDATE DATE,
|
||||||
|
UPDATEDBY VARCHAR2(50),
|
||||||
|
CONSTRAINT PK_GRAINS_JOBS PRIMARY KEY (JOBKEY)
|
||||||
|
)');
|
||||||
|
|
||||||
|
ddl('CREATE TABLE GRAINS_JOB_RUNS (
|
||||||
|
ID NUMBER(12) NOT NULL,
|
||||||
|
JOBKEY VARCHAR2(50) NOT NULL,
|
||||||
|
STARTDATE DATE NOT NULL,
|
||||||
|
ENDDATE DATE,
|
||||||
|
STATUS VARCHAR2(20),
|
||||||
|
ROWSAFFECTED NUMBER(10),
|
||||||
|
MESSAGE VARCHAR2(500),
|
||||||
|
TRIGGEREDBY VARCHAR2(50),
|
||||||
|
CONSTRAINT PK_GRAINS_JOB_RUNS PRIMARY KEY (ID)
|
||||||
|
)');
|
||||||
|
|
||||||
|
ddl('CREATE SEQUENCE SEQ_GRAINS_JOB_RUNS START WITH 1 INCREMENT BY 1 NOCACHE');
|
||||||
|
ddl('CREATE INDEX IX_GRAINS_JOB_RUNS_KEY ON GRAINS_JOB_RUNS (JOBKEY, ID)');
|
||||||
|
END;
|
||||||
|
/
|
||||||
|
|
||||||
|
-- Stop a job from SQL if the screen is not reachable: UPDATE GRAINS_JOBS SET ENABLED = 0 WHERE JOBKEY = 'close-old-permits'; COMMIT;
|
||||||
|
|
@ -54,6 +54,7 @@ Apply these scripts once per database (not run by the application), in this orde
|
||||||
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)
|
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)
|
||||||
5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run)
|
5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run)
|
||||||
5c. `db/role-co.sql` - new role CO with the same rights as GTO: role row (NTP schema) + copy of every GTO row in GRAINS_SCREEN_PERMISSIONS (safe to re-run)
|
5c. `db/role-co.sql` - new role CO with the same rights as GTO: role row (NTP schema) + copy of every GTO row in GRAINS_SCREEN_PERMISSIONS (safe to re-run)
|
||||||
|
7. `db/grains-jobs.sql` - tables of the scheduled jobs (`GRAINS_JOBS`, `GRAINS_JOB_RUNS`), primary schema. Without it the scheduler stays idle. Jobs are then started, stopped and timed on the SU screen "المهام المجدولة" (`/jobs`); nothing runs until a job is started there. `Jobs:SchedulerEnabled=false` (set in appsettings.Development.json) switches the scheduler loop off for a process
|
||||||
6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run)
|
6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run)
|
||||||
|
|
||||||
**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU
|
**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
|
||||||
- **Reports:** the two GTO reports (ارسالية عطاء التموين, ملخص التوزيع) and turn reports (translated values, centred counters).
|
- **Reports:** the two GTO reports (ارسالية عطاء التموين, ملخص التوزيع) and turn reports (translated values, centred counters).
|
||||||
- **Permits / distribution:** distribution reviewed twice against legacy and fixed (BlCategory bind, General Cargo exclusion, OPEN guards, queue cursor reset at sign-in, per-category confirmation, process-with-destination dropdowns + server check); voice call (الاتصال الصوتي) uses the legacy SOAP call; dialer callback hardened.
|
- **Permits / distribution:** distribution reviewed twice against legacy and fixed (BlCategory bind, General Cargo exclusion, OPEN guards, queue cursor reset at sign-in, per-category confirmation, process-with-destination dropdowns + server check); voice call (الاتصال الصوتي) uses the legacy SOAP call; dialer callback hardened.
|
||||||
- **Security pass:** accept / reject / cancel-confirmation staff-only, submit needs REQST, company-access null check, seed / check-trucks SU-only, attachment download scoped to the company.
|
- **Security pass:** accept / reject / cancel-confirmation staff-only, submit needs REQST, company-access null check, seed / check-trucks SU-only, attachment download scoped to the company.
|
||||||
|
- **Scheduled jobs:** SU screen `/jobs` ("المهام المجدولة") starts / stops the three legacy jobs (`activateGrainsDestination`, `GRAINS_Close_Old_Permits` - ported new, `parseGrainsPermits`) and sets their running time: every N minutes / hours, or at fixed times of the day (database server time). Code: `src/NTP.Application/Jobs` (catalog, schedule rules, service), `src/NTP.Infrastructure/Jobs` (20-second scheduler loop, runner), `JobsController`, `web/src/features/jobs`. Needs `db/grains-jobs.sql` first. The lock is a database row, so two API instances never run one job twice. Add a job = one entry in `JobCatalog`. The old config-driven `GrainsPermitJobsWorker` is not registered and superseded by this.
|
||||||
- **Operations:** unexpected 5xx errors go to `SYSTEM_ERRORS`; containers run with `TZ=Asia/Amman`.
|
- **Operations:** unexpected 5xx errors go to `SYSTEM_ERRORS`; containers run with `TZ=Asia/Amman`.
|
||||||
- **Roles:** `CO` was given the same code-level rights as `GTO` (see 3.1).
|
- **Roles:** `CO` was given the same code-level rights as `GTO` (see 3.1).
|
||||||
- Last local commit at hand-over: `bf1c04b`. **It may not be pushed** (Claude sessions cannot authenticate to Gitea): run `git log origin/main..HEAD` and push it.
|
- Last local commit at hand-over: `bf1c04b`. **It may not be pushed** (Claude sessions cannot authenticate to Gitea): run `git log origin/main..HEAD` and push it.
|
||||||
|
|
@ -28,6 +29,8 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
|
||||||
10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run).
|
10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run).
|
||||||
|
|
||||||
## 3. Open decisions and known gaps
|
## 3. Open decisions and known gaps
|
||||||
|
### 3.0 Scheduled jobs: untested parts
|
||||||
|
The schedule rules are unit-tested and the close-old-permits SQL was run read-only on QA, but the job tables did not exist when this was written: run `db/grains-jobs.sql`, then try the screen (save a time, start, run now, history) on QA. Close-old-permits differs from legacy in two safe ways: a permit found by two of its four groups is closed once, and it is closed only while it still has the status it was found with.
|
||||||
### 3.1 Role CO
|
### 3.1 Role CO
|
||||||
`CO` already existed in the database ("مدير العمليات وخدمة الجمهور", own group id 149, stakeholder 61, 29 mostly oil-related actions, 1 user) and the legacy menu uses it in many places. The code now treats CO like GTO, and `GRAINS_SCREEN_PERMISSIONS` already has the same 27 rows for both. **Decide** whether that user should really get GTO's grains authority or whether a new role code is wanted. Also unresolved: CO's legacy group has none of the registry actions 66-71 / 107, so accept / revoke of trucks, trailers, drivers and destinations are off for CO; `db/role-co.sql` does not create `GROUPS` / `GROUP_ACTIONS` rows.
|
`CO` already existed in the database ("مدير العمليات وخدمة الجمهور", own group id 149, stakeholder 61, 29 mostly oil-related actions, 1 user) and the legacy menu uses it in many places. The code now treats CO like GTO, and `GRAINS_SCREEN_PERMISSIONS` already has the same 27 rows for both. **Decide** whether that user should really get GTO's grains authority or whether a new role code is wanted. Also unresolved: CO's legacy group has none of the registry actions 66-71 / 107, so accept / revoke of trucks, trailers, drivers and destinations are off for CO; `db/role-co.sql` does not create `GROUPS` / `GROUP_ACTIONS` rows.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
using Asp.Versioning;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using NTP.Application.Jobs;
|
||||||
|
|
||||||
|
namespace NTP.Api.Controllers.V1.Grains;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scheduled jobs (ports of the legacy jobs\*.cfm files): list, set the running time, start / stop, run now, run history.
|
||||||
|
/// Super users only. Nothing runs until a job is started here.
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[ApiVersion(1.0)]
|
||||||
|
[Route("api/v{version:apiVersion}/grains/jobs")]
|
||||||
|
[Produces("application/json")]
|
||||||
|
[Authorize(Roles = "SU")]
|
||||||
|
public sealed class JobsController(IJobService jobs) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public Task<IReadOnlyList<JobDto>> List(CancellationToken ct) => jobs.ListAsync(ct);
|
||||||
|
|
||||||
|
/// <summary>Running time: every N minutes (INTERVAL) or at fixed times of the day (DAILY, HH:mm).</summary>
|
||||||
|
[HttpPut("{key}")]
|
||||||
|
public Task<JobDto> SaveSchedule(string key, SaveJobScheduleRequest request, CancellationToken ct) => jobs.SaveScheduleAsync(key, request, ct);
|
||||||
|
|
||||||
|
[HttpPost("{key}/start")]
|
||||||
|
public Task<JobDto> Start(string key, CancellationToken ct) => jobs.StartAsync(key, ct);
|
||||||
|
|
||||||
|
[HttpPost("{key}/stop")]
|
||||||
|
public Task<JobDto> Stop(string key, CancellationToken ct) => jobs.StopAsync(key, ct);
|
||||||
|
|
||||||
|
/// <summary>Starts the job now in the background, whether it is started or stopped; refuses when it is already running.</summary>
|
||||||
|
[HttpPost("{key}/run")]
|
||||||
|
public Task<JobActionResult> Run(string key, CancellationToken ct) => jobs.RunNowAsync(key, ct);
|
||||||
|
|
||||||
|
[HttpGet("{key}/runs")]
|
||||||
|
public Task<IReadOnlyList<JobRunDto>> Runs(string key, CancellationToken ct) => jobs.RunsAsync(key, ct);
|
||||||
|
}
|
||||||
|
|
@ -2,6 +2,8 @@
|
||||||
"Auth": {
|
"Auth": {
|
||||||
"SuperUsers": [ "samer", "QA", "MATHHER" ]
|
"SuperUsers": [ "samer", "QA", "MATHHER" ]
|
||||||
},
|
},
|
||||||
|
// the job scheduler never runs on a developer machine (a shared database would run its jobs twice); "run now" still works
|
||||||
|
"Jobs": { "SchedulerEnabled": false },
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
using NTP.Application.Abstractions;
|
||||||
|
using NTP.Domain.Grains.Permits;
|
||||||
|
|
||||||
|
namespace NTP.Application.Grains.Permits;
|
||||||
|
|
||||||
|
/// <summary>A permit that jobs/GRAINS_Close_Old_Permits.cfm closes.</summary>
|
||||||
|
public sealed class OldPermitRow
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public string? Status { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IPermitJobsRepository
|
||||||
|
{
|
||||||
|
/// <summary>The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules).</summary>
|
||||||
|
Task<IReadOnlyList<OldPermitRow>> GetOldPermitsToCloseAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Sets CLOSE only while the permit still has the status it was found with; returns the rows changed.</summary>
|
||||||
|
Task<int> CloseAsync(long permitId, string previousStatus, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IPermitJobsService
|
||||||
|
{
|
||||||
|
/// <summary>jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed.</summary>
|
||||||
|
Task<int> CloseOldPermitsAsync(CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService
|
||||||
|
{
|
||||||
|
public async Task<int> CloseOldPermitsAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rows = await repo.GetOldPermitsToCloseAsync(ct);
|
||||||
|
var seen = new HashSet<long>();
|
||||||
|
var closed = 0;
|
||||||
|
foreach (var row in rows)
|
||||||
|
{
|
||||||
|
// the legacy query is a UNION ALL: one permit can appear in several groups and was then closed (and logged) several times
|
||||||
|
if (!seen.Add(row.Id)) continue;
|
||||||
|
var previous = row.Status ?? string.Empty;
|
||||||
|
var done = await uow.ExecuteInTransactionAsync(async token =>
|
||||||
|
{
|
||||||
|
if (await repo.CloseAsync(row.Id, previous, token) == 0) return false; // its status changed since the query
|
||||||
|
await events.LogAsAsync("SYSTEM", null, row.Id, previous, PermitStatus.Closed, PermitEventType.Override, "System Close.", ct: token);
|
||||||
|
return true;
|
||||||
|
}, ct);
|
||||||
|
if (done) closed++;
|
||||||
|
}
|
||||||
|
return closed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,47 @@
|
||||||
|
using NTP.Application.Grains.Permits;
|
||||||
|
|
||||||
|
namespace NTP.Application.Jobs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The jobs the scheduler can run (ports of the legacy jobs\*.cfm files). To add one: add an entry here and make sure its code is safe to
|
||||||
|
/// run repeatedly. Everything about WHEN it runs lives in the database (screen "المهام المجدولة", SU only).
|
||||||
|
/// </summary>
|
||||||
|
public static class JobCatalog
|
||||||
|
{
|
||||||
|
private static T Get<T>(IServiceProvider sp) where T : class => (T)(sp.GetService(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not registered"));
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<JobDefinition> All =
|
||||||
|
[
|
||||||
|
new("activate-company-destinations",
|
||||||
|
"تفعيل وجهات الشركات المعلقة", "Activate pending company destinations",
|
||||||
|
"jobs/activateGrainsDestination.cfm: الوجهات التي مضى على تقديمها أكثر من 3 أيام (معلقة) تصبح فعالة، وتلغى الوجهات الفعالة السابقة لنفس القاطرة.",
|
||||||
|
"jobs/activateGrainsDestination.cfm: destinations pending for more than 3 days become active and the truck's previous active destinations are deactivated.",
|
||||||
|
async (sp, ct) =>
|
||||||
|
{
|
||||||
|
var n = await Get<IDestinationService>(sp).ActivatePendingCompanyDestinationsAsync(ct);
|
||||||
|
return new JobOutcome(n, $"تم تفعيل {n} وجهة");
|
||||||
|
}),
|
||||||
|
|
||||||
|
new("close-old-permits",
|
||||||
|
"إغلاق الارساليات القديمة", "Close old permits",
|
||||||
|
"jobs/GRAINS_Close_Old_Permits.cfm: إغلاق الارساليات التي مضى على تحميلها 48 ساعة، أو التي أكملت التفريغ ولم تغلق، أو المكررة لنفس القاطرة، بحدث \"System Close.\".",
|
||||||
|
"jobs/GRAINS_Close_Old_Permits.cfm: closes permits loaded more than 48 hours ago, finished but not closed, or duplicated for the same truck, with the event \"System Close.\".",
|
||||||
|
async (sp, ct) =>
|
||||||
|
{
|
||||||
|
var n = await Get<IPermitJobsService>(sp).CloseOldPermitsAsync(ct);
|
||||||
|
return new JobOutcome(n, $"تم إغلاق {n} إرسالية");
|
||||||
|
}),
|
||||||
|
|
||||||
|
new("fill-company-shares",
|
||||||
|
"استكمال ارساليات الشركات حسب الحصة", "Top up company permits to their share",
|
||||||
|
"jobs/parseGrainsPermits.cfm: لكل شركة، إنشاء إرساليات مفتوحة (على الدور) لتساوي حصتها من الدور في المشول والسائب.",
|
||||||
|
"jobs/parseGrainsPermits.cfm: for every company, creates open permits (on the turn) up to its queue share, for packed and bulk.",
|
||||||
|
async (sp, ct) =>
|
||||||
|
{
|
||||||
|
var n = await Get<IQueueService>(sp).FillCompanySharesAsync(ct);
|
||||||
|
return new JobOutcome(n, $"تم إنشاء {n} إرسالية");
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,119 @@
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace NTP.Application.Jobs;
|
||||||
|
|
||||||
|
/// <summary>Pure scheduling rules (no clock, no database), so they can be tested exactly.</summary>
|
||||||
|
public static class JobScheduleRules
|
||||||
|
{
|
||||||
|
public const int MinIntervalMinutes = 1;
|
||||||
|
public const int MaxIntervalMinutes = 7 * 24 * 60;
|
||||||
|
public const int DefaultIntervalMinutes = 60;
|
||||||
|
|
||||||
|
/// <summary>A daily time that was missed (application stopped, restart) still runs once if it is at most this late.</summary>
|
||||||
|
public static readonly TimeSpan CatchUp = TimeSpan.FromMinutes(30);
|
||||||
|
|
||||||
|
public static bool TryParseTime(string? text, out TimeOnly time) =>
|
||||||
|
TimeOnly.TryParseExact(text?.Trim(), "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out time);
|
||||||
|
|
||||||
|
/// <summary>"02:00,13:30" -> times (invalid parts are ignored).</summary>
|
||||||
|
public static IReadOnlyList<TimeOnly> ParseTimes(string? csv)
|
||||||
|
{
|
||||||
|
var list = new List<TimeOnly>();
|
||||||
|
foreach (var part in (csv ?? string.Empty).Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
if (TryParseTime(part, out var t)) list.Add(t);
|
||||||
|
return list.Distinct().OrderBy(t => t).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> SplitTimes(string? csv) => ParseTimes(csv).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)).ToList();
|
||||||
|
|
||||||
|
public static string JoinTimes(IEnumerable<string>? times) =>
|
||||||
|
string.Join(',', (times ?? []).Select(x => TryParseTime(x, out var t) ? t : (TimeOnly?)null).Where(t => t.HasValue)
|
||||||
|
.Select(t => t!.Value).Distinct().OrderBy(t => t).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)));
|
||||||
|
|
||||||
|
/// <summary>Returns an Arabic error text, or null when the schedule is valid.</summary>
|
||||||
|
public static string? Validate(string? scheduleType, int? intervalMinutes, IReadOnlyList<string>? dailyTimes)
|
||||||
|
{
|
||||||
|
switch (scheduleType)
|
||||||
|
{
|
||||||
|
case JobScheduleTypes.Interval:
|
||||||
|
if (intervalMinutes is null || intervalMinutes < MinIntervalMinutes || intervalMinutes > MaxIntervalMinutes)
|
||||||
|
return "الفترة يجب أن تكون بين دقيقة واحدة و 7 أيام";
|
||||||
|
return null;
|
||||||
|
case JobScheduleTypes.Daily:
|
||||||
|
if (dailyTimes is null || dailyTimes.Count == 0) return "يرجى تحديد وقت واحد على الأقل";
|
||||||
|
if (dailyTimes.Any(x => !TryParseTime(x, out _))) return "صيغة الوقت غير صحيحة، استخدم HH:mm";
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return "نوع الجدولة غير صحيح";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTime? Latest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a > b ? a : b;
|
||||||
|
|
||||||
|
/// <summary>The most recent configured daily time that is not in the future (today or yesterday), if any.</summary>
|
||||||
|
private static DateTime? LatestOccurrence(IReadOnlyList<TimeOnly> times, DateTime now)
|
||||||
|
{
|
||||||
|
DateTime? latest = null;
|
||||||
|
foreach (var day in new[] { -1, 0 })
|
||||||
|
foreach (var t in times)
|
||||||
|
{
|
||||||
|
var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
|
||||||
|
if (occurrence <= now && (latest is null || occurrence > latest)) latest = occurrence;
|
||||||
|
}
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Is the job due at <paramref name="now"/>? A job that is stopped or still running never is.</summary>
|
||||||
|
public static bool IsDue(JobSettingsRow s, DateTime now)
|
||||||
|
{
|
||||||
|
if (!s.IsEnabled || s.IsRunning) return false;
|
||||||
|
|
||||||
|
// a run (or saving / starting the job) closes the window of everything that was due before it
|
||||||
|
var floor = Latest(s.LastStart, s.UpdatedDate);
|
||||||
|
|
||||||
|
if (s.ScheduleType == JobScheduleTypes.Interval)
|
||||||
|
{
|
||||||
|
if (s.IntervalMinutes is not > 0) return false;
|
||||||
|
var anchor = floor ?? now;
|
||||||
|
return now >= anchor.AddMinutes(s.IntervalMinutes.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.ScheduleType == JobScheduleTypes.Daily)
|
||||||
|
{
|
||||||
|
var times = ParseTimes(s.DailyTimes);
|
||||||
|
var latest = LatestOccurrence(times, now);
|
||||||
|
if (latest is null || now - latest > CatchUp) return false;
|
||||||
|
return floor is null || latest > floor;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>When the job runs next (null when it is stopped or has no valid schedule). A job that is due now returns <paramref name="now"/>.</summary>
|
||||||
|
public static DateTime? NextRun(JobSettingsRow s, DateTime now)
|
||||||
|
{
|
||||||
|
if (!s.IsEnabled) return null;
|
||||||
|
if (IsDue(s, now)) return now;
|
||||||
|
|
||||||
|
if (s.ScheduleType == JobScheduleTypes.Interval)
|
||||||
|
{
|
||||||
|
if (s.IntervalMinutes is not > 0) return null;
|
||||||
|
var anchor = Latest(s.LastStart, s.UpdatedDate) ?? now;
|
||||||
|
var next = anchor.AddMinutes(s.IntervalMinutes.Value);
|
||||||
|
return next < now ? now : next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.ScheduleType == JobScheduleTypes.Daily)
|
||||||
|
{
|
||||||
|
var times = ParseTimes(s.DailyTimes);
|
||||||
|
DateTime? next = null;
|
||||||
|
foreach (var day in new[] { 0, 1 })
|
||||||
|
foreach (var t in times)
|
||||||
|
{
|
||||||
|
var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
|
||||||
|
if (occurrence > now && (next is null || occurrence < next)) next = occurrence;
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,107 @@
|
||||||
|
using NTP.Application.Abstractions;
|
||||||
|
using NTP.Application.Common;
|
||||||
|
|
||||||
|
namespace NTP.Application.Jobs;
|
||||||
|
|
||||||
|
public interface IJobService
|
||||||
|
{
|
||||||
|
Task<IReadOnlyList<JobDto>> ListAsync(CancellationToken ct = default);
|
||||||
|
Task<JobDto> SaveScheduleAsync(string key, SaveJobScheduleRequest request, CancellationToken ct = default);
|
||||||
|
Task<JobDto> StartAsync(string key, CancellationToken ct = default);
|
||||||
|
Task<JobDto> StopAsync(string key, CancellationToken ct = default);
|
||||||
|
Task<JobActionResult> RunNowAsync(string key, CancellationToken ct = default);
|
||||||
|
Task<IReadOnlyList<JobRunDto>> RunsAsync(string key, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Keys of the jobs that are due now (used by the scheduler loop).</summary>
|
||||||
|
Task<IReadOnlyList<string>> GetDueKeysAsync(CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class JobService(IJobRepository repo, IJobRunner runner, ICurrentUser user) : IJobService
|
||||||
|
{
|
||||||
|
private static JobDefinition Def(string key) =>
|
||||||
|
JobCatalog.Find(key) ?? throw new NotFoundException("Job", key);
|
||||||
|
|
||||||
|
/// <summary>The settings of a job that was never saved: stopped, every hour.</summary>
|
||||||
|
private static JobSettingsRow Defaults(string key) => new()
|
||||||
|
{
|
||||||
|
JobKey = key, Enabled = 0, ScheduleType = JobScheduleTypes.Interval, IntervalMinutes = JobScheduleRules.DefaultIntervalMinutes
|
||||||
|
};
|
||||||
|
|
||||||
|
private static JobDto ToDto(JobDefinition d, JobSettingsRow s, DateTime now) => new(
|
||||||
|
d.Key, d.TitleAr, d.TitleEn, d.DescriptionAr, d.DescriptionEn,
|
||||||
|
s.IsEnabled, s.ScheduleType ?? JobScheduleTypes.Interval, s.IntervalMinutes ?? JobScheduleRules.DefaultIntervalMinutes,
|
||||||
|
JobScheduleRules.SplitTimes(s.DailyTimes), s.IsRunning, s.LastStart, s.LastEnd, s.LastStatus, s.LastMessage, s.LastCount,
|
||||||
|
JobScheduleRules.NextRun(s, now));
|
||||||
|
|
||||||
|
private async Task<(DateTime Now, Dictionary<string, JobSettingsRow> Rows)> LoadAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var now = await repo.GetServerNowAsync(ct);
|
||||||
|
var rows = (await repo.GetAllAsync(ct)).ToDictionary(r => r.JobKey, StringComparer.OrdinalIgnoreCase);
|
||||||
|
return (now, rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<JobDto> OneAsync(string key, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
var (now, rows) = await LoadAsync(ct);
|
||||||
|
return ToDto(def, rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key), now);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<JobDto>> ListAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var (now, rows) = await LoadAsync(ct);
|
||||||
|
return JobCatalog.All.Select(d => ToDto(d, rows.GetValueOrDefault(d.Key) ?? Defaults(d.Key), now)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<JobDto> SaveScheduleAsync(string key, SaveJobScheduleRequest r, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
var error = JobScheduleRules.Validate(r.ScheduleType, r.IntervalMinutes, r.DailyTimes);
|
||||||
|
if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
|
||||||
|
|
||||||
|
var daily = r.ScheduleType == JobScheduleTypes.Daily;
|
||||||
|
await repo.SaveScheduleAsync(def.Key, r.ScheduleType, daily ? null : r.IntervalMinutes,
|
||||||
|
daily ? JobScheduleRules.JoinTimes(r.DailyTimes) : null, user.UserId, ct);
|
||||||
|
return await OneAsync(def.Key, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<JobDto> StartAsync(string key, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
var (_, rows) = await LoadAsync(ct);
|
||||||
|
var s = rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key);
|
||||||
|
var error = JobScheduleRules.Validate(s.ScheduleType, s.IntervalMinutes, JobScheduleRules.SplitTimes(s.DailyTimes));
|
||||||
|
if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
|
||||||
|
|
||||||
|
await repo.SetEnabledAsync(def.Key, true, user.UserId, ct);
|
||||||
|
return await OneAsync(def.Key, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<JobDto> StopAsync(string key, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
await repo.SetEnabledAsync(def.Key, false, user.UserId, ct);
|
||||||
|
return await OneAsync(def.Key, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<JobActionResult> RunNowAsync(string key, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
return await runner.StartAsync(def.Key, user.UserId, ct) == JobStartResult.Started
|
||||||
|
? new JobActionResult(true, "بدأ تشغيل المهمة")
|
||||||
|
: new JobActionResult(false, "المهمة قيد التنفيذ حاليا");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<JobRunDto>> RunsAsync(string key, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = Def(key);
|
||||||
|
return (await repo.GetRunsAsync(def.Key, 30, ct))
|
||||||
|
.Select(r => new JobRunDto(r.Id, r.StartDate, r.EndDate, r.Status, r.RowsAffected, r.Message, r.TriggeredBy)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<string>> GetDueKeysAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var (now, rows) = await LoadAsync(ct);
|
||||||
|
return JobCatalog.All.Where(d => rows.TryGetValue(d.Key, out var s) && JobScheduleRules.IsDue(s, now)).Select(d => d.Key).ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,103 @@
|
||||||
|
namespace NTP.Application.Jobs;
|
||||||
|
|
||||||
|
/// <summary>How a job is scheduled.</summary>
|
||||||
|
public static class JobScheduleTypes
|
||||||
|
{
|
||||||
|
/// <summary>Every N minutes (the screen offers minutes or hours), counted from the last start.</summary>
|
||||||
|
public const string Interval = "INTERVAL";
|
||||||
|
|
||||||
|
/// <summary>At one or more fixed times of the day (HH:mm, server time).</summary>
|
||||||
|
public const string Daily = "DAILY";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class JobStatuses
|
||||||
|
{
|
||||||
|
public const string Running = "RUNNING";
|
||||||
|
public const string Ok = "OK";
|
||||||
|
public const string Failed = "FAILED";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a job reports when it finishes.</summary>
|
||||||
|
public sealed record JobOutcome(int Count, string? Message = null);
|
||||||
|
|
||||||
|
/// <summary>One job of the catalog: its key, texts and the code that runs it (called in its own DI scope).</summary>
|
||||||
|
public sealed record JobDefinition(
|
||||||
|
string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
|
||||||
|
Func<IServiceProvider, CancellationToken, Task<JobOutcome>> Run);
|
||||||
|
|
||||||
|
/// <summary>GRAINS_JOBS row (a class: Dapper maps Oracle NUMBER onto properties, not onto positional constructors).</summary>
|
||||||
|
public sealed class JobSettingsRow
|
||||||
|
{
|
||||||
|
public string JobKey { get; set; } = string.Empty;
|
||||||
|
public int? Enabled { get; set; }
|
||||||
|
public string? ScheduleType { get; set; }
|
||||||
|
public int? IntervalMinutes { get; set; }
|
||||||
|
public string? DailyTimes { get; set; }
|
||||||
|
public DateTime? LastStart { get; set; }
|
||||||
|
public DateTime? LastEnd { get; set; }
|
||||||
|
public string? LastStatus { get; set; }
|
||||||
|
public string? LastMessage { get; set; }
|
||||||
|
public int? LastCount { get; set; }
|
||||||
|
public DateTime? UpdatedDate { get; set; }
|
||||||
|
public string? UpdatedBy { get; set; }
|
||||||
|
|
||||||
|
public bool IsEnabled => Enabled == 1;
|
||||||
|
public bool IsRunning => string.Equals(LastStatus, JobStatuses.Running, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GRAINS_JOB_RUNS row.</summary>
|
||||||
|
public sealed class JobRunRow
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public string JobKey { get; set; } = string.Empty;
|
||||||
|
public DateTime StartDate { get; set; }
|
||||||
|
public DateTime? EndDate { get; set; }
|
||||||
|
public string? Status { get; set; }
|
||||||
|
public int? RowsAffected { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public string? TriggeredBy { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record JobDto(
|
||||||
|
string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
|
||||||
|
bool Enabled, string ScheduleType, int IntervalMinutes, IReadOnlyList<string> DailyTimes,
|
||||||
|
bool Running, DateTime? LastStart, DateTime? LastEnd, string? LastStatus, string? LastMessage, int? LastCount, DateTime? NextRun);
|
||||||
|
|
||||||
|
public sealed record JobRunDto(long Id, DateTime StartDate, DateTime? EndDate, string? Status, int? RowsAffected, string? Message, string? TriggeredBy);
|
||||||
|
|
||||||
|
public sealed record SaveJobScheduleRequest(string ScheduleType, int? IntervalMinutes, IReadOnlyList<string>? DailyTimes);
|
||||||
|
|
||||||
|
public sealed record JobActionResult(bool Success, string Message);
|
||||||
|
|
||||||
|
public enum JobStartResult { Started, AlreadyRunning }
|
||||||
|
|
||||||
|
/// <summary>Storage of the job settings and of the run history (tables GRAINS_JOBS / GRAINS_JOB_RUNS, script db/grains-jobs.sql).</summary>
|
||||||
|
public interface IJobRepository
|
||||||
|
{
|
||||||
|
/// <summary>Database clock: schedules are judged against it, never against the container clock.</summary>
|
||||||
|
Task<DateTime> GetServerNowAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
|
Task<IReadOnlyList<JobSettingsRow>> GetAllAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Saves the schedule (creates the row when missing, jobs start stopped). Restarts the interval cycle.</summary>
|
||||||
|
Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Start (true) / stop (false). Restarts the interval cycle, so a started job never fires for a time that is already past.</summary>
|
||||||
|
Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Marks the job RUNNING and opens a history row. Returns null when it is already running (a RUNNING mark older than one hour counts as a crash
|
||||||
|
/// and is taken over). The mark lives in the database, so two API instances never run the same job at once.
|
||||||
|
/// </summary>
|
||||||
|
Task<long?> TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default);
|
||||||
|
|
||||||
|
Task FinishRunAsync(long runId, string key, string status, int? rows, string? message, CancellationToken ct = default);
|
||||||
|
|
||||||
|
Task<IReadOnlyList<JobRunRow>> GetRunsAsync(string key, int top, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts a job in the background (own DI scope) and records its run. Implemented in Infrastructure.</summary>
|
||||||
|
public interface IJobRunner
|
||||||
|
{
|
||||||
|
Task<JobStartResult> StartAsync(string key, string triggeredBy, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
@ -3,7 +3,9 @@ using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NTP.Application.Abstractions;
|
using NTP.Application.Abstractions;
|
||||||
using NTP.Application.Common;
|
using NTP.Application.Common;
|
||||||
|
using NTP.Application.Jobs;
|
||||||
using NTP.Infrastructure.HealthChecks;
|
using NTP.Infrastructure.HealthChecks;
|
||||||
|
using NTP.Infrastructure.Jobs;
|
||||||
using NTP.Infrastructure.Persistence;
|
using NTP.Infrastructure.Persistence;
|
||||||
|
|
||||||
namespace NTP.Infrastructure;
|
namespace NTP.Infrastructure;
|
||||||
|
|
@ -50,6 +52,10 @@ public static class DependencyInjection
|
||||||
services.AddScoped<IEventLogger, EventLogger>();
|
services.AddScoped<IEventLogger, EventLogger>();
|
||||||
services.AddSingleton<ISystemErrorLogger, SystemErrorLogger>();
|
services.AddSingleton<ISystemErrorLogger, SystemErrorLogger>();
|
||||||
|
|
||||||
|
// scheduled jobs: the runner starts a job in its own scope, the worker looks for due jobs (screen "المهام المجدولة", SU only)
|
||||||
|
services.AddSingleton<IJobRunner, JobRunner>();
|
||||||
|
services.AddHostedService<JobSchedulerWorker>();
|
||||||
|
|
||||||
// Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped).
|
// Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped).
|
||||||
// Do NOT add per-table lines here.
|
// Do NOT add per-table lines here.
|
||||||
services.AddConventionalServices(typeof(DependencyInjection).Assembly);
|
services.AddConventionalServices(typeof(DependencyInjection).Assembly);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,68 @@
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NTP.Application.Abstractions;
|
||||||
|
using NTP.Application.Common;
|
||||||
|
using NTP.Application.Jobs;
|
||||||
|
|
||||||
|
namespace NTP.Infrastructure.Jobs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs a job of the <see cref="JobCatalog"/> in the background, in its own DI scope (jobs use scoped services and their own transactions),
|
||||||
|
/// and writes the result into GRAINS_JOBS / GRAINS_JOB_RUNS. Used by the scheduler loop ("SCHEDULE") and by the "run now" button (the user id).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class JobRunner(
|
||||||
|
IServiceScopeFactory scopes,
|
||||||
|
ISystemErrorLogger systemErrors,
|
||||||
|
IHostApplicationLifetime lifetime,
|
||||||
|
ILogger<JobRunner> logger) : IJobRunner
|
||||||
|
{
|
||||||
|
public async Task<JobStartResult> StartAsync(string key, string triggeredBy, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var def = JobCatalog.Find(key) ?? throw new NotFoundException("Job", key);
|
||||||
|
|
||||||
|
long? runId;
|
||||||
|
await using (var scope = scopes.CreateAsyncScope())
|
||||||
|
runId = await scope.ServiceProvider.GetRequiredService<IJobRepository>().TryBeginRunAsync(def.Key, triggeredBy, ct);
|
||||||
|
if (runId is null) return JobStartResult.AlreadyRunning;
|
||||||
|
|
||||||
|
// the caller (an HTTP request or the scheduler tick) must not wait for the job
|
||||||
|
_ = Task.Run(() => ExecuteAsync(def, runId.Value, triggeredBy), CancellationToken.None);
|
||||||
|
return JobStartResult.Started;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ExecuteAsync(JobDefinition def, long runId, string triggeredBy)
|
||||||
|
{
|
||||||
|
var stopping = lifetime.ApplicationStopping;
|
||||||
|
string status;
|
||||||
|
int? rows = null;
|
||||||
|
string? message;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var scope = scopes.CreateAsyncScope();
|
||||||
|
var outcome = await def.Run(scope.ServiceProvider, stopping);
|
||||||
|
status = JobStatuses.Ok;
|
||||||
|
rows = outcome.Count;
|
||||||
|
message = outcome.Message;
|
||||||
|
logger.LogInformation("Job {Job} finished ({By}): {Message}", def.Key, triggeredBy, message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
status = JobStatuses.Failed;
|
||||||
|
message = stopping.IsCancellationRequested ? "تم إيقاف التطبيق أثناء التنفيذ" : ex.Message;
|
||||||
|
logger.LogError(ex, "Job {Job} failed ({By})", def.Key, triggeredBy);
|
||||||
|
if (!stopping.IsCancellationRequested)
|
||||||
|
await systemErrors.LogAsync(ex, "SYSTEM", null, null, $"scheduled job {def.Key} ({triggeredBy})");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var scope = scopes.CreateAsyncScope();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<IJobRepository>().FinishRunAsync(runId, def.Key, status, rows, message, CancellationToken.None);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Could not record the end of job {Job}", def.Key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,72 @@
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NTP.Application.Common;
|
||||||
|
using NTP.Application.Jobs;
|
||||||
|
|
||||||
|
namespace NTP.Infrastructure.Jobs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks every 20 seconds for jobs that are due (see <see cref="JobScheduleRules"/>) and starts them. What runs and when is set on the
|
||||||
|
/// SU screen "المهام المجدولة"; nothing runs until a job is started there. <c>Jobs:SchedulerEnabled=false</c> switches the loop off for
|
||||||
|
/// this process (set in appsettings.Development.json so a developer's machine never runs the jobs of a shared database; "run now" still works).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class JobSchedulerWorker(
|
||||||
|
IServiceScopeFactory scopes,
|
||||||
|
IJobRunner runner,
|
||||||
|
IConfiguration configuration,
|
||||||
|
ILogger<JobSchedulerWorker> logger) : BackgroundService
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan Tick = TimeSpan.FromSeconds(20);
|
||||||
|
private DateTime _lastTableWarning = DateTime.MinValue;
|
||||||
|
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
if (configuration.GetValue("Jobs:SchedulerEnabled", true) is false)
|
||||||
|
{
|
||||||
|
logger.LogInformation("Job scheduler is switched off (Jobs:SchedulerEnabled=false)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// let the application finish starting first
|
||||||
|
try { await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); } catch (OperationCanceledException) { return; }
|
||||||
|
|
||||||
|
using var timer = new PeriodicTimer(Tick);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IReadOnlyList<string> due;
|
||||||
|
await using (var scope = scopes.CreateAsyncScope())
|
||||||
|
due = await scope.ServiceProvider.GetRequiredService<IJobService>().GetDueKeysAsync(stoppingToken);
|
||||||
|
|
||||||
|
foreach (var key in due)
|
||||||
|
{
|
||||||
|
var result = await runner.StartAsync(key, "SCHEDULE", stoppingToken);
|
||||||
|
logger.LogInformation("Job {Job} is due: {Result}", key, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (BusinessException ex) when (ex.Code == "JOBS_TABLE_MISSING")
|
||||||
|
{
|
||||||
|
// the script has not been run on this database: say so now and then, not every 20 seconds
|
||||||
|
if (DateTime.UtcNow - _lastTableWarning > TimeSpan.FromMinutes(30))
|
||||||
|
{
|
||||||
|
_lastTableWarning = DateTime.UtcNow;
|
||||||
|
logger.LogWarning("Scheduled jobs are idle: {Message}", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Job scheduler tick failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (await WaitAsync(timer, stoppingToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> WaitAsync(PeriodicTimer timer, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try { return await timer.WaitForNextTickAsync(ct); }
|
||||||
|
catch (OperationCanceledException) { return false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NTP.Application.Grains.Permits;
|
||||||
|
|
||||||
|
namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits;
|
||||||
|
|
||||||
|
/// <summary>SQL of jobs/GRAINS_Close_Old_Permits.cfm.</summary>
|
||||||
|
internal sealed class PermitJobsRepository(IDbSession session, ILogger<PermitJobsRepository> logger)
|
||||||
|
: OracleRepositoryBase(session, logger), IPermitJobsRepository
|
||||||
|
{
|
||||||
|
// Copied from the legacy query, group by group (the same literals, so the effect is identical):
|
||||||
|
// 1. loaded (LGW) more than 48 hours ago and still on its way (released / accepted / at control / cleared), not for destination 215;
|
||||||
|
// 2. destinations 215 / 220 / 225 whose discharge weighing (DGW) is older than 1600 hours and which are cleared;
|
||||||
|
// 3. a truck with two ACCPT / RESD permits: the older one;
|
||||||
|
// 4. a truck with two REQST / PLND permits (PN above 19999999): the older one.
|
||||||
|
public Task<IReadOnlyList<OldPermitRow>> GetOldPermitsToCloseAsync(CancellationToken ct = default) =>
|
||||||
|
QueryAsync<OldPermitRow>("""
|
||||||
|
select p.id as Id, p.shipmentstatuscode as Status
|
||||||
|
from events e, permits p
|
||||||
|
where e.eventtype = 'LGW'
|
||||||
|
and e.domain = 'GN'
|
||||||
|
and e.permitid = p.id
|
||||||
|
and p.destinationaddressid not in ('215')
|
||||||
|
and p.shipmentstatuscode in ('RESD', 'ACCPT', 'ACTRL', 'CLRPR', 'CLPRL')
|
||||||
|
and sysdate - 48 / 24 > e.eventdate
|
||||||
|
and p.isactive = 'Y'
|
||||||
|
union all
|
||||||
|
select p.id, p.shipmentstatuscode
|
||||||
|
from events e, permits p
|
||||||
|
where e.eventtype = 'DGW'
|
||||||
|
and e.domain = 'GN'
|
||||||
|
and e.permitid = p.id
|
||||||
|
and p.destinationaddressid in ('215', '220', '225')
|
||||||
|
and p.shipmentstatuscode in ('CLRPR', 'CLPRL')
|
||||||
|
and sysdate - 1600 / 24 > e.eventdate
|
||||||
|
and p.isactive = 'Y'
|
||||||
|
union all
|
||||||
|
select p.id, p.shipmentstatuscode
|
||||||
|
from permits p, permits p2
|
||||||
|
where p.shipmentstatuscode in ('ACCPT', 'RESD')
|
||||||
|
and p2.shipmentstatuscode in ('ACCPT', 'RESD')
|
||||||
|
and p.tn = p2.tn
|
||||||
|
and p.domain = 'GN'
|
||||||
|
and p2.domain = 'GN'
|
||||||
|
and p.id < p2.id
|
||||||
|
and p.isactive = 'Y'
|
||||||
|
union all
|
||||||
|
select p.id, p.shipmentstatuscode
|
||||||
|
from permits p, permits p2
|
||||||
|
where p.shipmentstatuscode in ('REQST', 'PLND')
|
||||||
|
and p2.shipmentstatuscode in ('REQST', 'PLND')
|
||||||
|
and p.tn = p2.tn
|
||||||
|
and p.domain = 'GN'
|
||||||
|
and p2.domain = 'GN'
|
||||||
|
and p.id < p2.id
|
||||||
|
and p.pn > 19999999
|
||||||
|
and p.isactive = 'Y'
|
||||||
|
""", null, ct);
|
||||||
|
|
||||||
|
public Task<int> CloseAsync(long permitId, string previousStatus, CancellationToken ct = default) =>
|
||||||
|
ExecuteAsync("UPDATE PERMITS SET shipmentstatuscode = 'CLOSE' WHERE id = :Id AND shipmentstatuscode = :Prev",
|
||||||
|
new { Id = permitId, Prev = previousStatus }, ct);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,131 @@
|
||||||
|
using System.Data;
|
||||||
|
using Dapper;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NTP.Application.Common;
|
||||||
|
using NTP.Application.Grains.Registry;
|
||||||
|
using NTP.Application.Jobs;
|
||||||
|
using Oracle.ManagedDataAccess.Client;
|
||||||
|
|
||||||
|
namespace NTP.Infrastructure.Persistence.Repositories.Jobs;
|
||||||
|
|
||||||
|
/// <summary>Tables GRAINS_JOBS and GRAINS_JOB_RUNS of the primary schema (created by db/grains-jobs.sql).</summary>
|
||||||
|
internal sealed class JobRepository(IDbSession session, ILogger<JobRepository> logger)
|
||||||
|
: OracleRepositoryBase(session, logger), IJobRepository
|
||||||
|
{
|
||||||
|
private const int MessageBytes = 500;
|
||||||
|
|
||||||
|
/// <summary>The scheduler must not crash, and the screen must explain, when the script has not been run yet (ORA-00942).</summary>
|
||||||
|
private static async Task<T> Guard<T>(Func<Task<T>> action)
|
||||||
|
{
|
||||||
|
try { return await action(); }
|
||||||
|
catch (OracleException ex) when (ex.Number == 942)
|
||||||
|
{
|
||||||
|
throw new BusinessException("JOBS_TABLE_MISSING", "جداول المهام المجدولة غير موجودة، يرجى تشغيل السكربت db/grains-jobs.sql");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<DateTime> GetServerNowAsync(CancellationToken ct = default) => ExecuteScalarAsync<DateTime>("SELECT SYSDATE FROM DUAL", null, ct);
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<JobSettingsRow>> GetAllAsync(CancellationToken ct = default) => Guard(() => QueryAsync<JobSettingsRow>("""
|
||||||
|
SELECT j.JOBKEY AS JobKey, j.ENABLED AS Enabled, j.SCHEDULETYPE AS ScheduleType, j.INTERVALMINUTES AS IntervalMinutes,
|
||||||
|
j.DAILYTIMES AS DailyTimes, j.LASTSTARTDATE AS LastStart, j.LASTENDDATE AS LastEnd,
|
||||||
|
-- a RUNNING mark without an open run row (a start that failed) or older than an hour (a crash) is not a running job
|
||||||
|
CASE WHEN j.LASTSTATUS = 'RUNNING'
|
||||||
|
AND (j.LASTSTARTDATE < SYSDATE - 1 / 24
|
||||||
|
OR NOT EXISTS (SELECT 1 FROM GRAINS_JOB_RUNS r WHERE r.JOBKEY = j.JOBKEY AND r.STATUS = 'RUNNING'))
|
||||||
|
THEN NULL ELSE j.LASTSTATUS END AS LastStatus,
|
||||||
|
j.LASTMESSAGE AS LastMessage, j.LASTCOUNT AS LastCount, j.UPDATEDATE AS UpdatedDate, j.UPDATEDBY AS UpdatedBy
|
||||||
|
FROM GRAINS_JOBS j
|
||||||
|
""", null, ct));
|
||||||
|
|
||||||
|
public Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default) =>
|
||||||
|
Guard(async () =>
|
||||||
|
{
|
||||||
|
await ExecuteAsync("""
|
||||||
|
MERGE INTO GRAINS_JOBS j
|
||||||
|
USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
|
||||||
|
WHEN MATCHED THEN UPDATE SET j.SCHEDULETYPE = :Type, j.INTERVALMINUTES = :Interval, j.DAILYTIMES = :Times,
|
||||||
|
j.UPDATEDATE = SYSDATE, j.UPDATEDBY = :UserId
|
||||||
|
WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, DAILYTIMES, UPDATEDATE, UPDATEDBY)
|
||||||
|
VALUES (:Key, 0, :Type, :Interval, :Times, SYSDATE, :UserId)
|
||||||
|
""", new { Key = key, Type = scheduleType, Interval = intervalMinutes, Times = dailyTimes, UserId = userId }, ct);
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
public Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default) =>
|
||||||
|
Guard(async () =>
|
||||||
|
{
|
||||||
|
await ExecuteAsync("""
|
||||||
|
MERGE INTO GRAINS_JOBS j
|
||||||
|
USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
|
||||||
|
WHEN MATCHED THEN UPDATE SET j.ENABLED = :Enabled, j.UPDATEDATE = SYSDATE, j.UPDATEDBY = :UserId
|
||||||
|
WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, UPDATEDATE, UPDATEDBY)
|
||||||
|
VALUES (:Key, :Enabled, 'INTERVAL', 60, SYSDATE, :UserId)
|
||||||
|
""", new { Key = key, Enabled = enabled ? 1 : 0, UserId = userId }, ct);
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
public Task<long?> TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default) => Guard<long?>(async () =>
|
||||||
|
{
|
||||||
|
// make sure the row exists (a job that was never configured can still be run by hand)
|
||||||
|
await ExecuteAsync("""
|
||||||
|
MERGE INTO GRAINS_JOBS j
|
||||||
|
USING (SELECT :Key AS k FROM DUAL) s ON (j.JOBKEY = s.k)
|
||||||
|
WHEN NOT MATCHED THEN INSERT (JOBKEY, ENABLED, SCHEDULETYPE, INTERVALMINUTES, UPDATEDATE, UPDATEDBY)
|
||||||
|
VALUES (:Key, 0, 'INTERVAL', 60, SYSDATE, :UserId)
|
||||||
|
""", new { Key = key, UserId = triggeredBy }, ct);
|
||||||
|
|
||||||
|
// The guarded update is the lock: only one caller (in any API instance) can flip the row to RUNNING. A RUNNING mark is also taken
|
||||||
|
// over when no run row is open any more (a start that failed half way) or when it is older than an hour (a crash).
|
||||||
|
var taken = await ExecuteAsync("""
|
||||||
|
UPDATE GRAINS_JOBS
|
||||||
|
SET LASTSTATUS = 'RUNNING', LASTSTARTDATE = SYSDATE, LASTENDDATE = NULL, LASTMESSAGE = NULL, LASTCOUNT = NULL
|
||||||
|
WHERE JOBKEY = :Key
|
||||||
|
AND (LASTSTATUS IS NULL OR LASTSTATUS <> 'RUNNING' OR LASTSTARTDATE < SYSDATE - 1 / 24
|
||||||
|
OR NOT EXISTS (SELECT 1 FROM GRAINS_JOB_RUNS r WHERE r.JOBKEY = :Key AND r.STATUS = 'RUNNING'))
|
||||||
|
""", new { Key = key }, ct);
|
||||||
|
if (taken == 0) return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// bind names must not be Oracle reserved words (BY, ROWS ... give ORA-01745)
|
||||||
|
var p = new DynamicParameters(new { Key = key, RunBy = triggeredBy });
|
||||||
|
p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
|
||||||
|
await ExecuteAsync("""
|
||||||
|
INSERT INTO GRAINS_JOB_RUNS (ID, JOBKEY, STARTDATE, STATUS, TRIGGEREDBY)
|
||||||
|
VALUES (SEQ_GRAINS_JOB_RUNS.NEXTVAL, :Key, SYSDATE, 'RUNNING', :RunBy)
|
||||||
|
RETURNING ID INTO :NewId
|
||||||
|
""", p, ct);
|
||||||
|
return OracleSql.ToInt64(p.Get<object>("NewId"));
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// do not leave the job marked as running when its history row could not be written
|
||||||
|
await ExecuteAsync("UPDATE GRAINS_JOBS SET LASTSTATUS = NULL WHERE JOBKEY = :Key AND LASTSTATUS = 'RUNNING'", new { Key = key }, CancellationToken.None);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
public Task FinishRunAsync(long runId, string key, string status, int? rows, string? message, CancellationToken ct = default) =>
|
||||||
|
Guard(async () =>
|
||||||
|
{
|
||||||
|
var text = RegistryRules.FitBytes(message, MessageBytes);
|
||||||
|
await ExecuteAsync("""
|
||||||
|
UPDATE GRAINS_JOB_RUNS SET ENDDATE = SYSDATE, STATUS = :Status, ROWSAFFECTED = :RowCount, MESSAGE = :Msg WHERE ID = :Id
|
||||||
|
""", new { Status = status, RowCount = rows, Msg = text, Id = runId }, ct);
|
||||||
|
await ExecuteAsync("""
|
||||||
|
UPDATE GRAINS_JOBS SET LASTENDDATE = SYSDATE, LASTSTATUS = :Status, LASTCOUNT = :RowCount, LASTMESSAGE = :Msg WHERE JOBKEY = :Key
|
||||||
|
""", new { Status = status, RowCount = rows, Msg = text, Key = key }, ct);
|
||||||
|
// keep three months of history
|
||||||
|
await ExecuteAsync("DELETE FROM GRAINS_JOB_RUNS WHERE JOBKEY = :Key AND STARTDATE < SYSDATE - 90", new { Key = key }, ct);
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<JobRunRow>> GetRunsAsync(string key, int top, CancellationToken ct = default) => Guard(() => QueryAsync<JobRunRow>("""
|
||||||
|
SELECT * FROM (
|
||||||
|
SELECT r.ID AS Id, r.JOBKEY AS JobKey, r.STARTDATE AS StartDate, r.ENDDATE AS EndDate, r.STATUS AS Status,
|
||||||
|
r.ROWSAFFECTED AS RowsAffected, r.MESSAGE AS Message, r.TRIGGEREDBY AS TriggeredBy
|
||||||
|
FROM GRAINS_JOB_RUNS r WHERE r.JOBKEY = :Key ORDER BY r.ID DESC)
|
||||||
|
WHERE ROWNUM <= :Top
|
||||||
|
""", new { Key = key, Top = top }, ct));
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
using NTP.Application.Jobs;
|
||||||
|
|
||||||
|
namespace NTP.Tests;
|
||||||
|
|
||||||
|
public class JobScheduleRulesTests
|
||||||
|
{
|
||||||
|
private static readonly DateTime T0 = new(2026, 11, 17, 10, 0, 0);
|
||||||
|
|
||||||
|
private static JobSettingsRow Interval(int minutes, DateTime? lastStart = null, DateTime? updated = null, bool enabled = true, string? status = null) => new()
|
||||||
|
{
|
||||||
|
JobKey = "j", Enabled = enabled ? 1 : 0, ScheduleType = JobScheduleTypes.Interval, IntervalMinutes = minutes,
|
||||||
|
LastStart = lastStart, UpdatedDate = updated ?? T0, LastStatus = status
|
||||||
|
};
|
||||||
|
|
||||||
|
private static JobSettingsRow Daily(string times, DateTime? lastStart = null, DateTime? updated = null, bool enabled = true) => new()
|
||||||
|
{
|
||||||
|
JobKey = "j", Enabled = enabled ? 1 : 0, ScheduleType = JobScheduleTypes.Daily, DailyTimes = times, LastStart = lastStart, UpdatedDate = updated ?? T0.AddDays(-5)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- interval
|
||||||
|
[Fact]
|
||||||
|
public void Interval_runs_one_interval_after_it_was_started_not_at_once()
|
||||||
|
{
|
||||||
|
var s = Interval(30, updated: T0);
|
||||||
|
Assert.False(JobScheduleRules.IsDue(s, T0.AddMinutes(29)));
|
||||||
|
Assert.True(JobScheduleRules.IsDue(s, T0.AddMinutes(30)));
|
||||||
|
Assert.Equal(T0.AddMinutes(30), JobScheduleRules.NextRun(s, T0.AddMinutes(5)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Interval_is_counted_from_the_last_start()
|
||||||
|
{
|
||||||
|
var s = Interval(60, lastStart: T0.AddMinutes(100), updated: T0);
|
||||||
|
Assert.False(JobScheduleRules.IsDue(s, T0.AddMinutes(159)));
|
||||||
|
Assert.True(JobScheduleRules.IsDue(s, T0.AddMinutes(160)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_stopped_or_running_job_is_never_due()
|
||||||
|
{
|
||||||
|
Assert.False(JobScheduleRules.IsDue(Interval(1, enabled: false), T0.AddDays(1)));
|
||||||
|
Assert.Null(JobScheduleRules.NextRun(Interval(1, enabled: false), T0));
|
||||||
|
Assert.False(JobScheduleRules.IsDue(Interval(1, status: JobStatuses.Running), T0.AddDays(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- daily
|
||||||
|
[Fact]
|
||||||
|
public void Daily_runs_at_the_time_and_only_once()
|
||||||
|
{
|
||||||
|
var s = Daily("02:00", updated: T0.AddDays(-5));
|
||||||
|
var at = new DateTime(2026, 11, 18, 2, 0, 20);
|
||||||
|
Assert.True(JobScheduleRules.IsDue(s, at));
|
||||||
|
s.LastStart = at; // the run started
|
||||||
|
Assert.False(JobScheduleRules.IsDue(s, at.AddMinutes(1)));
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 19, 2, 0, 0), JobScheduleRules.NextRun(s, at.AddMinutes(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Daily_with_several_times_picks_each_in_turn()
|
||||||
|
{
|
||||||
|
var s = Daily("06:00,18:30", updated: T0.AddDays(-5));
|
||||||
|
Assert.True(JobScheduleRules.IsDue(s, new DateTime(2026, 11, 17, 18, 30, 5)));
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 17, 18, 30, 0), JobScheduleRules.NextRun(s, new DateTime(2026, 11, 17, 10, 0, 0)));
|
||||||
|
Assert.Equal(new DateTime(2026, 11, 18, 6, 0, 0), JobScheduleRules.NextRun(s, new DateTime(2026, 11, 17, 20, 0, 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Saving_after_the_time_has_passed_does_not_run_it_retroactively()
|
||||||
|
{
|
||||||
|
var s = Daily("10:00", updated: new DateTime(2026, 11, 17, 10, 5, 0)); // saved at 10:05
|
||||||
|
Assert.False(JobScheduleRules.IsDue(s, new DateTime(2026, 11, 17, 10, 6, 0)));
|
||||||
|
Assert.True(JobScheduleRules.IsDue(Daily("10:00", updated: new DateTime(2026, 11, 17, 9, 58, 0)), new DateTime(2026, 11, 17, 10, 0, 10)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void A_missed_daily_time_is_caught_up_only_within_half_an_hour()
|
||||||
|
{
|
||||||
|
var s = Daily("02:00", updated: T0.AddDays(-5));
|
||||||
|
Assert.True(JobScheduleRules.IsDue(s, new DateTime(2026, 11, 17, 2, 29, 0))); // restart shortly after the time
|
||||||
|
Assert.False(JobScheduleRules.IsDue(s, new DateTime(2026, 11, 17, 9, 0, 0))); // hours later: wait for tomorrow
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- validation
|
||||||
|
[Theory]
|
||||||
|
[InlineData("INTERVAL", 1, null, true)]
|
||||||
|
[InlineData("INTERVAL", 0, null, false)]
|
||||||
|
[InlineData("INTERVAL", 10081, null, false)]
|
||||||
|
[InlineData("DAILY", null, "02:00", true)]
|
||||||
|
[InlineData("DAILY", null, "2:00", false)]
|
||||||
|
[InlineData("DAILY", null, "24:00", false)]
|
||||||
|
[InlineData("DAILY", null, "", false)]
|
||||||
|
[InlineData("WEEKLY", 5, "02:00", false)]
|
||||||
|
public void Schedules_are_validated(string type, int? minutes, string? time, bool valid)
|
||||||
|
{
|
||||||
|
IReadOnlyList<string>? times = time is null ? null : time == "" ? [] : [time];
|
||||||
|
Assert.Equal(valid, JobScheduleRules.Validate(type, minutes, times) is null);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Times_are_normalised_sorted_and_deduplicated()
|
||||||
|
{
|
||||||
|
Assert.Equal("02:00,13:30", JobScheduleRules.JoinTimes(["13:30", "02:00", "13:30", "bad"]));
|
||||||
|
Assert.Equal(["02:00", "13:30"], JobScheduleRules.SplitTimes("13:30, 02:00,x"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void The_catalog_has_the_three_legacy_jobs_with_unique_keys()
|
||||||
|
{
|
||||||
|
Assert.Equal(3, JobCatalog.All.Count);
|
||||||
|
Assert.Equal(JobCatalog.All.Count, JobCatalog.All.Select(j => j.Key).Distinct().Count());
|
||||||
|
Assert.NotNull(JobCatalog.Find("CLOSE-OLD-PERMITS"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { api } from '@/api/client';
|
||||||
|
import { useWrite } from '@/api/hooks';
|
||||||
|
|
||||||
|
const base = '/grains/jobs';
|
||||||
|
const jobsKey = ['jobs'];
|
||||||
|
|
||||||
|
export interface JobItem {
|
||||||
|
key: string;
|
||||||
|
titleAr: string; titleEn: string; descriptionAr: string; descriptionEn: string;
|
||||||
|
enabled: boolean;
|
||||||
|
scheduleType: 'INTERVAL' | 'DAILY';
|
||||||
|
intervalMinutes: number;
|
||||||
|
dailyTimes: string[];
|
||||||
|
running: boolean;
|
||||||
|
lastStart: string | null; lastEnd: string | null; lastStatus: string | null; lastMessage: string | null; lastCount: number | null;
|
||||||
|
nextRun: string | null;
|
||||||
|
}
|
||||||
|
export interface JobRun {
|
||||||
|
id: number; startDate: string; endDate: string | null; status: string | null; rowsAffected: number | null; message: string | null; triggeredBy: string | null;
|
||||||
|
}
|
||||||
|
export interface ScheduleBody { scheduleType: 'INTERVAL' | 'DAILY'; intervalMinutes: number | null; dailyTimes: string[] | null }
|
||||||
|
export interface JobActionResult { success: boolean; message: string }
|
||||||
|
|
||||||
|
/** Refreshed every 10 seconds so a running job and its result show without reloading the page. */
|
||||||
|
export function useJobs() {
|
||||||
|
return useQuery({ queryKey: jobsKey, queryFn: () => api.get<JobItem[]>(base), refetchInterval: 10_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useJobRuns(key: string | null) {
|
||||||
|
return useQuery({ queryKey: [...jobsKey, 'runs', key], queryFn: () => api.get<JobRun[]>(`${base}/${key}/runs`), enabled: !!key });
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useSaveSchedule = (message: string) =>
|
||||||
|
useWrite((v: { key: string; body: ScheduleBody }) => api.put<JobItem>(`${base}/${v.key}`, v.body), { invalidate: [jobsKey], successMessage: message });
|
||||||
|
|
||||||
|
export const useStartJob = (message: string) =>
|
||||||
|
useWrite((key: string) => api.post<JobItem>(`${base}/${key}/start`), { invalidate: [jobsKey], successMessage: message });
|
||||||
|
|
||||||
|
export const useStopJob = (message: string) =>
|
||||||
|
useWrite((key: string) => api.post<JobItem>(`${base}/${key}/stop`), { invalidate: [jobsKey], successMessage: message });
|
||||||
|
|
||||||
|
/** The answer carries its own message ("started" / "already running"), shown by the page. */
|
||||||
|
export const useRunJob = () =>
|
||||||
|
useWrite((key: string) => api.post<JobActionResult>(`${base}/${key}/run`), { invalidate: [jobsKey], toastSuccess: false });
|
||||||
|
|
@ -0,0 +1,265 @@
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, MenuItem, Stack, Table, TableBody,
|
||||||
|
TableCell, TableContainer, TableHead, TableRow, TextField, ToggleButton, ToggleButtonGroup, Typography,
|
||||||
|
} from '@mui/material';
|
||||||
|
import AddIcon from '@mui/icons-material/Add';
|
||||||
|
import HistoryIcon from '@mui/icons-material/History';
|
||||||
|
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
|
||||||
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
|
import ScheduleIcon from '@mui/icons-material/Schedule';
|
||||||
|
import StopIcon from '@mui/icons-material/Stop';
|
||||||
|
import CloseIcon from '@mui/icons-material/Close';
|
||||||
|
import { EmptyState } from '@/components/EmptyState';
|
||||||
|
import { LoadingBanner } from '@/components/LoadingBanner';
|
||||||
|
import { PageHeader } from '@/components/PageHeader';
|
||||||
|
import { SectionPaper as Paper } from '@/components/SectionPaper';
|
||||||
|
import { formatDateTime, formatNumber } from '@/components/meta/format';
|
||||||
|
import { useFeatureUi } from '@/i18n/useUi';
|
||||||
|
import { useConfirm } from '@/providers/ConfirmProvider';
|
||||||
|
import { useToast } from '@/providers/ToastProvider';
|
||||||
|
import {
|
||||||
|
useJobRuns, useJobs, useRunJob, useSaveSchedule, useStartJob, useStopJob, type JobItem, type ScheduleBody,
|
||||||
|
} from './api';
|
||||||
|
import strings from './strings';
|
||||||
|
|
||||||
|
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||||
|
|
||||||
|
/** Digits typed -> HH:mm (always 24-hour, whatever the browser language is). */
|
||||||
|
function maskTime(raw: string): string {
|
||||||
|
const d = raw.replace(/\D/g, '').slice(0, 4);
|
||||||
|
return d.length <= 2 ? d : `${d.slice(0, 2)}:${d.slice(2)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** minutes -> the number and unit shown (whole hours are shown as hours). */
|
||||||
|
function toUnit(minutes: number): { value: string; unit: 'minutes' | 'hours' } {
|
||||||
|
return minutes >= 60 && minutes % 60 === 0 ? { value: String(minutes / 60), unit: 'hours' } : { value: String(minutes), unit: 'minutes' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusColor(status: string | null): 'success' | 'error' | 'info' | 'default' {
|
||||||
|
return status === 'OK' ? 'success' : status === 'FAILED' ? 'error' : status === 'RUNNING' ? 'info' : 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JobsPage() {
|
||||||
|
const { t } = useFeatureUi(strings);
|
||||||
|
const jobs = useJobs();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title={t('jobs.title')} subtitle={t('jobs.subtitle')} />
|
||||||
|
{jobs.isLoading ? (
|
||||||
|
<LoadingBanner />
|
||||||
|
) : jobs.error ? (
|
||||||
|
<Alert severity="error">{jobs.error instanceof Error ? jobs.error.message : t('jobs.loadError')}</Alert>
|
||||||
|
) : (jobs.data ?? []).length === 0 ? (
|
||||||
|
<EmptyState title={t('jobs.empty')} />
|
||||||
|
) : (
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{/* remount when the saved schedule changes so the draft follows the server, not every 10-second refresh */}
|
||||||
|
{(jobs.data ?? []).map((j) => (
|
||||||
|
<JobCard key={`${j.key}|${j.scheduleType}|${j.intervalMinutes}|${j.dailyTimes.join(',')}`} job={j} />
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function JobCard({ job }: { job: JobItem }) {
|
||||||
|
const { t, lang } = useFeatureUi(strings);
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
|
const save = useSaveSchedule(t('jobs.saved'));
|
||||||
|
const start = useStartJob(t('jobs.startedOk'));
|
||||||
|
const stop = useStopJob(t('jobs.stoppedOk'));
|
||||||
|
const run = useRunJob();
|
||||||
|
|
||||||
|
const first = toUnit(job.intervalMinutes);
|
||||||
|
const [type, setType] = useState<'INTERVAL' | 'DAILY'>(job.scheduleType);
|
||||||
|
const [amount, setAmount] = useState(first.value);
|
||||||
|
const [unit, setUnit] = useState<'minutes' | 'hours'>(first.unit);
|
||||||
|
const [times, setTimes] = useState<string[]>(job.dailyTimes);
|
||||||
|
const [newTime, setNewTime] = useState('');
|
||||||
|
const [showHistory, setShowHistory] = useState(false);
|
||||||
|
|
||||||
|
const minutes = Number(amount) * (unit === 'hours' ? 60 : 1);
|
||||||
|
const intervalOk = Number.isInteger(minutes) && minutes >= 1 && minutes <= 7 * 24 * 60;
|
||||||
|
const scheduleOk = type === 'INTERVAL' ? intervalOk : times.length > 0;
|
||||||
|
const body: ScheduleBody = type === 'INTERVAL'
|
||||||
|
? { scheduleType: 'INTERVAL', intervalMinutes: minutes, dailyTimes: null }
|
||||||
|
: { scheduleType: 'DAILY', intervalMinutes: null, dailyTimes: times };
|
||||||
|
const dirty = type !== job.scheduleType
|
||||||
|
|| (type === 'INTERVAL' ? minutes !== job.intervalMinutes : times.join(',') !== job.dailyTimes.join(','));
|
||||||
|
const busy = save.isPending || start.isPending || stop.isPending || run.isPending;
|
||||||
|
|
||||||
|
const title = lang === 'ar' ? job.titleAr : job.titleEn;
|
||||||
|
const description = lang === 'ar' ? job.descriptionAr : job.descriptionEn;
|
||||||
|
const state = job.running ? 'running' : job.enabled ? 'started' : 'stopped';
|
||||||
|
|
||||||
|
const addTime = () => {
|
||||||
|
if (!TIME_RE.test(newTime) || times.includes(newTime)) return;
|
||||||
|
setTimes([...times, newTime].sort());
|
||||||
|
setNewTime('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveOnly = () => save.mutate({ key: job.key, body });
|
||||||
|
// starting uses the schedule on screen: an unsaved change is saved first
|
||||||
|
const startJob = () => {
|
||||||
|
if (!dirty) { start.mutate(job.key); return; }
|
||||||
|
save.mutate({ key: job.key, body }, { onSuccess: () => start.mutate(job.key) });
|
||||||
|
};
|
||||||
|
const runNow = async () => {
|
||||||
|
if (!(await confirm({ message: t('jobs.runNowConfirm') }))) return;
|
||||||
|
run.mutate(job.key, { onSuccess: (r) => (r.success ? toast.success(r.message) : toast.warning(r.message)) });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper sx={{ p: 2 }}>
|
||||||
|
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>
|
||||||
|
<ScheduleIcon color="primary" />
|
||||||
|
<Box sx={{ flex: 1, minWidth: 220 }}>
|
||||||
|
<Typography sx={{ fontWeight: 700 }}>{title}</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary" dir="ltr" sx={{ display: 'block', textAlign: 'start' }}>{job.key}</Typography>
|
||||||
|
</Box>
|
||||||
|
<Chip
|
||||||
|
label={t(`jobs.state.${state}` as const)}
|
||||||
|
color={state === 'running' ? 'info' : state === 'started' ? 'success' : 'default'}
|
||||||
|
variant={state === 'stopped' ? 'outlined' : 'filled'}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>{description}</Typography>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'grid', gap: 2, mt: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" color="text.secondary">{t('jobs.lastRun')}</Typography>
|
||||||
|
{job.lastStart ? (
|
||||||
|
<Stack spacing={0.5}>
|
||||||
|
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||||
|
<Typography dir="ltr">{formatDateTime(job.lastStart, lang)}</Typography>
|
||||||
|
{job.lastStatus && <Chip size="small" label={t(`jobs.status.${job.lastStatus}` as 'jobs.status.OK')} color={statusColor(job.lastStatus)} />}
|
||||||
|
{job.lastCount !== null && <Typography variant="body2">{t('jobs.rows')}: <span dir="ltr">{formatNumber(job.lastCount, lang)}</span></Typography>}
|
||||||
|
</Stack>
|
||||||
|
{job.lastMessage && <Typography variant="body2" color="text.secondary">{job.lastMessage}</Typography>}
|
||||||
|
</Stack>
|
||||||
|
) : (
|
||||||
|
<Typography color="text.secondary">{t('jobs.never')}</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" color="text.secondary">{t('jobs.nextRun')}</Typography>
|
||||||
|
<Typography dir="ltr" sx={{ textAlign: 'start' }}>{job.nextRun ? formatDateTime(job.nextRun, lang) : '-'}</Typography>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Typography variant="subtitle2" sx={{ mt: 2.5, mb: 1 }}>{t('jobs.schedule')}</Typography>
|
||||||
|
<Stack spacing={1.5}>
|
||||||
|
<ToggleButtonGroup exclusive size="small" color="primary" value={type} onChange={(_, v: 'INTERVAL' | 'DAILY' | null) => v && setType(v)}>
|
||||||
|
<ToggleButton value="INTERVAL">{t('jobs.type.interval')}</ToggleButton>
|
||||||
|
<ToggleButton value="DAILY">{t('jobs.type.daily')}</ToggleButton>
|
||||||
|
</ToggleButtonGroup>
|
||||||
|
|
||||||
|
{type === 'INTERVAL' ? (
|
||||||
|
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||||
|
<Typography>{t('jobs.every')}</Typography>
|
||||||
|
<TextField
|
||||||
|
size="small" value={amount} sx={{ width: 100 }} error={!intervalOk} helperText={!intervalOk ? t('jobs.badInterval') : undefined}
|
||||||
|
onChange={(e) => setAmount(e.target.value.replace(/\D/g, '').slice(0, 5))}
|
||||||
|
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }}
|
||||||
|
/>
|
||||||
|
<TextField select size="small" value={unit} sx={{ width: 120 }} onChange={(e) => setUnit(e.target.value as 'minutes' | 'hours')}>
|
||||||
|
<MenuItem value="minutes">{t('jobs.unit.minutes')}</MenuItem>
|
||||||
|
<MenuItem value="hours">{t('jobs.unit.hours')}</MenuItem>
|
||||||
|
</TextField>
|
||||||
|
</Stack>
|
||||||
|
) : (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>{t('jobs.times')}</Typography>
|
||||||
|
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||||
|
{times.map((x) => (
|
||||||
|
<Chip key={x} label={<span dir="ltr">{x}</span>} onDelete={() => setTimes(times.filter((y) => y !== x))} />
|
||||||
|
))}
|
||||||
|
<TextField
|
||||||
|
size="small" value={newTime} placeholder={t('jobs.timeHint')} sx={{ width: 110 }}
|
||||||
|
onChange={(e) => setNewTime(maskTime(e.target.value))}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addTime(); } }}
|
||||||
|
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr', maxLength: 5 } }}
|
||||||
|
/>
|
||||||
|
<Button size="small" startIcon={<AddIcon />} disabled={!TIME_RE.test(newTime) || times.includes(newTime)} onClick={addTime}>
|
||||||
|
{t('jobs.addTime')}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
{times.length === 0 && <Typography variant="caption" color="error">{t('jobs.noTimes')}</Typography>}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Stack direction="row" spacing={1} useFlexGap sx={{ mt: 2.5, flexWrap: 'wrap' }}>
|
||||||
|
<Button variant="outlined" startIcon={<SaveIcon />} disabled={busy || !scheduleOk || !dirty} onClick={saveOnly}>{t('jobs.save')}</Button>
|
||||||
|
{job.enabled ? (
|
||||||
|
<Button variant="outlined" color="error" startIcon={<StopIcon />} disabled={busy} onClick={() => stop.mutate(job.key)}>{t('jobs.stop')}</Button>
|
||||||
|
) : (
|
||||||
|
<Button variant="contained" startIcon={<PlayArrowIcon />} disabled={busy || !scheduleOk} onClick={startJob}>
|
||||||
|
{dirty ? t('jobs.saveStart') : t('jobs.start')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button startIcon={<PlayArrowIcon />} disabled={busy || job.running} onClick={() => void runNow()}>{t('jobs.runNow')}</Button>
|
||||||
|
<Button startIcon={<HistoryIcon />} onClick={() => setShowHistory(true)}>{t('jobs.history')}</Button>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{showHistory && <HistoryDialog jobKey={job.key} title={title} onClose={() => setShowHistory(false)} />}
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HistoryDialog({ jobKey, title, onClose }: { jobKey: string; title: string; onClose: () => void }) {
|
||||||
|
const { t, lang } = useFeatureUi(strings);
|
||||||
|
const runs = useJobRuns(jobKey);
|
||||||
|
const rows = useMemo(() => runs.data ?? [], [runs.data]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onClose={onClose} fullWidth maxWidth="md">
|
||||||
|
<DialogTitle sx={{ display: 'flex', alignItems: 'center' }}>
|
||||||
|
<Box sx={{ flex: 1 }}>{t('jobs.h.title')} - {title}</Box>
|
||||||
|
<IconButton size="small" aria-label={t('jobs.close')} onClick={onClose}><CloseIcon fontSize="small" /></IconButton>
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
{runs.isLoading ? (
|
||||||
|
<LoadingBanner variant="update" />
|
||||||
|
) : rows.length === 0 ? (
|
||||||
|
<Typography color="text.secondary">{t('jobs.h.none')}</Typography>
|
||||||
|
) : (
|
||||||
|
<TableContainer>
|
||||||
|
<Table size="small">
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>{t('jobs.h.start')}</TableCell>
|
||||||
|
<TableCell>{t('jobs.h.end')}</TableCell>
|
||||||
|
<TableCell>{t('jobs.h.status')}</TableCell>
|
||||||
|
<TableCell align="center">{t('jobs.h.rows')}</TableCell>
|
||||||
|
<TableCell>{t('jobs.h.by')}</TableCell>
|
||||||
|
<TableCell>{t('jobs.h.message')}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{rows.map((r) => (
|
||||||
|
<TableRow key={r.id}>
|
||||||
|
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{formatDateTime(r.startDate, lang)}</TableCell>
|
||||||
|
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.endDate ? formatDateTime(r.endDate, lang) : ''}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{r.status && <Chip size="small" label={t(`jobs.status.${r.status}` as 'jobs.status.OK')} color={statusColor(r.status)} />}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell align="center" dir="ltr">{r.rowsAffected === null ? '' : formatNumber(r.rowsAffected, lang)}</TableCell>
|
||||||
|
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.triggeredBy === 'SCHEDULE' ? t('jobs.h.schedule') : r.triggeredBy}</TableCell>
|
||||||
|
<TableCell>{r.message}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions><Button onClick={onClose}>{t('jobs.close')}</Button></DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
import type { RouteObject } from 'react-router-dom';
|
||||||
|
import ScheduleIcon from '@mui/icons-material/Schedule';
|
||||||
|
import type { MenuItem } from '@/shell/types';
|
||||||
|
import { JobsPage } from './pages';
|
||||||
|
import strings from './strings';
|
||||||
|
|
||||||
|
// Super users only (the API refuses everybody else). The folder is called "jobs" so that the menu lists it after the Grains modules.
|
||||||
|
export const routes: RouteObject[] = [{ path: '/jobs', element: <JobsPage /> }];
|
||||||
|
|
||||||
|
export const menu: MenuItem[] = [
|
||||||
|
{ key: 'jobs', title: strings['jobs.menu'], icon: ScheduleIcon, path: '/jobs', roles: ['SU'] },
|
||||||
|
];
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { defineStrings } from '@/i18n/useUi';
|
||||||
|
|
||||||
|
/** Strings of the scheduled jobs screen (prefix `jobs.`). */
|
||||||
|
export default defineStrings({
|
||||||
|
'jobs.menu': { en: 'Scheduled jobs', ar: 'المهام المجدولة' },
|
||||||
|
'jobs.title': { en: 'Scheduled jobs', ar: 'المهام المجدولة' },
|
||||||
|
'jobs.subtitle': { en: 'Start or stop the background jobs and choose when they run', ar: 'تشغيل وإيقاف المهام الخلفية وتحديد وقت تشغيلها' },
|
||||||
|
'jobs.empty': { en: 'No jobs', ar: 'لا توجد مهام' },
|
||||||
|
'jobs.loadError': { en: 'Could not load the jobs', ar: 'تعذر تحميل المهام' },
|
||||||
|
|
||||||
|
'jobs.state.running': { en: 'Running now', ar: 'قيد التنفيذ' },
|
||||||
|
'jobs.state.started': { en: 'Started', ar: 'مفعّلة' },
|
||||||
|
'jobs.state.stopped': { en: 'Stopped', ar: 'متوقفة' },
|
||||||
|
|
||||||
|
'jobs.schedule': { en: 'Running time', ar: 'وقت التشغيل' },
|
||||||
|
'jobs.type.interval': { en: 'Every', ar: 'كل فترة' },
|
||||||
|
'jobs.type.daily': { en: 'At a fixed time', ar: 'في وقت محدد' },
|
||||||
|
'jobs.every': { en: 'Every', ar: 'كل' },
|
||||||
|
'jobs.unit.minutes': { en: 'minutes', ar: 'دقيقة' },
|
||||||
|
'jobs.unit.hours': { en: 'hours', ar: 'ساعة' },
|
||||||
|
'jobs.times': { en: 'Times of the day (server time)', ar: 'أوقات اليوم (توقيت الخادم)' },
|
||||||
|
'jobs.addTime': { en: 'Add', ar: 'إضافة' },
|
||||||
|
'jobs.timeHint': { en: 'HH:mm', ar: 'ساعة:دقيقة' },
|
||||||
|
'jobs.noTimes': { en: 'Add at least one time', ar: 'أضف وقتا واحدا على الأقل' },
|
||||||
|
'jobs.badInterval': { en: 'The period must be between 1 minute and 7 days', ar: 'الفترة يجب أن تكون بين دقيقة واحدة و 7 أيام' },
|
||||||
|
|
||||||
|
'jobs.lastRun': { en: 'Last run', ar: 'آخر تشغيل' },
|
||||||
|
'jobs.nextRun': { en: 'Next run', ar: 'التشغيل القادم' },
|
||||||
|
'jobs.never': { en: 'Never', ar: 'لم تعمل بعد' },
|
||||||
|
'jobs.rows': { en: 'Rows', ar: 'العدد' },
|
||||||
|
'jobs.status.OK': { en: 'Succeeded', ar: 'نجحت' },
|
||||||
|
'jobs.status.FAILED': { en: 'Failed', ar: 'فشلت' },
|
||||||
|
'jobs.status.RUNNING': { en: 'Running', ar: 'قيد التنفيذ' },
|
||||||
|
|
||||||
|
'jobs.save': { en: 'Save time', ar: 'حفظ الوقت' },
|
||||||
|
'jobs.start': { en: 'Start', ar: 'تشغيل' },
|
||||||
|
'jobs.saveStart': { en: 'Save and start', ar: 'حفظ وتشغيل' },
|
||||||
|
'jobs.stop': { en: 'Stop', ar: 'إيقاف' },
|
||||||
|
'jobs.runNow': { en: 'Run now', ar: 'تنفيذ الآن' },
|
||||||
|
'jobs.runNowConfirm': { en: 'Run this job now?', ar: 'هل تريد تنفيذ هذه المهمة الآن؟' },
|
||||||
|
'jobs.history': { en: 'History', ar: 'السجل' },
|
||||||
|
'jobs.saved': { en: 'The running time was saved', ar: 'تم حفظ وقت التشغيل' },
|
||||||
|
'jobs.startedOk': { en: 'The job is started', ar: 'تم تشغيل المهمة' },
|
||||||
|
'jobs.stoppedOk': { en: 'The job is stopped', ar: 'تم إيقاف المهمة' },
|
||||||
|
|
||||||
|
'jobs.h.title': { en: 'Run history', ar: 'سجل التنفيذ' },
|
||||||
|
'jobs.h.start': { en: 'Started', ar: 'البداية' },
|
||||||
|
'jobs.h.end': { en: 'Ended', ar: 'النهاية' },
|
||||||
|
'jobs.h.status': { en: 'Result', ar: 'النتيجة' },
|
||||||
|
'jobs.h.rows': { en: 'Rows', ar: 'العدد' },
|
||||||
|
'jobs.h.by': { en: 'By', ar: 'بواسطة' },
|
||||||
|
'jobs.h.message': { en: 'Message', ar: 'ملاحظة' },
|
||||||
|
'jobs.h.none': { en: 'No runs yet', ar: 'لا يوجد تنفيذ بعد' },
|
||||||
|
'jobs.h.schedule': { en: 'Scheduler', ar: 'المجدول' },
|
||||||
|
'jobs.close': { en: 'Close', ar: 'إغلاق' },
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue