74 lines
2.9 KiB
PHP
74 lines
2.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Machines\Domain\Services;
|
|
|
|
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
|
|
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
|
use App\Modules\Machines\Domain\ValueObjects\MaintenanceState;
|
|
use DateTimeImmutable;
|
|
|
|
/**
|
|
* Works out a maintenance item's state from what has accumulated since its
|
|
* last maintenance (spec 19.5). The counter interval counts the counter's
|
|
* latest reading minus its reading at the last maintenance; the time
|
|
* interval counts calendar periods from the day of the last maintenance.
|
|
* With both, maintenance is due when either is. The advance warning
|
|
* applies to both, but not to daily maintenance.
|
|
*/
|
|
final class MaintenanceStatus
|
|
{
|
|
/**
|
|
* @param int|null $intervalMilli The counter interval, null when none.
|
|
* @param int $baselineMilli The counter's reading at the last maintenance (or when the item was added).
|
|
* @param int|null $readingMilli The counter's latest reading.
|
|
* @param DateTimeImmutable $since The day of the last maintenance (or when the item was added).
|
|
*/
|
|
public static function evaluate(
|
|
?int $intervalMilli,
|
|
int $baselineMilli,
|
|
?int $readingMilli,
|
|
?MaintenancePeriod $period,
|
|
int $periodCount,
|
|
DateTimeImmutable $since,
|
|
int $warningPercent,
|
|
DateTimeImmutable $today,
|
|
): MaintenanceState {
|
|
$level = MaintenanceLevel::Ok;
|
|
$remaining = null;
|
|
$dueOn = null;
|
|
|
|
if ($intervalMilli !== null) {
|
|
$used = max(0, ($readingMilli ?? $baselineMilli) - $baselineMilli);
|
|
$remaining = $intervalMilli - $used;
|
|
$level = self::worse($level, match (true) {
|
|
$used >= $intervalMilli => MaintenanceLevel::Overdue,
|
|
$used * 100 >= $intervalMilli * $warningPercent => MaintenanceLevel::Approaching,
|
|
default => MaintenanceLevel::Ok,
|
|
});
|
|
}
|
|
|
|
if ($period !== null) {
|
|
$due = $period->next($since, $periodCount);
|
|
$dueOn = $due->format('Y-m-d');
|
|
$elapsed = $since->setTime(0, 0) <= $today ? (int) $since->setTime(0, 0)->diff($today->setTime(0, 0))->days : 0;
|
|
$length = max(1, $period->days($since, $periodCount));
|
|
$warns = ! ($period === MaintenancePeriod::Day && $periodCount === 1);
|
|
|
|
$level = self::worse($level, match (true) {
|
|
$today->format('Y-m-d') >= $dueOn => MaintenanceLevel::Overdue,
|
|
$warns && $elapsed * 100 >= $length * $warningPercent => MaintenanceLevel::Approaching,
|
|
default => MaintenanceLevel::Ok,
|
|
});
|
|
}
|
|
|
|
return new MaintenanceState($level, $remaining, $dueOn);
|
|
}
|
|
|
|
private static function worse(MaintenanceLevel $a, MaintenanceLevel $b): MaintenanceLevel
|
|
{
|
|
return $b->rank() > $a->rank() ? $b : $a;
|
|
}
|
|
}
|