From 025fbe9af894bf794fb60197ed9b3b6e704cec86 Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Tue, 17 Nov 2026 17:15:24 +0300 Subject: [PATCH] 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 --- CLAUDE.md | 1 + db/grains-jobs.sql | 53 ++++ docs/ENVIRONMENTS.md | 1 + docs/HANDOVER.md | 3 + .../Controllers/V1/Grains/JobsController.cs | 38 +++ src/NTP.Api/appsettings.Development.json | 2 + .../Grains/Permits/PermitJobsService.cs | 50 ++++ src/NTP.Application/Jobs/JobCatalog.cs | 47 ++++ src/NTP.Application/Jobs/JobScheduleRules.cs | 119 ++++++++ src/NTP.Application/Jobs/JobService.cs | 107 +++++++ src/NTP.Application/Jobs/JobsContracts.cs | 103 +++++++ src/NTP.Infrastructure/DependencyInjection.cs | 6 + src/NTP.Infrastructure/Jobs/JobRunner.cs | 68 +++++ .../Jobs/JobSchedulerWorker.cs | 72 +++++ .../Grains/Permits/PermitJobsRepository.cs | 62 ++++ .../Repositories/Jobs/JobRepository.cs | 131 +++++++++ tests/NTP.Tests/JobScheduleRulesTests.cs | 113 ++++++++ web/src/features/jobs/api.ts | 45 +++ web/src/features/jobs/pages.tsx | 265 ++++++++++++++++++ web/src/features/jobs/routes.tsx | 12 + web/src/features/jobs/strings.ts | 56 ++++ 21 files changed, 1354 insertions(+) create mode 100644 db/grains-jobs.sql create mode 100644 src/NTP.Api/Controllers/V1/Grains/JobsController.cs create mode 100644 src/NTP.Application/Grains/Permits/PermitJobsService.cs create mode 100644 src/NTP.Application/Jobs/JobCatalog.cs create mode 100644 src/NTP.Application/Jobs/JobScheduleRules.cs create mode 100644 src/NTP.Application/Jobs/JobService.cs create mode 100644 src/NTP.Application/Jobs/JobsContracts.cs create mode 100644 src/NTP.Infrastructure/Jobs/JobRunner.cs create mode 100644 src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs create mode 100644 src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs create mode 100644 src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs create mode 100644 tests/NTP.Tests/JobScheduleRulesTests.cs create mode 100644 web/src/features/jobs/api.ts create mode 100644 web/src/features/jobs/pages.tsx create mode 100644 web/src/features/jobs/routes.tsx create mode 100644 web/src/features/jobs/strings.ts diff --git a/CLAUDE.md b/CLAUDE.md index f3aa56a..23a7d9c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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.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 +- `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`) ## Commands (Windows; Git Bash or PowerShell) diff --git a/db/grains-jobs.sql b/db/grains-jobs.sql new file mode 100644 index 0000000..4af3bd3 --- /dev/null +++ b/db/grains-jobs.sql @@ -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; diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index bcc5536..dc9a771 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -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) 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) +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) **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index fc7d146..817379a 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -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). - **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. +- **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`. - **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. @@ -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). ## 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 `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. diff --git a/src/NTP.Api/Controllers/V1/Grains/JobsController.cs b/src/NTP.Api/Controllers/V1/Grains/JobsController.cs new file mode 100644 index 0000000..d644382 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/JobsController.cs @@ -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; + +/// +/// 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. +/// +[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> List(CancellationToken ct) => jobs.ListAsync(ct); + + /// Running time: every N minutes (INTERVAL) or at fixed times of the day (DAILY, HH:mm). + [HttpPut("{key}")] + public Task SaveSchedule(string key, SaveJobScheduleRequest request, CancellationToken ct) => jobs.SaveScheduleAsync(key, request, ct); + + [HttpPost("{key}/start")] + public Task Start(string key, CancellationToken ct) => jobs.StartAsync(key, ct); + + [HttpPost("{key}/stop")] + public Task Stop(string key, CancellationToken ct) => jobs.StopAsync(key, ct); + + /// Starts the job now in the background, whether it is started or stopped; refuses when it is already running. + [HttpPost("{key}/run")] + public Task Run(string key, CancellationToken ct) => jobs.RunNowAsync(key, ct); + + [HttpGet("{key}/runs")] + public Task> Runs(string key, CancellationToken ct) => jobs.RunsAsync(key, ct); +} diff --git a/src/NTP.Api/appsettings.Development.json b/src/NTP.Api/appsettings.Development.json index 545ff69..b092037 100644 --- a/src/NTP.Api/appsettings.Development.json +++ b/src/NTP.Api/appsettings.Development.json @@ -2,6 +2,8 @@ "Auth": { "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": { "LogLevel": { "Default": "Information", diff --git a/src/NTP.Application/Grains/Permits/PermitJobsService.cs b/src/NTP.Application/Grains/Permits/PermitJobsService.cs new file mode 100644 index 0000000..a7baa22 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitJobsService.cs @@ -0,0 +1,50 @@ +using NTP.Application.Abstractions; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +/// A permit that jobs/GRAINS_Close_Old_Permits.cfm closes. +public sealed class OldPermitRow +{ + public long Id { get; set; } + public string? Status { get; set; } +} + +public interface IPermitJobsRepository +{ + /// The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules). + Task> GetOldPermitsToCloseAsync(CancellationToken ct = default); + + /// Sets CLOSE only while the permit still has the status it was found with; returns the rows changed. + Task CloseAsync(long permitId, string previousStatus, CancellationToken ct = default); +} + +public interface IPermitJobsService +{ + /// jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed. + Task CloseOldPermitsAsync(CancellationToken ct = default); +} + +public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService +{ + public async Task CloseOldPermitsAsync(CancellationToken ct = default) + { + var rows = await repo.GetOldPermitsToCloseAsync(ct); + var seen = new HashSet(); + 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; + } +} diff --git a/src/NTP.Application/Jobs/JobCatalog.cs b/src/NTP.Application/Jobs/JobCatalog.cs new file mode 100644 index 0000000..4f09cf4 --- /dev/null +++ b/src/NTP.Application/Jobs/JobCatalog.cs @@ -0,0 +1,47 @@ +using NTP.Application.Grains.Permits; + +namespace NTP.Application.Jobs; + +/// +/// 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). +/// +public static class JobCatalog +{ + private static T Get(IServiceProvider sp) where T : class => (T)(sp.GetService(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not registered")); + + public static readonly IReadOnlyList 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(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(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(sp).FillCompanySharesAsync(ct); + return new JobOutcome(n, $"تم إنشاء {n} إرسالية"); + }), + ]; + + public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/NTP.Application/Jobs/JobScheduleRules.cs b/src/NTP.Application/Jobs/JobScheduleRules.cs new file mode 100644 index 0000000..010467c --- /dev/null +++ b/src/NTP.Application/Jobs/JobScheduleRules.cs @@ -0,0 +1,119 @@ +using System.Globalization; + +namespace NTP.Application.Jobs; + +/// Pure scheduling rules (no clock, no database), so they can be tested exactly. +public static class JobScheduleRules +{ + public const int MinIntervalMinutes = 1; + public const int MaxIntervalMinutes = 7 * 24 * 60; + public const int DefaultIntervalMinutes = 60; + + /// A daily time that was missed (application stopped, restart) still runs once if it is at most this late. + 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); + + /// "02:00,13:30" -> times (invalid parts are ignored). + public static IReadOnlyList ParseTimes(string? csv) + { + var list = new List(); + 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 SplitTimes(string? csv) => ParseTimes(csv).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)).ToList(); + + public static string JoinTimes(IEnumerable? 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))); + + /// Returns an Arabic error text, or null when the schedule is valid. + public static string? Validate(string? scheduleType, int? intervalMinutes, IReadOnlyList? 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; + + /// The most recent configured daily time that is not in the future (today or yesterday), if any. + private static DateTime? LatestOccurrence(IReadOnlyList 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; + } + + /// Is the job due at ? A job that is stopped or still running never is. + 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; + } + + /// When the job runs next (null when it is stopped or has no valid schedule). A job that is due now returns . + 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; + } +} diff --git a/src/NTP.Application/Jobs/JobService.cs b/src/NTP.Application/Jobs/JobService.cs new file mode 100644 index 0000000..2bf3df9 --- /dev/null +++ b/src/NTP.Application/Jobs/JobService.cs @@ -0,0 +1,107 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Jobs; + +public interface IJobService +{ + Task> ListAsync(CancellationToken ct = default); + Task SaveScheduleAsync(string key, SaveJobScheduleRequest request, CancellationToken ct = default); + Task StartAsync(string key, CancellationToken ct = default); + Task StopAsync(string key, CancellationToken ct = default); + Task RunNowAsync(string key, CancellationToken ct = default); + Task> RunsAsync(string key, CancellationToken ct = default); + + /// Keys of the jobs that are due now (used by the scheduler loop). + Task> 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); + + /// The settings of a job that was never saved: stopped, every hour. + 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 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 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> 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 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 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 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 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> 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> 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(); + } +} diff --git a/src/NTP.Application/Jobs/JobsContracts.cs b/src/NTP.Application/Jobs/JobsContracts.cs new file mode 100644 index 0000000..2f32287 --- /dev/null +++ b/src/NTP.Application/Jobs/JobsContracts.cs @@ -0,0 +1,103 @@ +namespace NTP.Application.Jobs; + +/// How a job is scheduled. +public static class JobScheduleTypes +{ + /// Every N minutes (the screen offers minutes or hours), counted from the last start. + public const string Interval = "INTERVAL"; + + /// At one or more fixed times of the day (HH:mm, server time). + public const string Daily = "DAILY"; +} + +public static class JobStatuses +{ + public const string Running = "RUNNING"; + public const string Ok = "OK"; + public const string Failed = "FAILED"; +} + +/// What a job reports when it finishes. +public sealed record JobOutcome(int Count, string? Message = null); + +/// One job of the catalog: its key, texts and the code that runs it (called in its own DI scope). +public sealed record JobDefinition( + string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn, + Func> Run); + +/// GRAINS_JOBS row (a class: Dapper maps Oracle NUMBER onto properties, not onto positional constructors). +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); +} + +/// GRAINS_JOB_RUNS row. +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 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? DailyTimes); + +public sealed record JobActionResult(bool Success, string Message); + +public enum JobStartResult { Started, AlreadyRunning } + +/// Storage of the job settings and of the run history (tables GRAINS_JOBS / GRAINS_JOB_RUNS, script db/grains-jobs.sql). +public interface IJobRepository +{ + /// Database clock: schedules are judged against it, never against the container clock. + Task GetServerNowAsync(CancellationToken ct = default); + + Task> GetAllAsync(CancellationToken ct = default); + + /// Saves the schedule (creates the row when missing, jobs start stopped). Restarts the interval cycle. + Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default); + + /// Start (true) / stop (false). Restarts the interval cycle, so a started job never fires for a time that is already past. + Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default); + + /// + /// 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. + /// + Task TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default); + + Task FinishRunAsync(long runId, string key, string status, int? rows, string? message, CancellationToken ct = default); + + Task> GetRunsAsync(string key, int top, CancellationToken ct = default); +} + +/// Starts a job in the background (own DI scope) and records its run. Implemented in Infrastructure. +public interface IJobRunner +{ + Task StartAsync(string key, string triggeredBy, CancellationToken ct = default); +} diff --git a/src/NTP.Infrastructure/DependencyInjection.cs b/src/NTP.Infrastructure/DependencyInjection.cs index 4f09b27..027f257 100644 --- a/src/NTP.Infrastructure/DependencyInjection.cs +++ b/src/NTP.Infrastructure/DependencyInjection.cs @@ -3,7 +3,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NTP.Application.Abstractions; using NTP.Application.Common; +using NTP.Application.Jobs; using NTP.Infrastructure.HealthChecks; +using NTP.Infrastructure.Jobs; using NTP.Infrastructure.Persistence; namespace NTP.Infrastructure; @@ -50,6 +52,10 @@ public static class DependencyInjection services.AddScoped(); services.AddSingleton(); + // scheduled jobs: the runner starts a job in its own scope, the worker looks for due jobs (screen "المهام المجدولة", SU only) + services.AddSingleton(); + services.AddHostedService(); + // Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped). // Do NOT add per-table lines here. services.AddConventionalServices(typeof(DependencyInjection).Assembly); diff --git a/src/NTP.Infrastructure/Jobs/JobRunner.cs b/src/NTP.Infrastructure/Jobs/JobRunner.cs new file mode 100644 index 0000000..e525e22 --- /dev/null +++ b/src/NTP.Infrastructure/Jobs/JobRunner.cs @@ -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; + +/// +/// Runs a job of the 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). +/// +internal sealed class JobRunner( + IServiceScopeFactory scopes, + ISystemErrorLogger systemErrors, + IHostApplicationLifetime lifetime, + ILogger logger) : IJobRunner +{ + public async Task 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().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().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); + } + } +} diff --git a/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs b/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs new file mode 100644 index 0000000..dc0eea0 --- /dev/null +++ b/src/NTP.Infrastructure/Jobs/JobSchedulerWorker.cs @@ -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; + +/// +/// Looks every 20 seconds for jobs that are due (see ) and starts them. What runs and when is set on the +/// SU screen "المهام المجدولة"; nothing runs until a job is started there. Jobs:SchedulerEnabled=false 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). +/// +internal sealed class JobSchedulerWorker( + IServiceScopeFactory scopes, + IJobRunner runner, + IConfiguration configuration, + ILogger 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 due; + await using (var scope = scopes.CreateAsyncScope()) + due = await scope.ServiceProvider.GetRequiredService().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 WaitAsync(PeriodicTimer timer, CancellationToken ct) + { + try { return await timer.WaitForNextTickAsync(ct); } + catch (OperationCanceledException) { return false; } + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs new file mode 100644 index 0000000..3703e50 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitJobsRepository.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// SQL of jobs/GRAINS_Close_Old_Permits.cfm. +internal sealed class PermitJobsRepository(IDbSession session, ILogger 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> GetOldPermitsToCloseAsync(CancellationToken ct = default) => + QueryAsync(""" + 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 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); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs new file mode 100644 index 0000000..9b24c42 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Jobs/JobRepository.cs @@ -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; + +/// Tables GRAINS_JOBS and GRAINS_JOB_RUNS of the primary schema (created by db/grains-jobs.sql). +internal sealed class JobRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IJobRepository +{ + private const int MessageBytes = 500; + + /// The scheduler must not crash, and the screen must explain, when the script has not been run yet (ORA-00942). + private static async Task Guard(Func> action) + { + try { return await action(); } + catch (OracleException ex) when (ex.Number == 942) + { + throw new BusinessException("JOBS_TABLE_MISSING", "جداول المهام المجدولة غير موجودة، يرجى تشغيل السكربت db/grains-jobs.sql"); + } + } + + public Task GetServerNowAsync(CancellationToken ct = default) => ExecuteScalarAsync("SELECT SYSDATE FROM DUAL", null, ct); + + public Task> GetAllAsync(CancellationToken ct = default) => Guard(() => QueryAsync(""" + 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 TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default) => Guard(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("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> GetRunsAsync(string key, int top, CancellationToken ct = default) => Guard(() => QueryAsync(""" + 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)); +} diff --git a/tests/NTP.Tests/JobScheduleRulesTests.cs b/tests/NTP.Tests/JobScheduleRulesTests.cs new file mode 100644 index 0000000..5a06041 --- /dev/null +++ b/tests/NTP.Tests/JobScheduleRulesTests.cs @@ -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? 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")); + } +} diff --git a/web/src/features/jobs/api.ts b/web/src/features/jobs/api.ts new file mode 100644 index 0000000..18cee81 --- /dev/null +++ b/web/src/features/jobs/api.ts @@ -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(base), refetchInterval: 10_000 }); +} + +export function useJobRuns(key: string | null) { + return useQuery({ queryKey: [...jobsKey, 'runs', key], queryFn: () => api.get(`${base}/${key}/runs`), enabled: !!key }); +} + +export const useSaveSchedule = (message: string) => + useWrite((v: { key: string; body: ScheduleBody }) => api.put(`${base}/${v.key}`, v.body), { invalidate: [jobsKey], successMessage: message }); + +export const useStartJob = (message: string) => + useWrite((key: string) => api.post(`${base}/${key}/start`), { invalidate: [jobsKey], successMessage: message }); + +export const useStopJob = (message: string) => + useWrite((key: string) => api.post(`${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(`${base}/${key}/run`), { invalidate: [jobsKey], toastSuccess: false }); diff --git a/web/src/features/jobs/pages.tsx b/web/src/features/jobs/pages.tsx new file mode 100644 index 0000000..c949308 --- /dev/null +++ b/web/src/features/jobs/pages.tsx @@ -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 ( + <> + + {jobs.isLoading ? ( + + ) : jobs.error ? ( + {jobs.error instanceof Error ? jobs.error.message : t('jobs.loadError')} + ) : (jobs.data ?? []).length === 0 ? ( + + ) : ( + + {/* remount when the saved schedule changes so the draft follows the server, not every 10-second refresh */} + {(jobs.data ?? []).map((j) => ( + + ))} + + )} + + ); +} + +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(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 ( + + + + + {title} + {job.key} + + + + + {description} + + + + {t('jobs.lastRun')} + {job.lastStart ? ( + + + {formatDateTime(job.lastStart, lang)} + {job.lastStatus && } + {job.lastCount !== null && {t('jobs.rows')}: {formatNumber(job.lastCount, lang)}} + + {job.lastMessage && {job.lastMessage}} + + ) : ( + {t('jobs.never')} + )} + + + {t('jobs.nextRun')} + {job.nextRun ? formatDateTime(job.nextRun, lang) : '-'} + + + + {t('jobs.schedule')} + + v && setType(v)}> + {t('jobs.type.interval')} + {t('jobs.type.daily')} + + + {type === 'INTERVAL' ? ( + + {t('jobs.every')} + setAmount(e.target.value.replace(/\D/g, '').slice(0, 5))} + slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }} + /> + setUnit(e.target.value as 'minutes' | 'hours')}> + {t('jobs.unit.minutes')} + {t('jobs.unit.hours')} + + + ) : ( + + {t('jobs.times')} + + {times.map((x) => ( + {x}} onDelete={() => setTimes(times.filter((y) => y !== x))} /> + ))} + setNewTime(maskTime(e.target.value))} + onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addTime(); } }} + slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr', maxLength: 5 } }} + /> + + + {times.length === 0 && {t('jobs.noTimes')}} + + )} + + + + + {job.enabled ? ( + + ) : ( + + )} + + + + + {showHistory && setShowHistory(false)} />} + + ); +} + +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 ( + + + {t('jobs.h.title')} - {title} + + + + {runs.isLoading ? ( + + ) : rows.length === 0 ? ( + {t('jobs.h.none')} + ) : ( + + + + + {t('jobs.h.start')} + {t('jobs.h.end')} + {t('jobs.h.status')} + {t('jobs.h.rows')} + {t('jobs.h.by')} + {t('jobs.h.message')} + + + + {rows.map((r) => ( + + {formatDateTime(r.startDate, lang)} + {r.endDate ? formatDateTime(r.endDate, lang) : ''} + + {r.status && } + + {r.rowsAffected === null ? '' : formatNumber(r.rowsAffected, lang)} + {r.triggeredBy === 'SCHEDULE' ? t('jobs.h.schedule') : r.triggeredBy} + {r.message} + + ))} + +
+
+ )} +
+ +
+ ); +} diff --git a/web/src/features/jobs/routes.tsx b/web/src/features/jobs/routes.tsx new file mode 100644 index 0000000..340549c --- /dev/null +++ b/web/src/features/jobs/routes.tsx @@ -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: }]; + +export const menu: MenuItem[] = [ + { key: 'jobs', title: strings['jobs.menu'], icon: ScheduleIcon, path: '/jobs', roles: ['SU'] }, +]; diff --git a/web/src/features/jobs/strings.ts b/web/src/features/jobs/strings.ts new file mode 100644 index 0000000..684cc59 --- /dev/null +++ b/web/src/features/jobs/strings.ts @@ -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: 'إغلاق' }, +});