From b32478268c81cb67fc26f5fd0129d3aa100995d8 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Mon, 30 Nov 2026 13:35:21 +0600 Subject: [PATCH] Salary Process real-time progress (SignalR) --- CLAUDE.md | 34 ++ HRM.BO/BackgroundJob/IJobProgress.cs | 79 +++++ HRM.BO/Salary/SalaryProcess.cs | 2 + HRM.DA/Service/Salary/SalaryCalculator.cs | 1 + HRM.DA/Service/Salary/SalaryMonthlyService.cs | 56 +++- .../Service/Salary/SalaryProcessProgress.cs | 275 ++++++++++++++++ HRM.DA/Service/Salary/SalaryProcessService.cs | 23 +- HRM.UI/ClientApp/package-lock.json | 194 ++++++++++- HRM.UI/ClientApp/package.json | 1 + HRM.UI/ClientApp/proxy.json | 1 + .../src/app/_models/realtime/job-snapshot.ts | 38 +++ .../app/_services/payroll/salary.service.ts | 9 + .../_services/realtime/realtime.service.ts | 307 ++++++++++++++++++ .../src/app/payroll/payroll.module.ts | 2 + .../salary-process.component.html | 18 + .../salary-process.component.scss | 26 ++ .../salary-process.component.ts | 107 ++++-- .../job-progress/job-progress.component.html | 89 +++++ .../job-progress/job-progress.component.scss | 298 +++++++++++++++++ .../job-progress/job-progress.component.ts | 229 +++++++++++++ .../app/realtime/realtime-shared.module.ts | 14 + .../Controllers/Payroll/SalaryController.cs | 92 ++++++ HRM.UI/Controllers/Realtime/JobsController.cs | 37 +++ HRM.UI/HRM.UI.csproj | 1 + HRM.UI/Realtime/AppHub.cs | 65 ++++ HRM.UI/Realtime/IAppClient.cs | 19 ++ HRM.UI/Realtime/IRealtimePublisher.cs | 68 ++++ HRM.UI/Realtime/Jobs/JobProgressReporter.cs | 100 ++++++ HRM.UI/Realtime/Jobs/JobRequest.cs | 40 +++ HRM.UI/Realtime/Jobs/JobRunner.cs | 198 +++++++++++ HRM.UI/Realtime/Jobs/JobSnapshot.cs | 65 ++++ HRM.UI/Realtime/Jobs/JobState.cs | 73 +++++ HRM.UI/Realtime/Jobs/JobStore.cs | 120 +++++++ HRM.UI/Realtime/RealtimeGroups.cs | 15 + HRM.UI/Realtime/RealtimeSettings.cs | 26 ++ HRM.UI/Realtime/RealtimeSetup.cs | 60 ++++ HRM.UI/Realtime/UserIdClaimProvider.cs | 16 + HRM.UI/Startup.cs | 8 + 38 files changed, 2783 insertions(+), 23 deletions(-) create mode 100644 HRM.BO/BackgroundJob/IJobProgress.cs create mode 100644 HRM.DA/Service/Salary/SalaryProcessProgress.cs create mode 100644 HRM.UI/ClientApp/src/app/_models/realtime/job-snapshot.ts create mode 100644 HRM.UI/ClientApp/src/app/_services/realtime/realtime.service.ts create mode 100644 HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.html create mode 100644 HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.scss create mode 100644 HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.ts create mode 100644 HRM.UI/ClientApp/src/app/realtime/realtime-shared.module.ts create mode 100644 HRM.UI/Controllers/Realtime/JobsController.cs create mode 100644 HRM.UI/Realtime/AppHub.cs create mode 100644 HRM.UI/Realtime/IAppClient.cs create mode 100644 HRM.UI/Realtime/IRealtimePublisher.cs create mode 100644 HRM.UI/Realtime/Jobs/JobProgressReporter.cs create mode 100644 HRM.UI/Realtime/Jobs/JobRequest.cs create mode 100644 HRM.UI/Realtime/Jobs/JobRunner.cs create mode 100644 HRM.UI/Realtime/Jobs/JobSnapshot.cs create mode 100644 HRM.UI/Realtime/Jobs/JobState.cs create mode 100644 HRM.UI/Realtime/Jobs/JobStore.cs create mode 100644 HRM.UI/Realtime/RealtimeGroups.cs create mode 100644 HRM.UI/Realtime/RealtimeSettings.cs create mode 100644 HRM.UI/Realtime/RealtimeSetup.cs create mode 100644 HRM.UI/Realtime/UserIdClaimProvider.cs diff --git a/CLAUDE.md b/CLAUDE.md index 77e9600..80241a5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -436,6 +436,40 @@ Two things to know before building on it: effectively unused. The per-recipient rows are accurate throughout — it is the header that lags. The UI compensates with a spinner, not with real numbers. +### Cross-cutting: real-time (SignalR) and background jobs + +One SignalR hub serves the whole app: `AppHub` at **`/api/hubs/app`** (`HRM.UI/Realtime/`, wired by +`services.AddRealtime(...)` + `endpoints.MapRealtime()` in `Startup`). Never add a second hub; tell features apart +by topic and group. + +- **Auth** is the normal JWT: the hub is `[Authorize]` and the `JWToken` cookie is read by Startup's + `OnMessageReceived`, so the browser sends nothing extra (no token in the URL). It sits under `/api` so the dev + proxy (`proxy.json`, `"ws": true`) and IIS treat it like any API call. Production IIS should have the + **WebSocket Protocol** feature on (without it SignalR falls back to SSE/long polling and still works). +- **Groups are server-chosen** (`RealtimeGroups`): a connection joins its payroll type's group on connect and a + job's group only through `SubscribeJob`, which checks the caller. Clients never name a group. +- **Sending**: inject `IRealtimePublisher` (`ToUserAsync`, `ToPayrollTypeAsync`, `ToAllAsync`), never + `IHubContext`. Messages arrive in Angular through `RealtimeService.on(topic)`. The client methods are + `IAppClient.JobProgress` and `IAppClient.Event(topic, payload)`; prefer a new topic over a new method. + The hub uses the Newtonsoft protocol, so a BO serialises exactly as in the REST API. +- **Long work with live progress**: `IJobRunner.Start(new JobRequest { Key, Title, OwnerUserId, PayrollTypeId, + Audience, Work = progress => ... })` returns a `JobSnapshot` (`runId`) at once; the work runs on a hosted + service (Channel queue, `Realtime:MaxConcurrentJobs`), one job per `Key` at a time (a second start returns the + running one). The work reports through **`IJobProgress`** (`HRM.BO/BackgroundJob`), which is what HRM.DA + services take as a parameter — HRM.DA never references SignalR. Throttling, ETA and sequence numbers are done + by the runner. Copy everything the work needs from `CurrentUser` before starting: there is no HttpContext later. +- **Angular**: `RealtimeService` (`_services/realtime/`) is the single, lazy connection (auto-reconnect, closes on + logout, reconnects on a new token). `watchJob(runId)` follows a job and survives reloads, reconnects and a + missing connection (it re-reads `GET api/jobs/{runId}` / polls). `` from + `RealtimeSharedModule` is the reusable progress UI. +- Job state is **in memory** (`Realtime:FinishedJobRetentionMinutes`): a restart loses it, and more than one + server would need a Redis backplane plus a database job store. Settings: the optional `Realtime` section + (`RealtimeSettings`). Client package `@microsoft/signalr` is pinned to the server's major (10.0.x). +- Worked example: Salary Process — `SalaryController` `SalaryProcess-start` / `SalaryProcess-active`, + `SalaryProcessService.SalaryProcess(..., IJobProgress)` and `SalaryProcessProgress`, which maps + `SalaryCalculator`'s existing `ProgressStatus` events (13 phases, one step per employee) to a real percentage. + The old synchronous `SalaryProcess` endpoint is unchanged. + ### Cross-cutting: approval workflow Most "apply → approve" features (leave, attendance regularization, claims, requisitions) route through diff --git a/HRM.BO/BackgroundJob/IJobProgress.cs b/HRM.BO/BackgroundJob/IJobProgress.cs new file mode 100644 index 0000000..1894ceb --- /dev/null +++ b/HRM.BO/BackgroundJob/IJobProgress.cs @@ -0,0 +1,79 @@ +using System; +using System.Threading; + +namespace HRM.BO +{ + /// + /// How a long-running piece of work (salary process, bulk upload, ...) tells the outside world how far it got. + /// + /// It lives in HRM.BO on purpose: HRM.DA services take it as a plain parameter and never know who listens. + /// HRM.UI implements it (background job runner + SignalR), so HRM.DA keeps no reference to ASP.NET or SignalR. + /// Every member is safe to call as often as you like - the implementation throttles what it actually sends. + /// A null IJobProgress means "nobody is listening": callers must check for null (or use TryReport below). + /// + public interface IJobProgress + { + /// Set when the application is shutting down or the job was cancelled. Work may check it between steps. + CancellationToken CancellationToken { get; } + + /// + /// Reports where the work is. + /// + /// 0 - 100 of the whole job. Values out of range are clamped; it never goes backwards. + /// Short name of the current stage, e.g. "Calculating Income Tax". Null keeps the previous one. + /// Optional extra line, e.g. an employee name. Null clears it. + /// Optional items done in the current stage (shown as current / total). + /// Optional items in the current stage. + void Report(double percent, string stage = null, string detail = null, int? current = null, int? total = null); + } + + public static class JobProgressExtensions + { + /// + /// Null-safe AND exception-safe Report. Business code (salary process, uploads, ...) must report through this: + /// progress only watches the work, so a fault in reporting must never be able to stop or change the work. + /// + public static void TryReport(this IJobProgress progress, double percent, string stage = null, string detail = null, + int? current = null, int? total = null) + { + if (progress == null) + return; + try + { + progress.Report(percent, stage, detail, current, total); + } + catch + { + // progress is best-effort; the work goes on regardless + } + } + } + + /// + /// Maps a sub-task's own 0 - 100 onto a slice [from, to] of an outer job's bar. Lets a service report its + /// own progress (e.g. the salary save, 0 - 100) without knowing which part of the whole job it is. + /// + public sealed class JobProgressScope : IJobProgress + { + private readonly IJobProgress _outer; + private readonly double _from; + private readonly double _to; + + public JobProgressScope(IJobProgress outer, double from, double to) + { + _outer = outer; + _from = Math.Max(0, Math.Min(100, from)); + _to = Math.Max(_from, Math.Min(100, to)); + } + + public CancellationToken CancellationToken => _outer != null ? _outer.CancellationToken : CancellationToken.None; + + public void Report(double percent, string stage = null, string detail = null, int? current = null, int? total = null) + { + if (_outer == null) + return; + double p = Math.Max(0, Math.Min(100, percent)); + _outer.Report(_from + (_to - _from) * p / 100.0, stage, detail, current, total); + } + } +} diff --git a/HRM.BO/Salary/SalaryProcess.cs b/HRM.BO/Salary/SalaryProcess.cs index 917a92c..7ba0aa3 100644 --- a/HRM.BO/Salary/SalaryProcess.cs +++ b/HRM.BO/Salary/SalaryProcess.cs @@ -462,6 +462,8 @@ namespace HRM.BO bool GetBySMonth(DateTime sMonth, int payrollTypeID); List SalaryProcess(SalaryProcess item, List employees); + /// Same as SalaryProcess, reporting real progress to (null = none). + List SalaryProcess(SalaryProcess item, List employees, IJobProgress progress); List GetCategoryEmployeeIDs(int categoryID, int payrollTypeID, DateTime salaryMonth); int Save(SalaryProcess item); void Delete(int id); diff --git a/HRM.DA/Service/Salary/SalaryCalculator.cs b/HRM.DA/Service/Salary/SalaryCalculator.cs index 91e5fcd..ba351ab 100644 --- a/HRM.DA/Service/Salary/SalaryCalculator.cs +++ b/HRM.DA/Service/Salary/SalaryCalculator.cs @@ -487,6 +487,7 @@ namespace HRM.DA List arrearItems = new EmployeeGradeSalaryService().GetArrearItems(this.PayrollTypeID); foreach (SalaryMonthly salary in _salaryMonthlys) { + UpdateProgressStatus(EnumProcessStatus.PerformStep); // progress signal only (2nd loop of this phase); changes nothing arrearAmount = 0; salary.ArrearGradeSalaries = arrearItems.FindAll(x => x.EmployeeID == salary.EmployeeID); foreach (EmployeeGradeSalary arrearItem in salary.ArrearGradeSalaries) diff --git a/HRM.DA/Service/Salary/SalaryMonthlyService.cs b/HRM.DA/Service/Salary/SalaryMonthlyService.cs index 429c3fa..1865273 100644 --- a/HRM.DA/Service/Salary/SalaryMonthlyService.cs +++ b/HRM.DA/Service/Salary/SalaryMonthlyService.cs @@ -2658,6 +2658,15 @@ namespace HRM.DA // } //} public void Save(SalaryProcess process, List items) + { + this.Save(process, items, null); + } + + /// + /// Same save as Save(process, items); only reports how far it got to (null = nobody listens, + /// which is exactly the original behaviour). Reporting never changes or stops the save (TryReport swallows faults). + /// + public void Save(SalaryProcess process, List items, IJobProgress progress) { TransactionContext tc = null; try @@ -2683,8 +2692,9 @@ namespace HRM.DA { x.SalaryProcessID = processId; }); - this.SaveBulk(tc, items); + this.SaveBulk(tc, items, progress != null ? new JobProgressScope(progress, 0, 95) : null); } + progress.TryReport(95, "Committing salary data"); tc.End(); } catch (Exception e) @@ -2702,11 +2712,51 @@ namespace HRM.DA public void SaveBulk(TransactionContext tc, List items) + { + this.SaveBulk(tc, items, null); + } + + /// + /// Progress (0 - 100) at the start of each of SaveBulk's four blocks, weighted by the rows each block writes + /// (salary rows, detail rows, tax rows, cost-center rows). Only reads counts; never throws (falls back to even steps). + /// + private static double[] SaveBulkProgressSteps(List items, IJobProgress progress) + { + double[] even = { 0, 25, 50, 75 }; + if (progress == null) + return even; + try + { + double master = items.Count; + double details = items.Sum(x => x.Details != null ? x.Details.Count : 0); + double taxes = items.Sum(x => x.Incometaxes != null ? x.Incometaxes.Count : 0); + double costs = items.Sum(x => x.CostCentersInvolments != null ? x.CostCentersInvolments.Count : 0); + double all = master + details + taxes + costs; + if (all <= 0) + return even; + return new[] + { + 0, + 100 * master / all, + 100 * (master + details) / all, + 100 * (master + details + taxes) / all + }; + } + catch + { + return even; + } + } + + /// Same bulk save; reports 0 - 100 of its four blocks (weighted by row count) to . + public void SaveBulk(TransactionContext tc, List items, IJobProgress progress) { try { if (items.Count > 0) { + double[] saveSteps = SaveBulkProgressSteps(items, progress); + progress.TryReport(saveSteps[0], "Saving salary records", null, 0, items.Count); int salaryPKID = tc.GenerateID("SalaryMonthly", "SalaryMonthlyID"); DataTable attnProcessEntryTable = new DataTable("SalaryMonthly"); attnProcessEntryTable.Columns.Add(new DataColumn("SALARYMONTHLYID", typeof(int))); @@ -2845,6 +2895,7 @@ namespace HRM.DA bulkCopy.DestinationTableName = "SALARYMONTHLY"; bulkCopy.WriteToServer(attnProcessEntryTable); + progress.TryReport(saveSteps[1], "Saving salary details"); } @@ -2902,6 +2953,7 @@ namespace HRM.DA bulkCopy.DestinationTableName = "SALARYMONTHLYDETAIL"; bulkCopy.WriteToServer(detailtable); + progress.TryReport(saveSteps[2], "Saving income tax data"); } @@ -2970,6 +3022,7 @@ namespace HRM.DA bulkCopy.DestinationTableName = "SALARYTEMPIT"; bulkCopy.WriteToServer(tax); + progress.TryReport(saveSteps[3], "Saving cost-center data"); } @@ -3005,6 +3058,7 @@ namespace HRM.DA bulkCopy.DestinationTableName = "SALARYEMPCOSTCENTER"; bulkCopy.WriteToServer(cost); + progress.TryReport(100, "Saving cost-center data"); } } diff --git a/HRM.DA/Service/Salary/SalaryProcessProgress.cs b/HRM.DA/Service/Salary/SalaryProcessProgress.cs new file mode 100644 index 0000000..2b42a9e --- /dev/null +++ b/HRM.DA/Service/Salary/SalaryProcessProgress.cs @@ -0,0 +1,275 @@ +using HRM.BO; +using System; +using System.Collections.Concurrent; +using System.Diagnostics; + +namespace HRM.DA +{ + /// + /// Real progress of the salary process for an IJobProgress listener. It only WATCHES the process: it reads the + /// events SalaryCalculator raises and never touches a salary, an employee or a query. Every entry point is wrapped + /// in try/catch, so a fault here can never stop or change the calculation. + /// + /// The run is split into stages, in the exact order they happen: + /// Validating -> Preparing calculation (SalaryCalculator ctor, approval check, Process() set-up + Initialize) + /// -> the 12 first calculation phases -> Salary exception -> Net income -> Saving. + /// A calculation phase starts with the ProgressStatus Start event (its first statement in SalaryCalculator) and + /// moves one step per PerformStep (one per employee / salary row; Basic salary has two such loops). + /// "Salary exception" has no events of its own: it is recognised by the status message Process() already sends. + /// + /// How much of the bar each stage gets is LEARNED: every successful run measures how long each stage really took + /// (per payroll type, in memory), and the next run splits the bar in those proportions - so the bar moves at an even + /// pace and the ETA is real. The first run (and the first after an app restart) uses default proportions. + /// 0 - 1 % is "Loading employees", reported by the caller before this class exists. + /// + internal sealed class SalaryProcessProgress + { + private const double StartPercent = 1; // 0 - 1 %: loading employees (caller) + private const double MinStageShare = 0.004; // a learned stage never gets less than 0.4 % of the bar + + // Calculation phases, in the order of the Start events in SalaryCalculator.Process. + private static readonly string[] PhaseNames = + { + "Collecting employee information", + "Calculating basic salary", + "Calculating benefits and deductions", + "Calculating overtime", + "Calculating bonus", + "Calculating unauthorized leave deduction", + "Calculating PF & CPF", + "Calculating income tax", + "Preparing cost-center data", + "Calculating loan installments", + "Calculating attendance days", + "Calculating leave days", + "Calculating net income" + }; + + // Loops (of one step per salary row) a phase runs; Basic salary also loops for arrears. + private static readonly int[] PhaseLoops = { 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; + + // Stages = Validating, Preparing, phases 0..11, Salary exception, phase 12 (net income), Saving. + private const int StageValidating = 0; + private const int StagePreparing = 1; + private const int StageFirstPhase = 2; // phase p (0..11) -> stage 2 + p + private const int StageSalaryException = 14; + private const int StageNetIncome = 15; // phase 12 + private const int StageSaving = 16; + private const int StageCount = 17; + + private static readonly double[] DefaultWeights = BuildDefaultWeights(); + + // Measured seconds per stage of the last successful run, per payroll type, with that run's employee count. + // Fixed set-up costs weigh differently in a 5-employee run than in a 5,000-employee one, so a measurement is + // only reused for a run of a similar size, and only runs of a meaningful size are learned from. + private static readonly ConcurrentDictionary LearnedRuns = new ConcurrentDictionary(); + private const int MinEmployeesToLearn = 20; + private const double MaxSizeRatio = 4; + + private sealed class LearnedRun + { + public int EmployeeCount; + public double[] Seconds; + } + + private const string EmployeeMessagePrefix = "Collecting information for the employee"; + private const string SalaryExceptionMessage = "Salary Exception"; + + private readonly IJobProgress _progress; + private readonly int _payrollTypeId; + private readonly int _employeeCount; + private readonly double[] _stageStart; // percent where each stage begins + private readonly double[] _stageShare; // percent each stage spans + private readonly double[] _secondsSpent = new double[StageCount]; + private readonly Stopwatch _clock = Stopwatch.StartNew(); + + private int _stage = -1; + private double _stageEnteredAt; + private int _phase = -1; + private int _step; + private string _detail; + + public SalaryProcessProgress(IJobProgress progress, int payrollTypeId, int employeeCount) + { + _progress = progress; + _payrollTypeId = payrollTypeId; + _employeeCount = Math.Max(1, employeeCount); + + double[] weights = WeightsFor(payrollTypeId, _employeeCount); + double total = 0; + foreach (double w in weights) total += w; + _stageStart = new double[StageCount]; + _stageShare = new double[StageCount]; + double at = StartPercent; + for (int i = 0; i < StageCount; i++) + { + _stageShare[i] = (100 - StartPercent) * weights[i] / total; + _stageStart[i] = at; + at += _stageShare[i]; + } + } + + public void Validating() + { + Safe(() => Enter(StageValidating, "Validating salary data")); + } + + /// From here until the first calculation phase starts: calculator set-up, approval check, Initialize. + public void Preparing() + { + Safe(() => Enter(StagePreparing, "Preparing calculation")); + } + + public void Attach(SalaryCalculator calculator) + { + calculator.ProgressStatus += OnProgressStatus; + calculator.ProcessStatus += OnProcessStatus; + } + + /// The save reports its own 0 - 100 through this; it lands in the Saving slice of the bar. + public IJobProgress Saving() + { + Safe(() => Enter(StageSaving, "Saving salary data")); + return new JobProgressScope(_progress, _stageStart[StageSaving], _stageStart[StageSaving] + _stageShare[StageSaving]); + } + + /// The run finished successfully: remember how long each stage took, for the next run's proportions. + public void Completed() + { + Safe(() => + { + CloseStage(); + double[] measured = (double[])_secondsSpent.Clone(); + double sum = 0; + foreach (double s in measured) sum += s; + if (sum > 0 && _employeeCount >= MinEmployeesToLearn) + LearnedRuns[_payrollTypeId] = new LearnedRun { EmployeeCount = _employeeCount, Seconds = measured }; + }); + } + + private void OnProcessStatus(string message) + { + Safe(() => + { + if (string.IsNullOrEmpty(message)) + { + _detail = null; + return; + } + string text = message.Trim(); + if (text.StartsWith(EmployeeMessagePrefix, StringComparison.OrdinalIgnoreCase)) + { + _detail = text.Substring(EmployeeMessagePrefix.Length).Trim(); + } + else if (text.IndexOf(SalaryExceptionMessage, StringComparison.OrdinalIgnoreCase) >= 0) + { + // Sent by Process() just before SalaryExceptionCalculation, i.e. after leave days, before net income. + Enter(StageSalaryException, "Calculating salary exception"); + } + else + { + _detail = null; + } + }); + } + + private void OnProgressStatus(EnumProcessStatus status) + { + Safe(() => + { + if (status == EnumProcessStatus.Start) + { + _phase++; + _step = 0; + _detail = null; + int phase = Math.Min(_phase, PhaseNames.Length - 1); + Enter(phase < 12 ? StageFirstPhase + phase : StageNetIncome, PhaseNames[phase]); + } + else if (status == EnumProcessStatus.PerformStep) + { + _step++; + PublishPhase(); + } + // End needs nothing: the next Start / stage moves the bar on. + }); + } + + private void PublishPhase() + { + if (_phase < 0) + return; + int phase = Math.Min(_phase, PhaseNames.Length - 1); + int stage = phase < 12 ? StageFirstPhase + phase : StageNetIncome; + int expected = _employeeCount * PhaseLoops[phase]; + double inside = Math.Min((double)_step / expected, 0.999); + int shown = Math.Min(_step, expected); + // A two-loop phase counts each employee twice; show employees, not loop steps. + int employeesDone = PhaseLoops[phase] > 1 ? Math.Min(_employeeCount, (int)Math.Ceiling((double)shown / PhaseLoops[phase])) : shown; + _progress.Report(_stageStart[stage] + _stageShare[stage] * inside, PhaseNames[phase], _detail, employeesDone, _employeeCount); + } + + private void Enter(int stage, string name) + { + if (stage == _stage) + return; + CloseStage(); + _stage = stage; + _stageEnteredAt = _clock.Elapsed.TotalSeconds; + _progress.Report(_stageStart[stage], name, null, null, null); + } + + private void CloseStage() + { + if (_stage < 0) + return; + double now = _clock.Elapsed.TotalSeconds; + _secondsSpent[_stage] += Math.Max(0, now - _stageEnteredAt); + _stageEnteredAt = now; + } + + private static double[] WeightsFor(int payrollTypeId, int employeeCount) + { + if (!LearnedRuns.TryGetValue(payrollTypeId, out LearnedRun run) || run?.Seconds == null || run.Seconds.Length != StageCount) + return DefaultWeights; + double ratio = (double)Math.Max(employeeCount, 1) / Math.Max(run.EmployeeCount, 1); + if (ratio > MaxSizeRatio || ratio < 1 / MaxSizeRatio) + return DefaultWeights; + double[] seconds = run.Seconds; + + double total = 0; + foreach (double s in seconds) total += s; + if (total <= 0) + return DefaultWeights; + + double[] weights = new double[StageCount]; + for (int i = 0; i < StageCount; i++) + weights[i] = Math.Max(seconds[i] / total, MinStageShare); + return weights; + } + + private static double[] BuildDefaultWeights() + { + // Used until a run has been measured: small set-up stages, equal calculation phases, a tenth for saving. + double[] w = new double[StageCount]; + w[StageValidating] = 2; + w[StagePreparing] = 3; + for (int p = 0; p < 12; p++) w[StageFirstPhase + p] = 6.5; + w[StageSalaryException] = 0.5; + w[StageNetIncome] = 6.5; + w[StageSaving] = 10; + return w; + } + + private static void Safe(Action action) + { + try + { + action(); + } + catch + { + // progress only watches the salary process; it must never be able to break it + } + } + } +} diff --git a/HRM.DA/Service/Salary/SalaryProcessService.cs b/HRM.DA/Service/Salary/SalaryProcessService.cs index e737f3a..a3d5f72 100644 --- a/HRM.DA/Service/Salary/SalaryProcessService.cs +++ b/HRM.DA/Service/Salary/SalaryProcessService.cs @@ -369,15 +369,32 @@ namespace HRM.DA } public List SalaryProcess(SalaryProcess item, List employees) + { + return this.SalaryProcess(item, employees, null); + } + + /// + /// The salary process, reporting real progress to (null = nobody listens, which is + /// exactly the original behaviour). Only listeners are added; the calculation and the save are untouched. + /// + public List SalaryProcess(SalaryProcess item, List employees, IJobProgress progress) { try { + // Progress only watches (see SalaryProcessProgress); with progress == null none of these lines do anything. + SalaryProcessProgress tracker = progress != null + ? new SalaryProcessProgress(progress, item.PayrollTypeID, employees != null ? employees.Count : 0) + : null; + if (tracker != null) tracker.Validating(); + bool IsFinantialAprovalRequired = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "finantialaproval", "finantialaprovalrequired"); string msg = String.Empty; var items = this.SalaryValidation(item, employees); if (items.Count != 0) return items; + if (tracker != null) tracker.Preparing(); SalaryCalculator calculator = new SalaryCalculator(); + if (tracker != null) tracker.Attach(calculator); if (IsFinantialAprovalRequired) { List salaryProcessStatusList = new List(); @@ -390,7 +407,11 @@ namespace HRM.DA calculator.Process(employees, item.SalaryMonth, item.PayrollTypeID, item.EuroRate); if (calculator.ErrorList.Count == 0) - new SalaryMonthlyService().Save(item, calculator.SalaryMonthlies); + { + IJobProgress saveProgress = tracker != null ? tracker.Saving() : null; + new SalaryMonthlyService().Save(item, calculator.SalaryMonthlies, saveProgress); + if (tracker != null) tracker.Completed(); + } //salaryProcessStatusList.ForEach(item => calculator.ErrorList.Add(item)); return calculator.ErrorList; } diff --git a/HRM.UI/ClientApp/package-lock.json b/HRM.UI/ClientApp/package-lock.json index d7e14a9..4707538 100644 --- a/HRM.UI/ClientApp/package-lock.json +++ b/HRM.UI/ClientApp/package-lock.json @@ -20,6 +20,7 @@ "@auth0/angular-jwt": "^5.2.0", "@azure/msal-angular": "^6.2.5", "@azure/msal-browser": "^5.27.0", + "@microsoft/signalr": "10.0.11", "@progress/kendo-angular-buttons": "25.3.0", "@progress/kendo-angular-charts": "25.3.0", "@progress/kendo-angular-common": "25.3.0", @@ -3370,6 +3371,40 @@ "win32" ] }, + "node_modules/@microsoft/signalr": { + "version": "10.0.11", + "resolved": "https://registry.npmjs.org/@microsoft/signalr/-/signalr-10.0.11.tgz", + "integrity": "sha512-FulOJ2EEtKvLQcswe/U7v8pzyXyk7Jua5xgWJPPwyQU/2Z9ORvKcVjyO75VvLsem+CJ1ORRexJ+7Bz1FCei2aw==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "eventsource": "^2.0.2", + "fetch-cookie": "^2.0.3", + "node-fetch": "^2.6.7", + "ws": "^7.5.10" + } + }, + "node_modules/@microsoft/signalr/node_modules/ws": { + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/@modelcontextprotocol/core": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", @@ -6273,6 +6308,18 @@ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/acorn": { "version": "8.19.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", @@ -8702,6 +8749,15 @@ "node": ">=0.10.0" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", @@ -8709,6 +8765,15 @@ "dev": true, "license": "MIT" }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exceljs": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", @@ -8886,6 +8951,16 @@ } } }, + "node_modules/fetch-cookie": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-2.2.0.tgz", + "integrity": "sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==", + "license": "Unlicense", + "dependencies": { + "set-cookie-parser": "^2.4.8", + "tough-cookie": "^4.0.0" + } + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -11965,6 +12040,26 @@ "semver": "bin/semver.js" } }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/node-gyp-build-optional-packages": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz", @@ -12728,6 +12823,27 @@ } } }, + "node_modules/psl": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } + }, + "node_modules/psl/node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/pump": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", @@ -12756,6 +12872,12 @@ "node": ">=0.9" } }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -12994,7 +13116,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, "license": "MIT" }, "node_modules/resolve": { @@ -13708,6 +13829,12 @@ "node": ">=10" } }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", + "license": "MIT" + }, "node_modules/set-function-length": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", @@ -14405,6 +14532,45 @@ "node": ">=0.6" } }, + "node_modules/tough-cookie": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", + "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tough-cookie/node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/tough-cookie/node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/traverse": { "version": "0.3.10", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.10.tgz", @@ -14780,6 +14946,16 @@ "node": ">=6" } }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -14945,6 +15121,22 @@ "license": "MIT", "optional": true }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/HRM.UI/ClientApp/package.json b/HRM.UI/ClientApp/package.json index cd5a5de..ba7ab5f 100644 --- a/HRM.UI/ClientApp/package.json +++ b/HRM.UI/ClientApp/package.json @@ -22,6 +22,7 @@ "@auth0/angular-jwt": "^5.2.0", "@azure/msal-angular": "^6.2.5", "@azure/msal-browser": "^5.27.0", + "@microsoft/signalr": "10.0.11", "@progress/kendo-angular-buttons": "25.3.0", "@progress/kendo-angular-charts": "25.3.0", "@progress/kendo-angular-common": "25.3.0", diff --git a/HRM.UI/ClientApp/proxy.json b/HRM.UI/ClientApp/proxy.json index 0c14b85..a84cd2d 100644 --- a/HRM.UI/ClientApp/proxy.json +++ b/HRM.UI/ClientApp/proxy.json @@ -3,6 +3,7 @@ "target": "https://localhost:44374", "secure": false, "changeOrigin": true, + "ws": true, "logLevel": "debug" } } diff --git a/HRM.UI/ClientApp/src/app/_models/realtime/job-snapshot.ts b/HRM.UI/ClientApp/src/app/_models/realtime/job-snapshot.ts new file mode 100644 index 0000000..21397a0 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/realtime/job-snapshot.ts @@ -0,0 +1,38 @@ +/** Same numbers as HRM.UI/Realtime/Jobs/JobSnapshot.cs (JobStatus). */ +export enum JobStatus { + Queued = 1, + Running = 2, + Succeeded = 3, + Failed = 4 +} + +/** A background job as the server reports it (HRM.UI/Realtime/Jobs/JobSnapshot.cs). */ +export interface JobSnapshot { + runId: string; + key: string; + title: string; + status: JobStatus; + /** 0 - 100, never goes backwards. */ + percent: number; + stage: string | null; + detail: string | null; + current: number | null; + total: number | null; + queuedAt: string; + startedAt: string | null; + finishedAt: string | null; + elapsedSeconds: number; + /** Estimated seconds left; null until there is enough to measure. */ + etaSeconds: number | null; + /** Grows with every change; an older message than the one shown is ignored. */ + sequence: number; + /** What the job returned (when Succeeded). Its shape belongs to the job. */ + result: any; + /** Why it failed (when Failed). */ + error: string | null; + isFinished: boolean; +} + +export function isJobFinished(job: JobSnapshot | null | undefined): boolean { + return !!job && (job.status === JobStatus.Succeeded || job.status === JobStatus.Failed); +} diff --git a/HRM.UI/ClientApp/src/app/_services/payroll/salary.service.ts b/HRM.UI/ClientApp/src/app/_services/payroll/salary.service.ts index cf10d81..cf01715 100644 --- a/HRM.UI/ClientApp/src/app/_services/payroll/salary.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/payroll/salary.service.ts @@ -5,6 +5,7 @@ import {EnumIncomeTaxDataFrom, EnumSalaryGroup, EnumSalaryItemCode} from '../../ import {SalaryEmpCostCenter} from '../../_models/Payroll/salaryEmpCostCenter'; import {SalaryMonthlyDetail} from '../../_models/Payroll/salaryMonthlyDetail'; import {SalaryApprovalAttachment, SalaryProcess, SalaryProcessStatus, SalaryProcessSummaryItem} from '../../_models/Payroll/salaryProcess'; +import { JobSnapshot } from '../../_models/realtime/job-snapshot'; import { SearchEmployee } from '../../_models/Employee/searchEmployee'; import { PayrollComponentList } from '../../_models/Attendance/PayrollComponentList'; import { HttpEvent } from '@angular/common/http'; @@ -215,6 +216,14 @@ export class SalaryService { salaryProcess(params: any) { return this.apiService.httpPost('/salary/SalaryProcess', params); } + /** Same request as salaryProcess; runs as a background job and answers the job (follow it with RealtimeService.watchJob). */ + salaryProcessStart(params: any) { + return this.apiService.httpPost('/salary/SalaryProcess-start', params); + } + /** The salary process running now in the login's payroll type, or null. */ + salaryProcessActive() { + return this.apiService.httpGet('/salary/SalaryProcess-active'); + } salaryProcessApprove(params: any) { return this.apiService.httpPost(this.apiService.base_url + '/salaryProcessApprove', params); } diff --git a/HRM.UI/ClientApp/src/app/_services/realtime/realtime.service.ts b/HRM.UI/ClientApp/src/app/_services/realtime/realtime.service.ts new file mode 100644 index 0000000..299a406 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_services/realtime/realtime.service.ts @@ -0,0 +1,307 @@ +import { Injectable, NgZone, OnDestroy } from '@angular/core'; +import { + HubConnection, + HubConnectionBuilder, + HubConnectionState, + IRetryPolicy, + LogLevel, + RetryContext +} from '@microsoft/signalr'; +import { BehaviorSubject, Observable, Subject, Subscription, filter, map } from 'rxjs'; +import { environment } from 'src/environments/environment'; +import { ApiService } from '../../app.api.service'; +import { AuthService } from '../auth/auth.service'; +import { JobSnapshot, isJobFinished } from '../../_models/realtime/job-snapshot'; + +export type RealtimeConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting'; + +/** A message pushed with IAppClient.Event on the server. */ +export interface RealtimeEvent { + topic: string; + payload: T; +} + +/** + * Retries quickly at first, then every 30 s for as long as the user is signed in. + * Gives up (null) once there is no token any more - a signed-out tab must not keep knocking. + */ +class SignedInRetryPolicy implements IRetryPolicy { + private static readonly steps = [0, 2000, 5000, 10000, 20000]; + + nextRetryDelayInMilliseconds(context: RetryContext): number | null { + if (!ApiService.AuthenticationToken && !localStorage.getItem('token')) { + return null; + } + const steps = SignedInRetryPolicy.steps; + return context.previousRetryCount < steps.length ? steps[context.previousRetryCount] : 30000; + } +} + +/** + * The app's ONE SignalR connection (hub HRM.UI/Realtime/AppHub.cs at /api/hubs/app), shared by every feature. + * + * - Lazy: nothing connects until a feature asks (watchJob / on), so screens that never use it pay nothing. + * - Auth is the HttpOnly JWToken cookie the API already uses (same origin, sent automatically). No token in the URL. + * - Reconnects by itself; a new sign-in / payroll-type switch (new token) opens a fresh connection. + * - Signs out with the user (AuthService.logout$). + * + * Features use: + * watchJob(runId) - live progress of a background job (HRM.UI/Realtime/Jobs), with HTTP catch-up and fallback. + * on(topic) - any other server push (IRealtimePublisher.ToUserAsync / ToPayrollTypeAsync / ToAllAsync). + */ +@Injectable({ providedIn: 'root' }) +export class RealtimeService implements OnDestroy { + private static readonly HUB_PATH = '/hubs/app'; + /** While connected, a job with no message for this long is re-read over HTTP (a lost message can never freeze the bar). */ + private static readonly SILENCE_CHECK_MS = 15000; + /** Polling interval when no connection can be made at all. */ + private static readonly POLL_MS = 2000; + + private connection: HubConnection | null = null; + private connectedToken: string | null = null; + private startPromise: Promise | null = null; + + private readonly stateSubject = new BehaviorSubject('disconnected'); + private readonly jobProgress$ = new Subject(); + private readonly events$ = new Subject(); + /** A (re)connection was made: joined groups are gone and must be joined again. */ + private readonly resubscribe$ = new Subject(); + private readonly subscriptions = new Subscription(); + + /** Current connection state, e.g. for a small "live" indicator. */ + readonly state$: Observable = this.stateSubject.asObservable(); + + constructor(private zone: NgZone, private apiService: ApiService, authService: AuthService) { + this.subscriptions.add(authService.logout$.subscribe(() => this.stop())); + } + + ngOnDestroy(): void { + this.subscriptions.unsubscribe(); + this.stop(); + } + + get isConnected(): boolean { + return this.connection?.state === HubConnectionState.Connected; + } + + /** + * Makes sure the connection is up with the current sign-in. Resolves true when connected, false when it could not + * connect (callers then fall back to HTTP). Never rejects. + */ + connect(): Promise { + const token = ApiService.AuthenticationToken || localStorage.getItem('token'); + if (!token) { + return Promise.resolve(false); + } + + // Signed in again or switched payroll type: the old connection carries the old claims. + if (this.connection && this.connectedToken !== token) { + this.dropConnection(); + } + + if (this.connection) { + if (this.connection.state === HubConnectionState.Connected) { + return Promise.resolve(true); + } + if (this.startPromise) { + return this.startPromise; + } + if (this.connection.state === HubConnectionState.Reconnecting) { + return Promise.resolve(false); + } + } else { + this.connection = this.buildConnection(); + this.connectedToken = token; + } + + const connection = this.connection; + this.setState('connecting'); + const startPromise: Promise = connection.start() + .then(() => { + if (this.connection !== connection) { + return false; // signed out / replaced while starting + } + this.setState('connected'); + this.zone.run(() => this.resubscribe$.next()); + return true; + }) + .catch((err) => { + if (!environment.production) { + console.warn('[realtime] could not connect, HTTP fallback is used', err); + } + if (this.connection === connection) { + this.setState('disconnected'); + } + return false; + }) + .finally(() => { + if (this.startPromise === startPromise) { + this.startPromise = null; + } + }); + this.startPromise = startPromise; + return startPromise; + } + + /** Closes the connection (sign-out). Watchers keep working over HTTP until they finish. */ + stop(): void { + this.dropConnection(); + } + + /** + * Server pushes of one topic (sent with IRealtimePublisher.ToUserAsync / ToPayrollTypeAsync / ToAllAsync). + * Subscribing connects if needed. + */ + on(topic: string): Observable { + return new Observable((subscriber) => { + this.connect(); + const sub = this.events$ + .pipe(filter((e) => e.topic === topic), map((e) => e.payload as T)) + .subscribe(subscriber); + return () => sub.unsubscribe(); + }); + } + + /** + * Live state of a background job, from its current state to its end (the observable completes when the job + * has Succeeded or Failed). Works the same after a page reload, in a second tab and on a flaky network: + * it joins the job over SignalR, re-joins after every reconnect, re-reads over HTTP when the push goes quiet, + * and polls over HTTP if no connection can be made at all. Out-of-date messages are dropped by sequence. + */ + watchJob(runId: string): Observable { + return new Observable((subscriber) => { + let last: JobSnapshot | null = null; + let lastMessageAt = Date.now(); + let closed = false; + let pollTimer: any = null; + let fetching = false; + + const emit = (job: JobSnapshot | null | undefined) => { + if (closed || !job || job.runId !== runId) { + return; + } + lastMessageAt = Date.now(); + if (last && job.sequence <= last.sequence) { + return; + } + last = job; + subscriber.next(job); + if (isJobFinished(job)) { + finish(); + subscriber.complete(); + } + }; + + const fetchOnce = () => { + if (closed || fetching) { + return; + } + fetching = true; + this.apiService.httpGet('/jobs/' + encodeURIComponent(runId)).subscribe({ + next: (job) => { + fetching = false; + emit(job); + }, + error: (err) => { + fetching = false; + if (err?.status === 404 || err?.status === 403) { + finish(); + subscriber.error(new Error(typeof err?.error === 'string' ? err.error : 'The job could not be found.')); + } + // other errors (network blip): the next tick tries again + } + }); + }; + + const joinOverHub = () => { + if (closed || !this.connection || !this.isConnected) { + return; + } + this.connection.invoke('SubscribeJob', runId) + .then((job) => this.zone.run(() => emit(job))) + .catch(() => this.zone.run(() => fetchOnce())); + }; + + // One timer does both jobs: polling when there is no connection, a silence check when there is. + const tick = () => { + if (closed) { + return; + } + if (!this.isConnected || Date.now() - lastMessageAt >= RealtimeService.SILENCE_CHECK_MS) { + fetchOnce(); + } + }; + + const subs = new Subscription(); + subs.add(this.jobProgress$.pipe(filter((j) => j.runId === runId)).subscribe((j) => emit(j))); + subs.add(this.resubscribe$.subscribe(() => joinOverHub())); + + const finish = () => { + if (closed) { + return; + } + closed = true; + subs.unsubscribe(); + if (pollTimer) { + clearInterval(pollTimer); + pollTimer = null; + } + if (this.connection && this.isConnected) { + this.connection.invoke('UnsubscribeJob', runId).catch(() => { /* connection going away */ }); + } + }; + + pollTimer = setInterval(tick, RealtimeService.POLL_MS); + this.connect().then((ok) => { + if (ok) { + joinOverHub(); // connect() may already have emitted resubscribe$ - a second join is harmless + } else { + fetchOnce(); + } + }); + + return () => finish(); + }); + } + + private buildConnection(): HubConnection { + const connection = new HubConnectionBuilder() + .withUrl(ApiService.BASE_URL + RealtimeService.HUB_PATH, { withCredentials: true }) + .withAutomaticReconnect(new SignedInRetryPolicy()) + .configureLogging(environment.production ? LogLevel.Warning : LogLevel.Information) + .build(); + + // Server -> browser methods: the names of HRM.UI/Realtime/IAppClient.cs. + connection.on('JobProgress', (job: JobSnapshot) => this.zone.run(() => this.jobProgress$.next(job))); + connection.on('Event', (topic: string, payload: any) => this.zone.run(() => this.events$.next({ topic, payload }))); + + connection.onreconnecting(() => this.setState('reconnecting')); + connection.onreconnected(() => { + this.setState('connected'); + this.zone.run(() => this.resubscribe$.next()); + }); + connection.onclose(() => { + if (this.connection === connection) { + this.setState('disconnected'); + } + }); + return connection; + } + + private dropConnection(): void { + const connection = this.connection; + this.connection = null; + this.connectedToken = null; + this.startPromise = null; + this.setState('disconnected'); + if (connection) { + connection.stop().catch(() => { /* already closed */ }); + } + } + + private setState(state: RealtimeConnectionState): void { + if (this.stateSubject.value !== state) { + this.zone.run(() => this.stateSubject.next(state)); + } + } +} diff --git a/HRM.UI/ClientApp/src/app/payroll/payroll.module.ts b/HRM.UI/ClientApp/src/app/payroll/payroll.module.ts index 8b15a37..724ee93 100644 --- a/HRM.UI/ClientApp/src/app/payroll/payroll.module.ts +++ b/HRM.UI/ClientApp/src/app/payroll/payroll.module.ts @@ -6,6 +6,7 @@ import { GridModule, PDFModule, ExcelModule } from '@progress/kendo-angular-grid import { InputsModule } from '@progress/kendo-angular-inputs'; import { ChartsModule } from '@progress/kendo-angular-charts'; import { DialogsModule, WindowModule } from '@progress/kendo-angular-dialog'; +import { RealtimeSharedModule } from '../realtime/realtime-shared.module'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; //import { CodeHighlighterModule } from 'primeng/codehighlighter'; //import { FullCalendarModule } from 'primeng/fullcalendar'; @@ -98,6 +99,7 @@ import { MasterMailLogModule } from '../master-mail-log/master-mail-log.module'; FormsModule, ReactiveFormsModule, DialogsModule, + RealtimeSharedModule, CommonModule, GridModule, InputsModule, diff --git a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.html b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.html index abc08e8..486bb86 100644 --- a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.html +++ b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.html @@ -1,4 +1,22 @@ + + +@if (showProcessProgress && processRunId) { +
+ + + + @if (processJobFailed) { + + } + +
+}
diff --git a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.scss b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.scss index e66b737..78f62e1 100644 --- a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.scss +++ b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.scss @@ -76,3 +76,29 @@ padding: 6px 10px; } } + +// Salary process progress dialog: no header, no Kendo frame - the progress card is the whole dialog. +:host ::ng-deep .sp-progress-dialog .k-window, +:host ::ng-deep .sp-progress-dialog .k-dialog { + border: 0; + border-radius: 20px; + overflow: hidden; + max-width: calc(100vw - 32px); + box-shadow: 0 30px 80px rgba(15, 23, 42, 0.28), 0 6px 20px rgba(15, 23, 42, 0.12); + animation: sp-dialog-in 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); +} +:host ::ng-deep .sp-progress-dialog .k-window-content, +:host ::ng-deep .sp-progress-dialog .k-dialog-content { + padding: 0; + overflow: hidden; +} +.sp-progress-footer { + display: flex; + justify-content: flex-end; + padding: 0 28px 22px; + background: #ffffff; +} +@keyframes sp-dialog-in { + from { opacity: 0; transform: translateY(14px) scale(0.98); } + to { opacity: 1; transform: none; } +} diff --git a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.ts b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.ts index f88dc33..652714a 100644 --- a/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll/salary/salary-process/salary-process.component.ts @@ -1,4 +1,4 @@ -import {Component, OnInit, ChangeDetectionStrategy} from '@angular/core'; +import {Component, OnInit, OnDestroy, ChangeDetectionStrategy} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {ApiService} from '../../../app.api.service'; import {HRMNotificationService} from '../../../app.notification.service'; @@ -13,6 +13,7 @@ import {AuthService} from '../../../_services/auth/auth.service'; import {BasicService} from '../../../_services/Basic/basic.service'; import {EmployeeServices} from '../../../_services/employee/employee.service'; import {SalaryService} from '../../../_services/payroll/salary.service'; +import {JobSnapshot} from '../../../_models/realtime/job-snapshot'; import { CommonModule } from '@angular/common'; import { LoadingPanelComponent } from 'src/app/hrm-loding panel/loading-panel.component'; @@ -32,7 +33,7 @@ import { EmployeePickerComponent } from 'src/app/picker/employee-picker.componen standalone: false, }) -export class SalaryProcessComponent implements OnInit { +export class SalaryProcessComponent implements OnInit, OnDestroy { _salaryProcess: FormGroup; salaryMonth: Date = new Date(); payrollType: PayrollType; @@ -44,6 +45,12 @@ export class SalaryProcessComponent implements OnInit { returnMessage: string = ''; processRequest: { paymentDate: Date, remarks: string, empid: number, euroRate: number }[]; euroRate = 0; + // Real-time progress of the salary process job (SignalR) + showProcessProgress: boolean = false; + processRunId: string | null = null; + processJobFinished: boolean = false; + processJobFailed: boolean = false; + private progressCloseTimer: any = null; // Category: when no employee is selected, the salary of this category's employees is processed categories: Category[] = []; selectedCategoryID: number = null; @@ -79,6 +86,7 @@ export class SalaryProcessComponent implements OnInit { ngOnInit() { this.pbuttonEnalble = true; this.createFrom(); + this.resumeActiveProcessJob(); // categories of the current payroll type (the API filters by the login's payroll type) this.basicDataService.getAllCategory(EnumStatus.Active).subscribe( @@ -231,38 +239,97 @@ export class SalaryProcessComponent implements OnInit { }); } - // the salary process itself, unchanged: one request item per employee + // The salary process: one request item per employee, exactly as before. It now runs as a background job on the + // server (same processing, same result) and the dialog shows its real progress over SignalR. private runSalaryProcess(empIDs: number[]) { this.loadingPanelService.ShowLoadingPanel = true; - var returnID: number; this.processRequest = []; empIDs.forEach(empID => { this.processRequest.push({ 'paymentDate': this.paymentdate, 'remarks': this.remarks, 'empid': empID, 'euroRate': this.euroRate }); }); this.errorOrSucessList = []; - this.salaryservice.salaryProcess(this.processRequest).subscribe( - (resp: any) => { - this.errorOrSucessList = resp; + this.returnMessage = ''; + this.salaryservice.salaryProcessStart(this.processRequest).subscribe( + (job: JobSnapshot) => { + this.loadingPanelService.ShowLoadingPanel = false; + this.followProcessJob(job); }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showError(err.error); this.returnMessage = err.error; - }, - () => { - this.loadingPanelService.ShowLoadingPanel = false; - this.pbuttonEnalble = false; + }); + } - if (this.errorOrSucessList == undefined) { - this.notificationService.showSuccess('Salary processed and saved successfully'); - this.returnMessage = 'Salary processed and saved successfully'; - } else { - this.notificationService.showError('Salary process unsuccessful, please check the following error.'); - this.returnMessage = 'Salary process unsuccessful, please check the following error.'; + /** Opens the progress dialog for a running (or just started) salary process job. */ + private followProcessJob(job: JobSnapshot) { + if (!job?.runId) { + return; + } + this.clearProgressCloseTimer(); + this.processJobFinished = false; + this.processJobFailed = false; + this.processRunId = job.runId; + this.showProcessProgress = true; + } + /** Same outcome handling as the old synchronous call: result null = success, otherwise the error list. */ + onProcessJobSucceeded(job: JobSnapshot) { + this.processJobFinished = true; + this.errorOrSucessList = job.result; + this.pbuttonEnalble = false; + + if (this.errorOrSucessList == undefined) { + this.notificationService.showSuccess('Salary processed and saved successfully'); + this.returnMessage = 'Salary processed and saved successfully'; + } else { + this.notificationService.showError('Salary process unsuccessful, please check the following error.'); + this.returnMessage = 'Salary process unsuccessful, please check the following error.'; + } + // Let the 100 % and the completed tick show for a moment, then close by itself. + this.clearProgressCloseTimer(); + this.progressCloseTimer = setTimeout(() => this.closeProcessProgress(), 1400); + } + + onProcessJobFailed(error: string) { + this.processJobFinished = true; + this.processJobFailed = true; + this.notificationService.showError(error); + this.returnMessage = error; + } + + /** The dialog has no cancel: Esc / close is ignored while the process runs. */ + onProcessDialogClose() { + if (this.processJobFinished) { + this.closeProcessProgress(); + } + } + + closeProcessProgress() { + this.clearProgressCloseTimer(); + this.showProcessProgress = false; + this.processRunId = null; + } + + ngOnDestroy() { + this.clearProgressCloseTimer(); + } + + private clearProgressCloseTimer() { + if (this.progressCloseTimer) { + clearTimeout(this.progressCloseTimer); + this.progressCloseTimer = null; + } + } + + /** A salary process already running in this payroll type (other tab, other admin, page reload): follow it. */ + private resumeActiveProcessJob() { + this.salaryservice.salaryProcessActive().subscribe( + (job: JobSnapshot) => { + if (job?.runId) { + this.followProcessJob(job); } - } - ); - + }, + () => { /* nothing running, or the server is older - the screen works as before */ }); } } diff --git a/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.html b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.html new file mode 100644 index 0000000..86ce630 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.html @@ -0,0 +1,89 @@ + diff --git a/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.scss b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.scss new file mode 100644 index 0000000..212d55a --- /dev/null +++ b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.scss @@ -0,0 +1,298 @@ +// Live job progress card. Follows the GoHR runtime palette (--gh-btn on :root) with literal fallbacks. +// All motion is presentation only; the numbers come from the server. + +:host { + --jp-accent: var(--gh-btn, #045AEA); + --jp-accent-soft: color-mix(in srgb, var(--jp-accent) 12%, white); + --jp-accent-light: color-mix(in srgb, var(--jp-accent) 55%, white); + --jp-success: #16A34A; + --jp-fail: #DC2626; + display: block; +} + +.jp { + position: relative; + display: flex; + flex-direction: column; + gap: 18px; + padding: 28px 28px 24px; + border-radius: 20px; + background: + radial-gradient(120% 80% at 100% 0%, var(--jp-accent-soft) 0%, rgba(255, 255, 255, 0) 60%), + #ffffff; + color: #111827; + overflow: hidden; +} + +// ── Top row ────────────────────────────────────────────────────────────── +.jp-top { + display: flex; + align-items: center; + gap: 16px; +} + +.jp-icon { + position: relative; + width: 52px; + height: 52px; + flex-shrink: 0; + display: grid; + place-items: center; +} + +.jp-icon-core { + width: 26px; + height: 26px; + fill: none; + stroke: var(--jp-accent); + stroke-width: 1.8; + animation: jp-spin 4s linear infinite; +} + +.jp-orbit { + position: absolute; + inset: 0; + border-radius: 50%; + border: 2.5px solid transparent; + border-top-color: var(--jp-accent); + border-right-color: var(--jp-accent-light); + animation: jp-spin 1.1s cubic-bezier(0.55, 0.15, 0.45, 0.85) infinite; +} +.jp-orbit--2 { + inset: 7px; + border-width: 2px; + border-top-color: transparent; + border-bottom-color: var(--jp-accent-light); + animation-duration: 1.6s; + animation-direction: reverse; +} + +.jp-icon-check, +.jp-icon-fail { + width: 52px; + height: 52px; + fill: none; + stroke-width: 3; + stroke-linecap: round; + stroke-linejoin: round; +} +.jp-icon-check { stroke: var(--jp-success); } +.jp-icon-fail { stroke: var(--jp-fail); } +.jp-check-circle { + stroke-dasharray: 150; + stroke-dashoffset: 150; + animation: jp-draw 0.6s ease-out forwards; +} +.jp-check-mark { + stroke-dasharray: 50; + stroke-dashoffset: 50; + animation: jp-draw 0.35s 0.45s ease-out forwards; +} + +.jp-heading { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.jp-title { + font-size: 17px; + font-weight: 700; + letter-spacing: -0.01em; +} + +.jp-stage { + display: flex; + align-items: center; + gap: 8px; + font-size: 13.5px; + font-weight: 500; + color: #4B5563; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + animation: jp-stage-in 0.35s ease-out; +} + +.jp-live { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--jp-accent); + flex-shrink: 0; + box-shadow: 0 0 0 0 color-mix(in srgb, var(--jp-accent) 50%, transparent); + animation: jp-ping 1.4s ease-out infinite; +} + +// ── Percentage ─────────────────────────────────────────────────────────── +.jp-percent { + display: flex; + align-items: baseline; + line-height: 1; + font-variant-numeric: tabular-nums; + color: var(--jp-accent); + transition: color 0.4s ease; +} +.jp-percent-whole { font-size: 52px; font-weight: 800; letter-spacing: -0.03em; } +.jp-percent-frac { font-size: 26px; font-weight: 700; opacity: 0.75; } +.jp-percent-sign { font-size: 24px; font-weight: 700; margin-left: 4px; opacity: 0.6; } + +// ── Bar ────────────────────────────────────────────────────────────────── +.jp-track { + position: relative; + height: 22px; + border-radius: 999px; + background: #EEF2F7; + box-shadow: inset 0 1px 3px rgba(15, 23, 42, 0.12); + overflow: hidden; +} + +.jp-fill { + position: relative; + height: 100%; + min-width: 22px; + border-radius: inherit; + background: linear-gradient(90deg, var(--jp-accent-light) 0%, var(--jp-accent) 100%); + box-shadow: 0 2px 10px color-mix(in srgb, var(--jp-accent) 35%, transparent); + overflow: hidden; + transition: background 0.4s ease; +} + +// Moving diagonal stripes while the job is running +.jp-stripes { + position: absolute; + inset: 0; + background-image: repeating-linear-gradient( + -45deg, + rgba(255, 255, 255, 0.22) 0 10px, + rgba(255, 255, 255, 0) 10px 20px + ); + background-size: 28.28px 28.28px; + opacity: 0; + transition: opacity 0.3s ease; +} +.jp--running .jp-stripes { + opacity: 1; + animation: jp-stripes 0.9s linear infinite; +} + +// A light sweep passing along the filled part +.jp-sheen { + position: absolute; + top: 0; + bottom: 0; + width: 40%; + left: -40%; + background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 50%, rgba(255, 255, 255, 0) 100%); + opacity: 0; +} +.jp--running .jp-sheen { + opacity: 1; + animation: jp-sheen 2.2s ease-in-out infinite; +} + +// Glowing leading edge +.jp-head { + position: absolute; + top: 3px; + right: 3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: #ffffff; + box-shadow: 0 0 0 4px color-mix(in srgb, #ffffff 35%, transparent), 0 0 14px 4px rgba(255, 255, 255, 0.85); + animation: jp-head 1.2s ease-in-out infinite; +} + +// ── Detail / error ─────────────────────────────────────────────────────── +.jp-detail { + margin-top: -6px; + font-size: 12.5px; + color: #6B7280; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.jp-error { + padding: 10px 12px; + border-radius: 10px; + background: #FEF2F2; + border: 1px solid #FECACA; + color: #B91C1C; + font-size: 13px; + animation: jp-stage-in 0.3s ease-out; +} + +// ── Facts ──────────────────────────────────────────────────────────────── +.jp-facts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); + gap: 10px; +} + +.jp-fact { + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 12px; + border-radius: 12px; + background: #F8FAFC; + border: 1px solid #EEF2F7; +} + +.jp-fact-label { + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: #9CA3AF; +} + +.jp-fact-value { + font-size: 15px; + font-weight: 700; + color: #1F2937; + font-variant-numeric: tabular-nums; + + small { font-size: 12px; font-weight: 600; color: #9CA3AF; } +} + +// ── Finished states ────────────────────────────────────────────────────── +.jp--success { + .jp-percent { color: var(--jp-success); } + .jp-fill { + background: linear-gradient(90deg, #4ADE80 0%, var(--jp-success) 100%); + box-shadow: 0 2px 10px rgba(22, 163, 74, 0.35); + } +} + +.jp--failed { + .jp-percent { color: var(--jp-fail); } + .jp-fill { + background: linear-gradient(90deg, #F87171 0%, var(--jp-fail) 100%); + box-shadow: 0 2px 10px rgba(220, 38, 38, 0.3); + } +} + +// ── Keyframes ──────────────────────────────────────────────────────────── +@keyframes jp-spin { to { transform: rotate(360deg); } } +@keyframes jp-draw { to { stroke-dashoffset: 0; } } +@keyframes jp-stripes { from { background-position: 0 0; } to { background-position: 28.28px 0; } } +@keyframes jp-sheen { 0% { left: -40%; } 60%, 100% { left: 110%; } } +@keyframes jp-head { 0%, 100% { transform: scale(0.85); opacity: 0.85; } 50% { transform: scale(1.05); opacity: 1; } } +@keyframes jp-stage-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } } +@keyframes jp-ping { + 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--jp-accent) 50%, transparent); } + 100% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--jp-accent) 0%, transparent); } +} + +@media (prefers-reduced-motion: reduce) { + .jp-orbit, .jp-icon-core, .jp-stripes, .jp-sheen, .jp-head, .jp-live { animation: none !important; } +} + +@media (max-width: 480px) { + .jp { padding: 22px 18px 18px; } + .jp-percent-whole { font-size: 42px; } +} diff --git a/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.ts b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.ts new file mode 100644 index 0000000..f7a16fc --- /dev/null +++ b/HRM.UI/ClientApp/src/app/realtime/job-progress/job-progress.component.ts @@ -0,0 +1,229 @@ +import { + ChangeDetectionStrategy, + Component, + EventEmitter, + Input, + OnChanges, + OnDestroy, + Output, + SimpleChanges +} from '@angular/core'; +import { Subscription } from 'rxjs'; +import { RealtimeService } from '../../_services/realtime/realtime.service'; +import { JobSnapshot, JobStatus } from '../../_models/realtime/job-snapshot'; + +/** + * Live progress of one background job (HRM.UI/Realtime/Jobs). Give it the runId the start endpoint returned: + * + * + * + * Every number comes from the server (percent, stage, items done, elapsed, estimate). The only things done here are + * presentation: the bar and the percentage glide to each new value instead of jumping, and the elapsed / remaining + * clocks keep ticking between two server messages (from the last value the server sent, never invented). + */ +@Component({ + selector: 'app-job-progress', + templateUrl: './job-progress.component.html', + styleUrls: ['./job-progress.component.scss'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false +}) +export class JobProgressComponent implements OnChanges, OnDestroy { + @Input() runId: string | null = null; + /** Overrides the job's own title. */ + @Input() title: string | null = null; + + /** Every change (also the first state). */ + @Output() changed = new EventEmitter(); + /** The job finished successfully; job.result holds what the work returned. */ + @Output() succeeded = new EventEmitter(); + /** The job failed, or could not be followed at all. */ + @Output() failed = new EventEmitter(); + + job: JobSnapshot | null = null; + watchError: string | null = null; + readonly JobStatus = JobStatus; + + /** The percentage on screen; glides towards job.percent. */ + displayPercent = 0; + /** Elapsed / remaining seconds on screen; tick every second from the last server values. */ + elapsedNow = 0; + etaNow: number | null = null; + + private watch: Subscription | null = null; + private tweenFrame: number | null = null; + private clockTimer: any = null; + private receivedAt = 0; + + constructor(private realtime: RealtimeService) { } + + ngOnChanges(changes: SimpleChanges): void { + if (changes['runId']) { + this.start(); + } + } + + ngOnDestroy(): void { + this.unwatch(); + this.stopTween(); + this.stopClock(); + } + + get isRunning(): boolean { + return !this.watchError && !!this.job && (this.job.status === JobStatus.Queued || this.job.status === JobStatus.Running); + } + + get isSucceeded(): boolean { + return this.job?.status === JobStatus.Succeeded; + } + + get isFailed(): boolean { + return !!this.watchError || this.job?.status === JobStatus.Failed; + } + + get percentWhole(): string { + return Math.floor(this.displayPercent).toString(); + } + + get percentFraction(): string { + if (this.displayPercent >= 100 || this.displayPercent <= 0) { + return ''; + } + return '.' + Math.floor((this.displayPercent % 1) * 10).toString(); + } + + get hasCount(): boolean { + return !!this.job && this.job.total != null && this.job.total > 0 && this.job.current != null; + } + + get stageText(): string { + if (this.watchError) { + return 'Could not follow the process'; + } + if (!this.job) { + return 'Connecting…'; + } + if (this.isSucceeded) { + return 'Completed'; + } + if (this.job.status === JobStatus.Failed) { + return 'Process failed'; + } + return this.job.stage || 'Starting…'; + } + + formatDuration(seconds: number | null | undefined): string { + if (seconds == null || isNaN(seconds)) { + return '—'; + } + const s = Math.max(0, Math.round(seconds)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + if (h > 0) { + return `${h}h ${m.toString().padStart(2, '0')}m`; + } + if (m > 0) { + return `${m}m ${sec.toString().padStart(2, '0')}s`; + } + return `${sec}s`; + } + + private start(): void { + this.unwatch(); + this.stopTween(); + this.stopClock(); + this.job = null; + this.watchError = null; + this.displayPercent = 0; + this.elapsedNow = 0; + this.etaNow = null; + if (!this.runId) { + return; + } + this.watch = this.realtime.watchJob(this.runId).subscribe({ + next: (job) => this.apply(job), + error: (err) => { + this.watchError = err?.message || 'The job could not be followed.'; + this.stopClock(); + this.failed.emit(this.watchError); + } + }); + } + + private apply(job: JobSnapshot): void { + this.job = job; + this.receivedAt = Date.now(); + this.elapsedNow = job.elapsedSeconds || 0; + this.etaNow = job.etaSeconds; + this.tweenTo(Math.min(100, Math.max(0, job.percent || 0))); + + if (this.isRunning) { + this.startClock(); + } else { + this.stopClock(); + } + + this.changed.emit(job); + if (job.status === JobStatus.Succeeded) { + this.succeeded.emit(job); + } else if (job.status === JobStatus.Failed) { + this.failed.emit(job.error || 'The job failed.'); + } + } + + /** Glides the shown percentage to the new real value (ease-out, ~0.6 s). */ + private tweenTo(target: number): void { + this.stopTween(); + const from = this.displayPercent; + if (Math.abs(target - from) < 0.05) { + this.displayPercent = target; + return; + } + const duration = 600; + const startedAt = performance.now(); + const step = (now: number) => { + const t = Math.min(1, (now - startedAt) / duration); + const eased = 1 - Math.pow(1 - t, 3); + this.displayPercent = from + (target - from) * eased; + this.tweenFrame = t < 1 ? requestAnimationFrame(step) : null; + }; + this.tweenFrame = requestAnimationFrame(step); + } + + private stopTween(): void { + if (this.tweenFrame != null) { + cancelAnimationFrame(this.tweenFrame); + this.tweenFrame = null; + } + } + + /** Elapsed counts up and the estimate counts down between two server messages. */ + private startClock(): void { + if (this.clockTimer) { + return; + } + this.clockTimer = setInterval(() => { + if (!this.job) { + return; + } + const since = (Date.now() - this.receivedAt) / 1000; + this.elapsedNow = (this.job.elapsedSeconds || 0) + since; + this.etaNow = this.job.etaSeconds != null ? Math.max(0, this.job.etaSeconds - since) : null; + }, 1000); + } + + private stopClock(): void { + if (this.clockTimer) { + clearInterval(this.clockTimer); + this.clockTimer = null; + } + } + + private unwatch(): void { + if (this.watch) { + this.watch.unsubscribe(); + this.watch = null; + } + } +} diff --git a/HRM.UI/ClientApp/src/app/realtime/realtime-shared.module.ts b/HRM.UI/ClientApp/src/app/realtime/realtime-shared.module.ts new file mode 100644 index 0000000..66a7917 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/realtime/realtime-shared.module.ts @@ -0,0 +1,14 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { JobProgressComponent } from './job-progress/job-progress.component'; + +/** + * Reusable real-time UI. Import it into a feature module to use . + * The connection itself is RealtimeService (providedIn: 'root'), so importing this module twice is harmless. + */ +@NgModule({ + declarations: [JobProgressComponent], + imports: [CommonModule], + exports: [JobProgressComponent] +}) +export class RealtimeSharedModule { } diff --git a/HRM.UI/Controllers/Payroll/SalaryController.cs b/HRM.UI/Controllers/Payroll/SalaryController.cs index 63ab486..26035e9 100644 --- a/HRM.UI/Controllers/Payroll/SalaryController.cs +++ b/HRM.UI/Controllers/Payroll/SalaryController.cs @@ -1196,6 +1196,98 @@ namespace HRM.UI.Controllers.Payroll return Ok(errorOrSucess); } + #region Salary Process with real-time progress (background job + SignalR) + + /// + /// Same request body and the same processing as SalaryProcess above, but it runs as a background job: the call + /// answers at once with the job (runId), and the browser follows its real progress over SignalR + /// (RealtimeService.watchJob). The job's Result is exactly what SalaryProcess returns: null on success, otherwise + /// the error list. One run per payroll type at a time - a second start returns the running one. + /// + [HttpPost] + [Route("SalaryProcess-start")] + public ActionResult SalaryProcessStart(dynamic processItems, [FromServices] HRM.UI.Realtime.Jobs.IJobRunner jobRunner) + { + SalaryProcess oporcess = new SalaryProcess(); + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + + // Parsed exactly as SalaryProcess parses it. + var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(processItems)); + int index = 0; + string empid = ""; + try + { + foreach (var item in items) + { + if (index == 0) + { + oporcess.PayrollTypeID = (int)currentUser.PayrollTypeID; + oporcess.CreatedBy = currentUser.UserID; + oporcess.CreatedDate = DateTime.Today; + oporcess.SalaryMonth = GlobalFunctions.LastDateOfMonth((DateTime)currentUser.NextPayProcessDate); + if (item["euroRate"] != null) + { + oporcess.EuroRate = (double)item["euroRate"].ToObject(); + } + if (item["remarks"] != null) + oporcess.Remarks = (string)item["remarks"].ToObject(); + oporcess.PaymentDate = (DateTime)item["paymentDate"].ToObject(); + oporcess.ProcessCode = oporcess.SalaryMonth.ToString("ddmmyy") + DateTime.Today.ToString("hh:mm"); + oporcess.ProcessDate = DateTime.Today; + } + empid = empid + (string)item["empid"].ToObject() + ","; + } + if (empid.Length > 0) + { + empid = empid.Substring(0, empid.Length - 1); + } + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + + // Everything the work needs is copied now: it runs after this request has ended. + int payrollTypeId = (int)currentUser.PayrollTypeID; + string employeeIds = empid; + + HRM.UI.Realtime.Jobs.JobStartResult started = jobRunner.Start(new HRM.UI.Realtime.Jobs.JobRequest + { + Key = SalaryProcessJobKey(payrollTypeId), + Title = "Salary Process", + OwnerUserId = currentUser.UserID, + PayrollTypeId = payrollTypeId, + Audience = HRM.UI.Realtime.Jobs.JobAudience.PayrollType, + Work = progress => + { + progress.TryReport(0, "Loading employees"); + List employees = this._employeeService.GetByEmpIDs(employeeIds, payrollTypeId); + List errorOrSucess = this._salaryProcessService.SalaryProcess(oporcess, employees, progress); + if (errorOrSucess != null && errorOrSucess.Count == 0) errorOrSucess = null; + return errorOrSucess; + } + }); + + return Ok(started.Job); + } + + /// The salary process running now in the user's payroll type (null when none), so a reopened screen follows it. + [HttpGet("SalaryProcess-active")] + public ActionResult SalaryProcessActive([FromServices] HRM.UI.Realtime.Jobs.IJobRunner jobRunner) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser?.PayrollTypeID == null) + return Ok(null); + return Ok(jobRunner.GetActive(SalaryProcessJobKey(currentUser.PayrollTypeID.Value), currentUser.UserID, currentUser.PayrollTypeID)); + } + + private static string SalaryProcessJobKey(int payrollTypeId) + { + return "salary-process:" + payrollTypeId; + } + + #endregion + // Salary Process screen: no employee selected but a Category -> the employees to process [HttpGet("getCategoryEmployeeIDsForSalary/{categoryID}")] diff --git a/HRM.UI/Controllers/Realtime/JobsController.cs b/HRM.UI/Controllers/Realtime/JobsController.cs new file mode 100644 index 0000000..4904ac7 --- /dev/null +++ b/HRM.UI/Controllers/Realtime/JobsController.cs @@ -0,0 +1,37 @@ +using HRM.BO; +using HRM.UI.Realtime.Jobs; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace HRM.UI.Controllers.Realtime +{ + /// + /// Reading background jobs over plain HTTP. The browser uses it to catch up (page reload, another tab) and as a + /// fallback when no SignalR connection can be made; live changes come over the hub. + /// + [ApiController] + [Route("api/jobs")] + [Authorize] + public class JobsController : ControllerBase + { + private readonly IJobRunner _jobRunner; + + public JobsController(IJobRunner jobRunner) + { + _jobRunner = jobRunner; + } + + /// One job's current state. + [HttpGet("{runId}")] + public ActionResult Get(string runId) + { + CurrentUser user = CurrentUser.GetCurrentUser(HttpContext.User); + JobAccess access = _jobRunner.TryGet(runId, user.UserID, user.PayrollTypeID, out JobSnapshot snapshot); + if (access == JobAccess.NotFound) + return NotFound("The job could not be found. The application may have restarted."); + if (access == JobAccess.Forbidden) + return Forbid(); + return Ok(snapshot); + } + } +} diff --git a/HRM.UI/HRM.UI.csproj b/HRM.UI/HRM.UI.csproj index 2676f22..93f3acf 100644 --- a/HRM.UI/HRM.UI.csproj +++ b/HRM.UI/HRM.UI.csproj @@ -1218,6 +1218,7 @@ + diff --git a/HRM.UI/Realtime/AppHub.cs b/HRM.UI/Realtime/AppHub.cs new file mode 100644 index 0000000..c11c107 --- /dev/null +++ b/HRM.UI/Realtime/AppHub.cs @@ -0,0 +1,65 @@ +using HRM.BO; +using HRM.UI.Realtime.Jobs; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using System; +using System.Threading.Tasks; + +namespace HRM.UI.Realtime +{ + /// + /// The application's single SignalR hub (/api/hubs/app). One connection per browser tab carries every real-time + /// feature; features are told apart by groups and topics, never by extra hubs. + /// + /// Authentication is the app's normal JWT (the HttpOnly JWToken cookie, read in Startup's OnMessageReceived). + /// Clients never pick a group: the hub adds them, after checking their claims. + /// + [Authorize] + public class AppHub : Hub + { + private readonly IJobRunner _jobRunner; + + public AppHub(IJobRunner jobRunner) + { + _jobRunner = jobRunner; + } + + public override async Task OnConnectedAsync() + { + CurrentUser user = CurrentUser.GetCurrentUser(Context.User); + if (user?.PayrollTypeID != null) + await Groups.AddToGroupAsync(Context.ConnectionId, RealtimeGroups.PayrollType(user.PayrollTypeID.Value)); + await base.OnConnectedAsync(); + } + + /// + /// Starts following a background job: answers its current state and from then on pushes every change as JobProgress. + /// Call it again after a reconnect (the browser does) - group membership does not survive a new connection. + /// + public async Task SubscribeJob(string runId) + { + CurrentUser user = CurrentUser.GetCurrentUser(Context.User); + if (user == null) + throw new HubException("Not signed in."); + + JobAccess access = _jobRunner.TryGet(runId, user.UserID, user.PayrollTypeID, out _); + if (access == JobAccess.NotFound) + throw new HubException("The job could not be found. The application may have restarted."); + if (access == JobAccess.Forbidden) + throw new HubException("You are not allowed to follow this job."); + + await Groups.AddToGroupAsync(Context.ConnectionId, RealtimeGroups.Job(runId)); + + // Read the state only after joining the group, so no change can fall between the answer and the first push. + _jobRunner.TryGet(runId, user.UserID, user.PayrollTypeID, out JobSnapshot snapshot); + return snapshot; + } + + public Task UnsubscribeJob(string runId) + { + if (string.IsNullOrEmpty(runId)) + return Task.CompletedTask; + return Groups.RemoveFromGroupAsync(Context.ConnectionId, RealtimeGroups.Job(runId)); + } + } +} diff --git a/HRM.UI/Realtime/IAppClient.cs b/HRM.UI/Realtime/IAppClient.cs new file mode 100644 index 0000000..b9803f0 --- /dev/null +++ b/HRM.UI/Realtime/IAppClient.cs @@ -0,0 +1,19 @@ +using HRM.UI.Realtime.Jobs; +using System.Threading.Tasks; + +namespace HRM.UI.Realtime +{ + /// + /// What the server can call on a browser. The method names are the event names the Angular RealtimeService listens to, + /// so renaming one here means renaming it there (src/app/_services/realtime/realtime.service.ts). + /// Prefer with a new topic over adding a method: it needs no change on either side. + /// + public interface IAppClient + { + /// A background job moved on (progress, stage, finished, failed). + Task JobProgress(JobSnapshot snapshot); + + /// Any other real-time message. is a dotted name such as "calendar.changed". + Task Event(string topic, object payload); + } +} diff --git a/HRM.UI/Realtime/IRealtimePublisher.cs b/HRM.UI/Realtime/IRealtimePublisher.cs new file mode 100644 index 0000000..96cfdd3 --- /dev/null +++ b/HRM.UI/Realtime/IRealtimePublisher.cs @@ -0,0 +1,68 @@ +using HRM.UI.Realtime.Jobs; +using Microsoft.AspNetCore.SignalR; +using System.Threading.Tasks; + +namespace HRM.UI.Realtime +{ + /// + /// The only way application code sends real-time messages. Inject it (singleton) wherever a push is needed; + /// never inject IHubContext directly, so a later move to Redis / Azure SignalR changes this one class only. + /// All methods are fire-safe: a failed send is logged, never thrown back into business code. + /// + public interface IRealtimePublisher + { + /// To every open tab of one user (the JWT "UserID" claim). + Task ToUserAsync(int userId, string topic, object payload); + + /// To every user currently working in one payroll type. + Task ToPayrollTypeAsync(int payrollTypeId, string topic, object payload); + + /// To every connected user. + Task ToAllAsync(string topic, object payload); + + /// A job's progress to everybody following it. Used by the job runner; features rarely need it. + Task JobChangedAsync(JobSnapshot snapshot); + } + + internal sealed class RealtimePublisher : IRealtimePublisher + { + private readonly IHubContext _hub; + + public RealtimePublisher(IHubContext hub) + { + _hub = hub; + } + + public Task ToUserAsync(int userId, string topic, object payload) + { + return Safe(_hub.Clients.User(userId.ToString()).Event(topic, payload)); + } + + public Task ToPayrollTypeAsync(int payrollTypeId, string topic, object payload) + { + return Safe(_hub.Clients.Group(RealtimeGroups.PayrollType(payrollTypeId)).Event(topic, payload)); + } + + public Task ToAllAsync(string topic, object payload) + { + return Safe(_hub.Clients.All.Event(topic, payload)); + } + + public Task JobChangedAsync(JobSnapshot snapshot) + { + return Safe(_hub.Clients.Group(RealtimeGroups.Job(snapshot.RunId)).JobProgress(snapshot)); + } + + private static async Task Safe(Task send) + { + try + { + await send.ConfigureAwait(false); + } + catch (System.Exception ex) + { + Ease.Core.Utility.ExceptionLog.Write(ex); + } + } + } +} diff --git a/HRM.UI/Realtime/Jobs/JobProgressReporter.cs b/HRM.UI/Realtime/Jobs/JobProgressReporter.cs new file mode 100644 index 0000000..849b9fe --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobProgressReporter.cs @@ -0,0 +1,100 @@ +using HRM.BO; +using System; +using System.Threading; + +namespace HRM.UI.Realtime.Jobs +{ + /// + /// The IJobProgress a job's work receives. Work may call Report thousands of times a second; this class keeps the + /// latest values and sends at most one message per throttle interval, except that a new stage is sent at once. + /// A trailing timer makes sure the last value is always sent, even when the work goes quiet after it. + /// + internal sealed class JobProgressReporter : IJobProgress, IDisposable + { + private readonly JobState _state; + private readonly IRealtimePublisher _publisher; + private readonly TimeSpan _throttle; + private readonly Timer _flushTimer; + private DateTime _lastSent = DateTime.MinValue; + private bool _pending; + private bool _timerArmed; + private bool _disposed; + + public JobProgressReporter(JobState state, IRealtimePublisher publisher, TimeSpan throttle, CancellationToken cancellationToken) + { + _state = state; + _publisher = publisher; + _throttle = throttle; + CancellationToken = cancellationToken; + _flushTimer = new Timer(_ => Flush(), null, Timeout.Infinite, Timeout.Infinite); + } + + public CancellationToken CancellationToken { get; } + + public void Report(double percent, string stage = null, string detail = null, int? current = null, int? total = null) + { + JobSnapshot toSend = null; + lock (_state.Sync) + { + if (_disposed || _state.IsFinished) + return; + + bool stageChanged = stage != null && !string.Equals(stage, _state.Stage, StringComparison.Ordinal); + + if (double.IsNaN(percent)) percent = _state.Percent; + // Never backwards, never 100 before the work has really returned. + _state.Percent = Math.Max(_state.Percent, Math.Min(Math.Max(percent, 0), 99.9)); + if (stage != null) _state.Stage = stage; + _state.Detail = detail; + _state.Current = current; + _state.Total = total; + + DateTime now = DateTime.Now; + if (stageChanged || now - _lastSent >= _throttle) + { + _state.Sequence++; + _lastSent = now; + _pending = false; + toSend = _state.ToSnapshot(); + } + else + { + _pending = true; + if (!_timerArmed) + { + _timerArmed = true; + _flushTimer.Change(_throttle, Timeout.InfiniteTimeSpan); + } + } + } + + if (toSend != null) + _ = _publisher.JobChangedAsync(toSend); + } + + private void Flush() + { + JobSnapshot toSend = null; + lock (_state.Sync) + { + _timerArmed = false; + if (_disposed || !_pending || _state.IsFinished) + return; + _state.Sequence++; + _lastSent = DateTime.Now; + _pending = false; + toSend = _state.ToSnapshot(); + } + _ = _publisher.JobChangedAsync(toSend); + } + + public void Dispose() + { + lock (_state.Sync) + { + _disposed = true; + } + _flushTimer.Dispose(); + } + } +} diff --git a/HRM.UI/Realtime/Jobs/JobRequest.cs b/HRM.UI/Realtime/Jobs/JobRequest.cs new file mode 100644 index 0000000..f98b60f --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobRequest.cs @@ -0,0 +1,40 @@ +using HRM.BO; +using System; + +namespace HRM.UI.Realtime.Jobs +{ + /// + /// What to run in the background. Build it inside the controller action: the work runs after the request has + /// ended, so it must not touch HttpContext / CurrentUser - copy what it needs (user id, payroll type, ...) first. + /// + public class JobRequest + { + /// + /// Kind + scope, e.g. "salary-process:" + payrollTypeId. While a job with this key is queued or running, + /// starting another returns the running one instead (no double processing on a double click or a second tab). + /// + public string Key { get; set; } + + /// Shown above the progress bar, e.g. "Salary Process". + public string Title { get; set; } + + public int OwnerUserId { get; set; } + public int? PayrollTypeId { get; set; } + public JobAudience Audience { get; set; } = JobAudience.Owner; + + /// + /// The work itself. Report progress through the IJobProgress it gets; whatever it returns becomes + /// JobSnapshot.Result. An exception marks the job Failed with the exception's message (and is logged). + /// + public Func Work { get; set; } + } + + /// What IJobRunner.Start answers. + public class JobStartResult + { + public JobSnapshot Job { get; set; } + + /// True when a job with the same key was already queued/running and is returned instead of a new one. + public bool AlreadyRunning { get; set; } + } +} diff --git a/HRM.UI/Realtime/Jobs/JobRunner.cs b/HRM.UI/Realtime/Jobs/JobRunner.cs new file mode 100644 index 0000000..39fa1b7 --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobRunner.cs @@ -0,0 +1,198 @@ +using Ease.Core.Utility; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using System; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace HRM.UI.Realtime.Jobs +{ + /// + /// Runs long work off the request thread and makes its progress visible in real time. + /// + /// Usage from a controller action (copy what the work needs from CurrentUser first - there is no HttpContext later): + /// + /// JobStartResult started = _jobRunner.Start(new JobRequest { + /// Key = "salary-process:" + payrollTypeId, Title = "Salary Process", + /// OwnerUserId = userId, PayrollTypeId = payrollTypeId, Audience = JobAudience.PayrollType, + /// Work = progress => service.DoTheWork(..., progress) }); + /// return Ok(started.Job); // the browser follows it with RealtimeService.watchJob(runId) + /// + /// + public interface IJobRunner + { + JobStartResult Start(JobRequest request); + + /// A job's current state, checked against the viewer's rights. + JobAccess TryGet(string runId, int viewerUserId, int? viewerPayrollTypeId, out JobSnapshot snapshot); + + /// The job of this key that is queued or running now (null when none), checked against the viewer's rights. + JobSnapshot GetActive(string key, int viewerUserId, int? viewerPayrollTypeId); + } + + /// + /// Queues jobs and is also the hosted service that runs them: a Channel feeds a loop that starts each job on its own + /// long-running task, at most RealtimeSettings.MaxConcurrentJobs at a time. Jobs are not cut off by the end of the + /// HTTP request; an application shutdown still ends them, exactly as it would end a long synchronous request. + /// + internal sealed class JobRunner : BackgroundService, IJobRunner + { + private readonly JobStore _store = new JobStore(); + private readonly Channel _queue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + private readonly IRealtimePublisher _publisher; + private readonly RealtimeSettings _settings; + private readonly SemaphoreSlim _slots; + + public JobRunner(IRealtimePublisher publisher, IOptions settings) + { + _publisher = publisher; + _settings = settings.Value; + _slots = new SemaphoreSlim(Math.Max(1, _settings.MaxConcurrentJobs)); + } + + public JobStartResult Start(JobRequest request) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + if (request.Work == null) throw new ArgumentException("A job needs Work.", nameof(request)); + + _store.Purge(TimeSpan.FromMinutes(Math.Max(1, _settings.FinishedJobRetentionMinutes))); + + JobState state = _store.Register(request, out bool alreadyRunning); + if (!alreadyRunning) + { + lock (state.Sync) + { + state.Stage = "Waiting to start"; + } + _queue.Writer.TryWrite(state); + } + + JobSnapshot snapshot; + lock (state.Sync) + { + snapshot = state.ToSnapshot(); + } + return new JobStartResult { Job = snapshot, AlreadyRunning = alreadyRunning }; + } + + public JobAccess TryGet(string runId, int viewerUserId, int? viewerPayrollTypeId, out JobSnapshot snapshot) + { + snapshot = null; + JobState state = _store.Get(runId); + if (state == null) + return JobAccess.NotFound; + if (!JobStore.CanView(state, viewerUserId, viewerPayrollTypeId)) + return JobAccess.Forbidden; + lock (state.Sync) + { + snapshot = state.ToSnapshot(); + } + return JobAccess.Ok; + } + + public JobSnapshot GetActive(string key, int viewerUserId, int? viewerPayrollTypeId) + { + JobState state = _store.GetActive(key); + if (state == null || !JobStore.CanView(state, viewerUserId, viewerPayrollTypeId)) + return null; + lock (state.Sync) + { + return state.ToSnapshot(); + } + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await foreach (JobState state in _queue.Reader.ReadAllAsync(stoppingToken)) + { + await _slots.WaitAsync(stoppingToken); + _ = Task.Factory.StartNew(() => + { + try + { + Execute(state, stoppingToken); + } + finally + { + _slots.Release(); + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + } + } + catch (OperationCanceledException) + { + // application is stopping + } + } + + private void Execute(JobState state, CancellationToken stoppingToken) + { + JobSnapshot snapshot; + lock (state.Sync) + { + state.Status = JobStatus.Running; + state.StartedAt = DateTime.Now; + state.Stage = "Starting"; + state.Sequence++; + snapshot = state.ToSnapshot(); + } + _ = _publisher.JobChangedAsync(snapshot); + + TimeSpan throttle = TimeSpan.FromMilliseconds(Math.Max(50, _settings.ProgressThrottleMilliseconds)); + using (JobProgressReporter reporter = new JobProgressReporter(state, _publisher, throttle, stoppingToken)) + { + object result = null; + Exception failure = null; + try + { + result = state.Request.Work(reporter); + } + catch (Exception ex) + { + failure = ex; + ExceptionLog.Write(ex); + } + + reporter.Dispose(); // no late throttled message may arrive after the final one + + lock (state.Sync) + { + state.FinishedAt = DateTime.Now; + if (failure == null) + { + state.Status = JobStatus.Succeeded; + state.Percent = 100; + state.Stage = "Completed"; + state.Detail = null; + state.Result = result; + } + else + { + state.Status = JobStatus.Failed; + state.Error = UserMessage(failure); + } + state.Sequence++; + snapshot = state.ToSnapshot(); + } + } + + _store.Finished(state); + _ = _publisher.JobChangedAsync(snapshot); + } + + /// The message the user should read: services wrap the real error in ServiceException with the same text. + private static string UserMessage(Exception ex) + { + Exception e = ex; + while (e is AggregateException && e.InnerException != null) + e = e.InnerException; + return string.IsNullOrWhiteSpace(e.Message) ? "The job failed." : e.Message; + } + } +} diff --git a/HRM.UI/Realtime/Jobs/JobSnapshot.cs b/HRM.UI/Realtime/Jobs/JobSnapshot.cs new file mode 100644 index 0000000..363ed22 --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobSnapshot.cs @@ -0,0 +1,65 @@ +using System; + +namespace HRM.UI.Realtime.Jobs +{ + public enum JobStatus + { + Queued = 1, + Running = 2, + Succeeded = 3, + Failed = 4 + } + + /// Who besides the owner may watch a job. + public enum JobAudience + { + /// Only the user who started it. + Owner = 1, + + /// Every user of the same payroll type (e.g. a second admin opening the Salary Process screen). + PayrollType = 2 + } + + /// + /// A job as the browser sees it - one immutable copy per message. Sent over SignalR and returned by api/jobs, + /// always with the same shape (Angular model: src/app/_models/realtime/job-snapshot.ts). + /// + public class JobSnapshot + { + public string RunId { get; set; } + + /// The job's kind + scope, e.g. "salary-process:3". Only one job per key runs at a time. + public string Key { get; set; } + + public string Title { get; set; } + public JobStatus Status { get; set; } + + /// 0 - 100, never goes backwards. + public double Percent { get; set; } + + public string Stage { get; set; } + public string Detail { get; set; } + public int? Current { get; set; } + public int? Total { get; set; } + + public DateTime QueuedAt { get; set; } + public DateTime? StartedAt { get; set; } + public DateTime? FinishedAt { get; set; } + + public double ElapsedSeconds { get; set; } + + /// Estimated seconds left, from the speed measured so far. Null until there is enough to measure. + public double? EtaSeconds { get; set; } + + /// Grows with every change. A browser ignores a message older than the one it already shows. + public long Sequence { get; set; } + + /// What the work returned (set when Succeeded). Its shape is the job's own business. + public object Result { get; set; } + + /// Why it failed (set when Failed). + public string Error { get; set; } + + public bool IsFinished => Status == JobStatus.Succeeded || Status == JobStatus.Failed; + } +} diff --git a/HRM.UI/Realtime/Jobs/JobState.cs b/HRM.UI/Realtime/Jobs/JobState.cs new file mode 100644 index 0000000..ef39e75 --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobState.cs @@ -0,0 +1,73 @@ +using System; + +namespace HRM.UI.Realtime.Jobs +{ + /// + /// The live, mutable state of one job. Only JobRunner and JobProgressReporter change it, always under ; + /// everybody else gets an immutable copy. + /// + internal sealed class JobState + { + public readonly object Sync = new object(); + + public JobState(string runId, JobRequest request) + { + RunId = runId; + Request = request; + Status = JobStatus.Queued; + QueuedAt = DateTime.Now; + } + + public string RunId { get; } + public JobRequest Request { get; } + + public JobStatus Status; + public double Percent; + public string Stage; + public string Detail; + public int? Current; + public int? Total; + public DateTime QueuedAt; + public DateTime? StartedAt; + public DateTime? FinishedAt; + public object Result; + public string Error; + public long Sequence; + + public bool IsFinished => Status == JobStatus.Succeeded || Status == JobStatus.Failed; + + /// A consistent copy. Call it while holding . + public JobSnapshot ToSnapshot() + { + DateTime now = DateTime.Now; + double elapsed = StartedAt.HasValue ? ((FinishedAt ?? now) - StartedAt.Value).TotalSeconds : 0; + + double? eta = null; + if (Status == JobStatus.Running && Percent >= 2 && Percent < 100 && elapsed >= 3) + eta = Math.Round(elapsed * (100 - Percent) / Percent, 0); + else if (IsFinished) + eta = 0; + + return new JobSnapshot + { + RunId = RunId, + Key = Request.Key, + Title = Request.Title, + Status = Status, + Percent = Math.Round(Percent, 1), + Stage = Stage, + Detail = Detail, + Current = Current, + Total = Total, + QueuedAt = QueuedAt, + StartedAt = StartedAt, + FinishedAt = FinishedAt, + ElapsedSeconds = Math.Round(elapsed, 0), + EtaSeconds = eta, + Sequence = Sequence, + Result = Result, + Error = Error + }; + } + } +} diff --git a/HRM.UI/Realtime/Jobs/JobStore.cs b/HRM.UI/Realtime/Jobs/JobStore.cs new file mode 100644 index 0000000..685cf2d --- /dev/null +++ b/HRM.UI/Realtime/Jobs/JobStore.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace HRM.UI.Realtime.Jobs +{ + public enum JobAccess + { + Ok = 1, + NotFound = 2, + Forbidden = 3 + } + + /// + /// Every job of this process, in memory. A restart forgets them (the work itself is cut off too), which is the same + /// as a long synchronous request that dies with the process. For more than one server this would move to the database. + /// + internal sealed class JobStore + { + private readonly ConcurrentDictionary _jobs = new ConcurrentDictionary(); + private readonly Dictionary _activeByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly object _keyLock = new object(); + + /// Adds a new job, unless one with the same key is still queued or running - then that one comes back. + public JobState Register(JobRequest request, out bool alreadyRunning) + { + lock (_keyLock) + { + if (!string.IsNullOrEmpty(request.Key) + && _activeByKey.TryGetValue(request.Key, out string activeRunId) + && _jobs.TryGetValue(activeRunId, out JobState active)) + { + lock (active.Sync) + { + if (!active.IsFinished) + { + alreadyRunning = true; + return active; + } + } + } + + JobState state = new JobState(Guid.NewGuid().ToString("N"), request); + _jobs[state.RunId] = state; + if (!string.IsNullOrEmpty(request.Key)) + _activeByKey[request.Key] = state.RunId; + alreadyRunning = false; + return state; + } + } + + public JobState Get(string runId) + { + if (string.IsNullOrEmpty(runId)) + return null; + return _jobs.TryGetValue(runId, out JobState state) ? state : null; + } + + /// The job of this key that is queued or running now, or null. + public JobState GetActive(string key) + { + if (string.IsNullOrEmpty(key)) + return null; + lock (_keyLock) + { + if (!_activeByKey.TryGetValue(key, out string runId)) + return null; + JobState state = Get(runId); + if (state == null) + return null; + lock (state.Sync) + { + return state.IsFinished ? null : state; + } + } + } + + public void Finished(JobState state) + { + lock (_keyLock) + { + if (!string.IsNullOrEmpty(state.Request.Key) + && _activeByKey.TryGetValue(state.Request.Key, out string runId) + && runId == state.RunId) + { + _activeByKey.Remove(state.Request.Key); + } + } + } + + /// Drops finished jobs older than the retention, so memory does not grow for ever. + public void Purge(TimeSpan retention) + { + DateTime limit = DateTime.Now - retention; + foreach (JobState state in _jobs.Values.ToList()) + { + bool expired; + lock (state.Sync) + { + expired = state.IsFinished && state.FinishedAt.HasValue && state.FinishedAt.Value < limit; + } + if (expired) + _jobs.TryRemove(state.RunId, out _); + } + } + + /// The owner may always watch; others only when the job is shared with their payroll type. + public static bool CanView(JobState state, int userId, int? payrollTypeId) + { + JobRequest request = state.Request; + if (request.OwnerUserId == userId) + return true; + return request.Audience == JobAudience.PayrollType + && request.PayrollTypeId.HasValue + && payrollTypeId.HasValue + && request.PayrollTypeId.Value == payrollTypeId.Value; + } + } +} diff --git a/HRM.UI/Realtime/RealtimeGroups.cs b/HRM.UI/Realtime/RealtimeGroups.cs new file mode 100644 index 0000000..b1ffcd7 --- /dev/null +++ b/HRM.UI/Realtime/RealtimeGroups.cs @@ -0,0 +1,15 @@ +namespace HRM.UI.Realtime +{ + /// + /// The one place SignalR group names are built, so a publisher and the hub can never disagree on a name. + /// Clients never choose a group: the hub adds a connection to a group only after checking the caller's claims. + /// + public static class RealtimeGroups + { + /// Every connection of users working in one payroll type. + public static string PayrollType(int payrollTypeId) => "payroll-type:" + payrollTypeId; + + /// Connections following one background job. + public static string Job(string runId) => "job:" + runId; + } +} diff --git a/HRM.UI/Realtime/RealtimeSettings.cs b/HRM.UI/Realtime/RealtimeSettings.cs new file mode 100644 index 0000000..c3045ca --- /dev/null +++ b/HRM.UI/Realtime/RealtimeSettings.cs @@ -0,0 +1,26 @@ +namespace HRM.UI.Realtime +{ + /// + /// The "Realtime" section of appsettings.json. Every value has a sensible default, so the section may be left out. + /// + public class RealtimeSettings + { + /// How often the server pings an idle connection (seconds). Keep below any proxy idle timeout. + public int KeepAliveSeconds { get; set; } = 15; + + /// A client is dropped when nothing arrives from it for this long (seconds). Must be about 2 x the client's keep-alive. + public int ClientTimeoutSeconds { get; set; } = 30; + + /// Largest message a client may send to the hub (KB). Clients only send small commands. + public int MaxReceiveMessageKB { get; set; } = 64; + + /// Background jobs allowed to run at the same time; further jobs wait in the queue. + public int MaxConcurrentJobs { get; set; } = 4; + + /// A finished job's result stays readable this long (minutes), so a reload or a late tab still sees it. + public int FinishedJobRetentionMinutes { get; set; } = 60; + + /// Least time between two progress messages of one job (milliseconds). Stage changes and the end are always sent at once. + public int ProgressThrottleMilliseconds { get; set; } = 250; + } +} diff --git a/HRM.UI/Realtime/RealtimeSetup.cs b/HRM.UI/Realtime/RealtimeSetup.cs new file mode 100644 index 0000000..593fe53 --- /dev/null +++ b/HRM.UI/Realtime/RealtimeSetup.cs @@ -0,0 +1,60 @@ +using HRM.UI.Realtime.Jobs; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System; + +namespace HRM.UI.Realtime +{ + /// + /// Real-time (SignalR) and background-job wiring, kept out of Startup: + /// services.AddRealtime(...) in ConfigureServices, endpoints.MapRealtime() inside UseEndpoints. + /// + public static class RealtimeSetup + { + /// The hub's URL. It sits under /api so the Angular dev proxy and IIS treat it like every other API call. + public const string HubPath = "/api/hubs/app"; + + public static IServiceCollection AddRealtime(this IServiceCollection services, IConfiguration configuration, + IWebHostEnvironment environment) + { + IConfigurationSection section = configuration.GetSection("Realtime"); + services.Configure(section); + RealtimeSettings settings = section.Get() ?? new RealtimeSettings(); + + services.AddSignalR(options => + { + options.KeepAliveInterval = TimeSpan.FromSeconds(Math.Max(5, settings.KeepAliveSeconds)); + options.ClientTimeoutInterval = TimeSpan.FromSeconds(Math.Max(10, settings.ClientTimeoutSeconds)); + options.MaximumReceiveMessageSize = Math.Max(4, settings.MaxReceiveMessageKB) * 1024L; + options.EnableDetailedErrors = environment.IsDevelopment(); + }) + // Same JSON as the REST API (AddNewtonsoftJson), so a BO looks identical over both. + .AddNewtonsoftJsonProtocol(); + + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(provider => provider.GetRequiredService()); + services.AddHostedService(provider => provider.GetRequiredService()); + + return services; + } + + public static IEndpointRouteBuilder MapRealtime(this IEndpointRouteBuilder endpoints) + { + endpoints.MapHub(HubPath, options => + { + // Close the connection when the JWT it was opened with expires; the browser reconnects with the + // current cookie, or stops if the user is signed out. + options.CloseOnAuthenticationExpiration = true; + }); + return endpoints; + } + } +} diff --git a/HRM.UI/Realtime/UserIdClaimProvider.cs b/HRM.UI/Realtime/UserIdClaimProvider.cs new file mode 100644 index 0000000..313c253 --- /dev/null +++ b/HRM.UI/Realtime/UserIdClaimProvider.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.SignalR; + +namespace HRM.UI.Realtime +{ + /// + /// Ties a connection to the app's own user id (the "UserID" claim of the JWT), so + /// IRealtimePublisher.ToUserAsync reaches every tab that user has open. + /// + public class UserIdClaimProvider : IUserIdProvider + { + public string GetUserId(HubConnectionContext connection) + { + return connection.User?.FindFirst("UserID")?.Value; + } + } +} diff --git a/HRM.UI/Startup.cs b/HRM.UI/Startup.cs index 51c9c3b..2dec61e 100644 --- a/HRM.UI/Startup.cs +++ b/HRM.UI/Startup.cs @@ -3,6 +3,7 @@ using HRM.BO; using HRM.BO.Configuration; using HRM.DA; using HRM.UI.BackgroundJobs.Calendar; +using HRM.UI.Realtime; using HRM.UI.Configuration.DI; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -315,6 +316,11 @@ namespace HRM.UI.Api #endregion + #region Realtime (SignalR) + background jobs + // One hub for the whole app + a job runner with live progress. See HRM.UI/Realtime. + services.AddRealtime(Configuration, HostingEnvironment); + #endregion + _logger.LogDebug("Startup::ConfigureServices::ApiVersioning, Swagger and DI settings"); } else @@ -367,6 +373,8 @@ namespace HRM.UI.Api endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); + // SignalR hub - must stay before UseSpa, or the SPA fallback answers /api/hubs/app. + endpoints.MapRealtime(); }); app.UseSpa(spa => {