HRM-10/HRM.DA/Service/Salary/SalaryProcessProgress.cs
2026-11-30 13:35:21 +06:00

276 lines
12 KiB
C#

using HRM.BO;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace HRM.DA
{
/// <summary>
/// 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.
/// </summary>
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<int, LearnedRun> LearnedRuns = new ConcurrentDictionary<int, LearnedRun>();
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"));
}
/// <summary>From here until the first calculation phase starts: calculator set-up, approval check, Initialize.</summary>
public void Preparing()
{
Safe(() => Enter(StagePreparing, "Preparing calculation"));
}
public void Attach(SalaryCalculator calculator)
{
calculator.ProgressStatus += OnProgressStatus;
calculator.ProcessStatus += OnProcessStatus;
}
/// <summary>The save reports its own 0 - 100 through this; it lands in the Saving slice of the bar.</summary>
public IJobProgress Saving()
{
Safe(() => Enter(StageSaving, "Saving salary data"));
return new JobProgressScope(_progress, _stageStart[StageSaving], _stageStart[StageSaving] + _stageShare[StageSaving]);
}
/// <summary>The run finished successfully: remember how long each stage took, for the next run's proportions.</summary>
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
}
}
}
}