Track machine counters and maintenance with counter and time intervals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\Contracts;
|
||||
|
||||
/**
|
||||
* Records the stock used at a maintenance through the Inventory module.
|
||||
*/
|
||||
interface MaintenanceMaterials
|
||||
{
|
||||
/**
|
||||
* @return bool False when the stock could not be recorded (e.g. the item is out of use).
|
||||
*/
|
||||
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\Contracts;
|
||||
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceRecordSummary;
|
||||
|
||||
interface MaintenanceQueries
|
||||
{
|
||||
/**
|
||||
* A machine's maintenance items with their states, late ones first.
|
||||
*
|
||||
* @return list<MaintenanceItemStatus>
|
||||
*/
|
||||
public function itemsOf(int $machineId, bool $includeInactive = false): array;
|
||||
|
||||
public function findItem(int $itemId): ?MaintenanceItemStatus;
|
||||
|
||||
/**
|
||||
* Items in use of machines in use whose maintenance is coming up or
|
||||
* late: the maintenance requests.
|
||||
*
|
||||
* @return list<MaintenanceItemStatus>
|
||||
*/
|
||||
public function due(): array;
|
||||
|
||||
/**
|
||||
* A machine's maintenance history, newest first, filtered by item and
|
||||
* by days (Y-m-d, both inclusive).
|
||||
*
|
||||
* @return list<MaintenanceRecordSummary>
|
||||
*/
|
||||
public function history(int $machineId, ?int $itemId = null, ?string $from = null, ?string $to = null, int $limit = 200): array;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A maintenance item as entered: the counter interval as typed with its
|
||||
* counter, the time interval as a period key (day, week, month, year) and
|
||||
* count, the advance warning in percent, and an optional stock item used
|
||||
* up at each maintenance with its quantity as typed.
|
||||
*/
|
||||
final readonly class MaintenanceItemData
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public ?int $counterId = null,
|
||||
public string $interval = '',
|
||||
public ?string $period = null,
|
||||
public int $periodCount = 1,
|
||||
public int $warningPercent = 90,
|
||||
public ?string $instructions = null,
|
||||
public ?int $stockItemId = null,
|
||||
public string $stockQuantity = '',
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\DTOs;
|
||||
|
||||
use App\Modules\Machines\Domain\Enums\CounterUnit;
|
||||
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
|
||||
/**
|
||||
* A maintenance item with its state now. Counter amounts are in thousandths
|
||||
* of the counter's unit; $remainingMilli is negative when past. Days are
|
||||
* Y-m-d; $lastPerformedAt is "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class MaintenanceItemStatus
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public int $machineId,
|
||||
public string $machineName,
|
||||
public ?int $responsibleUserId,
|
||||
public string $name,
|
||||
public ?int $counterId,
|
||||
public ?string $counterName,
|
||||
public ?CounterUnit $counterUnit,
|
||||
public ?int $intervalMilli,
|
||||
public ?MaintenancePeriod $period,
|
||||
public int $periodCount,
|
||||
public int $warningPercent,
|
||||
public ?string $instructions,
|
||||
public ?int $stockItemId,
|
||||
public ?int $stockQuantityMilli,
|
||||
public bool $isActive,
|
||||
public MaintenanceLevel $level,
|
||||
public ?int $remainingMilli,
|
||||
public ?string $dueOn,
|
||||
public ?int $readingMilli,
|
||||
public ?int $lastRecordId,
|
||||
public ?string $lastPerformedAt,
|
||||
public ?string $lastPerformedByName,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A maintenance done, as in a machine's maintenance history. Times are
|
||||
* "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class MaintenanceRecordSummary
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public int $itemId,
|
||||
public string $itemName,
|
||||
public string $performedAt,
|
||||
public string $userName,
|
||||
public ?int $readingMilli,
|
||||
public ?string $note,
|
||||
public ?string $cancelledAt,
|
||||
public ?string $cancelledByName,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Application\UseCases;
|
||||
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemData;
|
||||
use App\Modules\Machines\Domain\Contracts\MachineRepository;
|
||||
use App\Modules\Machines\Domain\Contracts\MaintenanceRepository;
|
||||
use App\Modules\Machines\Domain\Entities\MaintenanceItem;
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
use App\Modules\Machines\Domain\Exceptions\CounterNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidMaintenanceItem;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
|
||||
use App\Modules\Machines\Domain\Exceptions\MachineNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNeedsInterval;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceRecordCancelled;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceRecordNotFound;
|
||||
use App\Modules\Machines\Domain\ValueObjects\Reading;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Machine maintenance (spec 19.5): maintenance items are kept by
|
||||
* management; counter readings and maintenance done are recorded by
|
||||
* anyone using the machine. A maintenance record starts the item's
|
||||
* intervals again and uses up its stock item; a mistaken record is
|
||||
* cancelled by management, never deleted.
|
||||
*/
|
||||
final class MachineMaintenance
|
||||
{
|
||||
public function __construct(
|
||||
private MachineRepository $machines,
|
||||
private MaintenanceRepository $maintenance,
|
||||
private MaintenanceMaterials $materials,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The item's id.
|
||||
*
|
||||
* @throws MachineNotFound
|
||||
* @throws MaintenanceItemNotFound
|
||||
* @throws CounterNotFound
|
||||
* @throws InvalidReading
|
||||
* @throws InvalidMaintenanceItem
|
||||
* @throws MaintenanceItemNeedsInterval
|
||||
*/
|
||||
public function saveItem(int $machineId, ?int $itemId, MaintenanceItemData $data): int
|
||||
{
|
||||
$interval = Reading::parse($data->interval);
|
||||
$quantity = $data->stockItemId === null ? null : Reading::parse($data->stockQuantity);
|
||||
$period = $data->period === null || $data->period === '' ? null : (MaintenancePeriod::tryFrom($data->period) ?? throw new InvalidMaintenanceItem);
|
||||
|
||||
return $this->transactions->run(function () use ($machineId, $itemId, $data, $interval, $quantity, $period): int {
|
||||
$this->machines->findById($machineId) ?? throw new MachineNotFound;
|
||||
|
||||
if ($data->counterId !== null && $this->maintenance->machineOfCounter($data->counterId) !== $machineId) {
|
||||
throw new CounterNotFound;
|
||||
}
|
||||
|
||||
$counterReading = $data->counterId === null ? 0 : ($this->maintenance->latestReading($data->counterId) ?? 0);
|
||||
|
||||
if ($itemId === null) {
|
||||
$item = MaintenanceItem::create($machineId, $data->name, $data->counterId, $interval, $counterReading, $period, $data->periodCount, $this->clock->today(), $data->warningPercent, $data->instructions, $data->stockItemId, $quantity);
|
||||
} else {
|
||||
$item = $this->maintenance->findItem($itemId);
|
||||
|
||||
if ($item === null || $item->machineId() !== $machineId) {
|
||||
throw new MaintenanceItemNotFound;
|
||||
}
|
||||
|
||||
$counterChanged = $item->counterId() !== $data->counterId;
|
||||
$item->change($data->name, $data->counterId, $interval, $period, $data->periodCount, $data->warningPercent, $data->instructions, $data->stockItemId, $quantity);
|
||||
|
||||
if ($counterChanged) {
|
||||
$item->rebaseCounter($counterReading);
|
||||
}
|
||||
}
|
||||
|
||||
return (int) $this->maintenance->saveItem($item)->id();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws MaintenanceItemNotFound
|
||||
*/
|
||||
public function setItemActive(int $itemId, bool $active): void
|
||||
{
|
||||
$this->transactions->run(function () use ($itemId, $active): void {
|
||||
$item = $this->maintenance->findItem($itemId) ?? throw new MaintenanceItemNotFound;
|
||||
$active ? $item->activate() : $item->deactivate();
|
||||
$this->maintenance->saveItem($item);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a counter's reading, e.g. the machine's own total counter.
|
||||
*
|
||||
* @throws CounterNotFound
|
||||
* @throws InvalidReading
|
||||
*/
|
||||
public function recordReading(int $counterId, string $reading, int $actorUserId): int
|
||||
{
|
||||
$milli = Reading::parse($reading) ?? throw new InvalidReading;
|
||||
|
||||
$this->transactions->run(function () use ($counterId, $milli, $actorUserId): void {
|
||||
$this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound;
|
||||
$this->maintenance->addReading($counterId, $milli, $actorUserId, $this->clock->now());
|
||||
});
|
||||
|
||||
return $milli;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records maintenance done (Huolto tehty) with the counter's reading
|
||||
* (the latest one when not given) and uses up the item's stock item.
|
||||
*
|
||||
* @return array{recordId: int, stockRecorded: bool}
|
||||
*
|
||||
* @throws MaintenanceItemNotFound
|
||||
* @throws InvalidReading
|
||||
*/
|
||||
public function recordMaintenance(int $itemId, int $actorUserId, string $reading = '', ?string $note = null): array
|
||||
{
|
||||
$readingMilli = Reading::parse($reading);
|
||||
$note = $note === null ? '' : trim($note);
|
||||
|
||||
return $this->transactions->run(function () use ($itemId, $actorUserId, $readingMilli, $note): array {
|
||||
$item = $this->maintenance->findItem($itemId) ?? throw new MaintenanceItemNotFound;
|
||||
$now = $this->clock->now();
|
||||
|
||||
if ($item->counterId() !== null) {
|
||||
if ($readingMilli !== null) {
|
||||
$this->maintenance->addReading($item->counterId(), $readingMilli, $actorUserId, $now);
|
||||
} else {
|
||||
$readingMilli = $this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli();
|
||||
}
|
||||
}
|
||||
|
||||
$recordId = $this->maintenance->addRecord($itemId, $now, $actorUserId, $item->counterId() === null ? null : $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000));
|
||||
|
||||
$stockRecorded = $item->stockItemId() === null
|
||||
|| $this->materials->use($item->stockItemId(), (int) $item->stockQuantityMilli(), $item->machineId(), $recordId, $actorUserId);
|
||||
|
||||
return ['recordId' => $recordId, 'stockRecorded' => $stockRecorded];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws MaintenanceRecordNotFound
|
||||
* @throws MaintenanceRecordCancelled
|
||||
*/
|
||||
public function cancelRecord(int $recordId, int $actorUserId): void
|
||||
{
|
||||
$this->transactions->run(function () use ($recordId, $actorUserId): void {
|
||||
$record = $this->maintenance->findRecord($recordId) ?? throw new MaintenanceRecordNotFound;
|
||||
|
||||
if ($record['cancelled']) {
|
||||
throw new MaintenanceRecordCancelled;
|
||||
}
|
||||
|
||||
$this->maintenance->cancelRecord($recordId, $actorUserId, $this->clock->now());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Contracts;
|
||||
|
||||
use App\Modules\Machines\Domain\Entities\MaintenanceItem;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Maintenance items, maintenance records and counter readings.
|
||||
*/
|
||||
interface MaintenanceRepository
|
||||
{
|
||||
public function findItem(int $id): ?MaintenanceItem;
|
||||
|
||||
public function saveItem(MaintenanceItem $item): MaintenanceItem;
|
||||
|
||||
/**
|
||||
* The machine a counter belongs to, or null when there is no such counter.
|
||||
*/
|
||||
public function machineOfCounter(int $counterId): ?int;
|
||||
|
||||
public function latestReading(int $counterId): ?int;
|
||||
|
||||
public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void;
|
||||
|
||||
/**
|
||||
* @return int The record's id.
|
||||
*/
|
||||
public function addRecord(int $itemId, DateTimeImmutable $performedAt, int $userId, ?int $readingMilli, ?string $note): int;
|
||||
|
||||
/**
|
||||
* @return array{id: int, itemId: int, cancelled: bool}|null
|
||||
*/
|
||||
public function findRecord(int $id): ?array;
|
||||
|
||||
public function cancelRecord(int $id, int $userId, DateTimeImmutable $at): void;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Entities;
|
||||
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidMaintenanceItem;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNeedsInterval;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A maintenance item of a machine (huoltokohde, spec 19.5), e.g. emptying
|
||||
* the waste ink tank or changing the blade. It is due by a counter
|
||||
* interval (e.g. every 20 000 prints), a time interval (daily, weekly,
|
||||
* monthly or yearly maintenance, every N periods) or whichever comes
|
||||
* first; using a time interval is optional. A stock item, e.g. a spare
|
||||
* drum, may be used up at each maintenance. Items are taken out of use,
|
||||
* not deleted.
|
||||
*/
|
||||
final class MaintenanceItem
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private int $machineId,
|
||||
private string $name,
|
||||
private ?int $counterId,
|
||||
private ?int $intervalMilli,
|
||||
private int $baselineMilli,
|
||||
private ?MaintenancePeriod $period,
|
||||
private int $periodCount,
|
||||
private DateTimeImmutable $startsOn,
|
||||
private int $warningPercent,
|
||||
private ?string $instructions,
|
||||
private ?int $stockItemId,
|
||||
private ?int $stockQuantityMilli,
|
||||
private bool $active,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidMaintenanceItem
|
||||
* @throws MaintenanceItemNeedsInterval
|
||||
*/
|
||||
public static function create(
|
||||
int $machineId,
|
||||
string $name,
|
||||
?int $counterId,
|
||||
?int $intervalMilli,
|
||||
int $baselineMilli,
|
||||
?MaintenancePeriod $period,
|
||||
int $periodCount,
|
||||
DateTimeImmutable $startsOn,
|
||||
int $warningPercent,
|
||||
?string $instructions,
|
||||
?int $stockItemId,
|
||||
?int $stockQuantityMilli,
|
||||
): self {
|
||||
$item = new self(null, $machineId, '', null, null, $baselineMilli, null, 1, $startsOn, 90, null, null, null, true);
|
||||
$item->change($name, $counterId, $intervalMilli, $period, $periodCount, $warningPercent, $instructions, $stockItemId, $stockQuantityMilli);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
public static function reconstitute(
|
||||
int $id,
|
||||
int $machineId,
|
||||
string $name,
|
||||
?int $counterId,
|
||||
?int $intervalMilli,
|
||||
int $baselineMilli,
|
||||
?MaintenancePeriod $period,
|
||||
int $periodCount,
|
||||
DateTimeImmutable $startsOn,
|
||||
int $warningPercent,
|
||||
?string $instructions,
|
||||
?int $stockItemId,
|
||||
?int $stockQuantityMilli,
|
||||
bool $active,
|
||||
): self {
|
||||
return new self($id, $machineId, $name, $counterId, $intervalMilli, $baselineMilli, $period, $periodCount, $startsOn, $warningPercent, $instructions, $stockItemId, $stockQuantityMilli, $active);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidMaintenanceItem
|
||||
* @throws MaintenanceItemNeedsInterval
|
||||
*/
|
||||
public function change(
|
||||
string $name,
|
||||
?int $counterId,
|
||||
?int $intervalMilli,
|
||||
?MaintenancePeriod $period,
|
||||
int $periodCount,
|
||||
int $warningPercent,
|
||||
?string $instructions,
|
||||
?int $stockItemId,
|
||||
?int $stockQuantityMilli,
|
||||
): void {
|
||||
$name = trim(preg_replace('/\s+/u', ' ', $name) ?? $name);
|
||||
$hasCounterInterval = $counterId !== null && $intervalMilli !== null;
|
||||
|
||||
if ($name === '' || mb_strlen($name) > 150
|
||||
|| ($intervalMilli !== null && $intervalMilli < 1)
|
||||
|| $periodCount < 1 || $periodCount > 365
|
||||
|| $warningPercent < 1 || $warningPercent > 99
|
||||
|| ($stockItemId !== null && ($stockQuantityMilli === null || $stockQuantityMilli < 1))) {
|
||||
throw new InvalidMaintenanceItem;
|
||||
}
|
||||
|
||||
if (! $hasCounterInterval && $period === null) {
|
||||
throw new MaintenanceItemNeedsInterval;
|
||||
}
|
||||
|
||||
$instructions = $instructions === null ? '' : trim($instructions);
|
||||
|
||||
$this->name = $name;
|
||||
$this->counterId = $hasCounterInterval ? $counterId : null;
|
||||
$this->intervalMilli = $hasCounterInterval ? $intervalMilli : null;
|
||||
$this->period = $period;
|
||||
$this->periodCount = $periodCount;
|
||||
$this->warningPercent = $warningPercent;
|
||||
$this->instructions = $instructions === '' ? null : $instructions;
|
||||
$this->stockItemId = $stockItemId;
|
||||
$this->stockQuantityMilli = $stockItemId === null ? null : $stockQuantityMilli;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the counter changes, the amount counts from its latest reading.
|
||||
*/
|
||||
public function rebaseCounter(int $readingMilli): void
|
||||
{
|
||||
$this->baselineMilli = $readingMilli;
|
||||
}
|
||||
|
||||
public function activate(): void
|
||||
{
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
public function deactivate(): void
|
||||
{
|
||||
$this->active = false;
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function machineId(): int
|
||||
{
|
||||
return $this->machineId;
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function counterId(): ?int
|
||||
{
|
||||
return $this->counterId;
|
||||
}
|
||||
|
||||
public function intervalMilli(): ?int
|
||||
{
|
||||
return $this->intervalMilli;
|
||||
}
|
||||
|
||||
public function baselineMilli(): int
|
||||
{
|
||||
return $this->baselineMilli;
|
||||
}
|
||||
|
||||
public function period(): ?MaintenancePeriod
|
||||
{
|
||||
return $this->period;
|
||||
}
|
||||
|
||||
public function periodCount(): int
|
||||
{
|
||||
return $this->periodCount;
|
||||
}
|
||||
|
||||
public function startsOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->startsOn;
|
||||
}
|
||||
|
||||
public function warningPercent(): int
|
||||
{
|
||||
return $this->warningPercent;
|
||||
}
|
||||
|
||||
public function instructions(): ?string
|
||||
{
|
||||
return $this->instructions;
|
||||
}
|
||||
|
||||
public function stockItemId(): ?int
|
||||
{
|
||||
return $this->stockItemId;
|
||||
}
|
||||
|
||||
public function stockQuantityMilli(): ?int
|
||||
{
|
||||
return $this->stockQuantityMilli;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->active;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Enums;
|
||||
|
||||
/**
|
||||
* The state of a maintenance item (spec 19.5): in order, maintenance
|
||||
* coming up (past the advance warning), or late (a maintenance request).
|
||||
*/
|
||||
enum MaintenanceLevel: string
|
||||
{
|
||||
case Ok = 'ok';
|
||||
case Approaching = 'approaching';
|
||||
case Overdue = 'overdue';
|
||||
|
||||
public function rank(): int
|
||||
{
|
||||
return match ($this) {
|
||||
self::Ok => 0,
|
||||
self::Approaching => 1,
|
||||
self::Overdue => 2,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Enums;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A time-based maintenance interval (spec 19.5): daily, weekly, monthly or
|
||||
* yearly maintenance, possibly every N periods. Several items of a machine
|
||||
* can have different periods at the same time.
|
||||
*/
|
||||
enum MaintenancePeriod: string
|
||||
{
|
||||
case Day = 'day';
|
||||
case Week = 'week';
|
||||
case Month = 'month';
|
||||
case Year = 'year';
|
||||
|
||||
/**
|
||||
* The day the next maintenance is due after the given day. A month or
|
||||
* year from the 31st (or 29 February) ends on the last day of the month.
|
||||
*/
|
||||
public function next(DateTimeImmutable $from, int $count): DateTimeImmutable
|
||||
{
|
||||
$from = $from->setTime(0, 0);
|
||||
|
||||
return match ($this) {
|
||||
self::Day => $from->modify("+{$count} days"),
|
||||
self::Week => $from->modify('+'.(7 * $count).' days'),
|
||||
self::Month => self::addMonths($from, $count),
|
||||
self::Year => self::addMonths($from, 12 * $count),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The interval's length in days from the day, for the advance warning.
|
||||
*/
|
||||
public function days(DateTimeImmutable $from, int $count): int
|
||||
{
|
||||
return (int) $from->setTime(0, 0)->diff($this->next($from, $count))->days;
|
||||
}
|
||||
|
||||
private static function addMonths(DateTimeImmutable $from, int $months): DateTimeImmutable
|
||||
{
|
||||
$first = $from->modify('first day of this month')->modify("+{$months} months");
|
||||
$day = min((int) $from->format('j'), (int) $first->format('t'));
|
||||
|
||||
return $first->setDate((int) $first->format('Y'), (int) $first->format('n'), $day);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CounterNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The counter was not found.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidMaintenanceItem extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A maintenance item needs a name of 1-150 characters, positive intervals and a warning of 1-99 percent.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidReading extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A reading must be a number of zero or more with at most three decimals.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class MaintenanceItemNeedsInterval extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A maintenance item needs a counter interval, a time interval or both.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class MaintenanceItemNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The maintenance item was not found.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class MaintenanceRecordCancelled extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The maintenance record has already been cancelled.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class MaintenanceRecordNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The maintenance record was not found.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
|
||||
|
||||
/**
|
||||
* How a maintenance item stands now: its level (the worse of its counter
|
||||
* and time intervals), the counter amount left (in thousandths, negative
|
||||
* when past) and the day the time interval is due (Y-m-d).
|
||||
*/
|
||||
final readonly class MaintenanceState
|
||||
{
|
||||
public function __construct(
|
||||
public MaintenanceLevel $level,
|
||||
public ?int $remainingMilli,
|
||||
public ?string $dueOn,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Machines\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
|
||||
|
||||
/**
|
||||
* A counter reading or a counter amount in thousandths of the counter's
|
||||
* unit, typed as "20000", "20 000" or "12,5".
|
||||
*/
|
||||
final class Reading
|
||||
{
|
||||
/**
|
||||
* @return int|null Null for an empty value.
|
||||
*
|
||||
* @throws InvalidReading
|
||||
*/
|
||||
public static function parse(string $value): ?int
|
||||
{
|
||||
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? '');
|
||||
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{1,12})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) {
|
||||
throw new InvalidReading;
|
||||
}
|
||||
|
||||
return (int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Adapters;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseData;
|
||||
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
/**
|
||||
* Records stock used at machine maintenance through the Inventory module.
|
||||
* A failure (e.g. the item is out of use) does not undo the maintenance.
|
||||
*/
|
||||
class StockForMachines implements MaintenanceMaterials
|
||||
{
|
||||
public function __construct(private RecordStockUse $recordUse) {}
|
||||
|
||||
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool
|
||||
{
|
||||
try {
|
||||
$this->recordUse->execute(new StockUseData(
|
||||
$stockItemId,
|
||||
StockQuantity::inputValue($quantityMilli),
|
||||
machineId: $machineId,
|
||||
maintenanceRecordId: $maintenanceRecordId,
|
||||
), $userId);
|
||||
} catch (DomainException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Machines Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $machine_id
|
||||
* @property string $name
|
||||
* @property int|null $machine_counter_id
|
||||
* @property int|null $interval_milli
|
||||
* @property int $counter_baseline_milli
|
||||
* @property MaintenancePeriod|null $period
|
||||
* @property int $period_count
|
||||
* @property string $starts_on Y-m-d
|
||||
* @property int $warning_percent
|
||||
* @property string|null $instructions
|
||||
* @property int|null $stock_item_id
|
||||
* @property int|null $stock_quantity_milli
|
||||
* @property bool $is_active
|
||||
*/
|
||||
#[Table('maintenance_items')]
|
||||
#[Fillable([
|
||||
'machine_id', 'name', 'machine_counter_id', 'interval_milli', 'counter_baseline_milli', 'period', 'period_count',
|
||||
'starts_on', 'warning_percent', 'instructions', 'stock_item_id', 'stock_quantity_milli', 'is_active',
|
||||
])]
|
||||
class MaintenanceItemModel extends Model
|
||||
{
|
||||
/**
|
||||
* The latest maintenance that was not cancelled.
|
||||
*
|
||||
* @return HasOne<MaintenanceRecordModel, $this>
|
||||
*/
|
||||
public function lastRecord(): HasOne
|
||||
{
|
||||
return $this->hasOne(MaintenanceRecordModel::class, 'maintenance_item_id')
|
||||
->ofMany(['performed_at' => 'max', 'id' => 'max'], fn ($query) => $query->whereNull('cancelled_at'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'machine_id' => 'integer',
|
||||
'machine_counter_id' => 'integer',
|
||||
'interval_milli' => 'integer',
|
||||
'counter_baseline_milli' => 'integer',
|
||||
'period' => MaintenancePeriod::class,
|
||||
'period_count' => 'integer',
|
||||
'warning_percent' => 'integer',
|
||||
'stock_item_id' => 'integer',
|
||||
'stock_quantity_milli' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Machines Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $maintenance_item_id
|
||||
* @property Carbon $performed_at
|
||||
* @property int $user_id
|
||||
* @property int|null $counter_reading_milli
|
||||
* @property string|null $note
|
||||
* @property Carbon|null $cancelled_at
|
||||
* @property int|null $cancelled_by
|
||||
*/
|
||||
#[Table('maintenance_records')]
|
||||
#[Fillable(['maintenance_item_id', 'performed_at', 'user_id', 'counter_reading_milli', 'note', 'cancelled_at', 'cancelled_by'])]
|
||||
class MaintenanceRecordModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'maintenance_item_id' => 'integer',
|
||||
'performed_at' => 'immutable_datetime',
|
||||
'user_id' => 'integer',
|
||||
'counter_reading_milli' => 'integer',
|
||||
'cancelled_at' => 'immutable_datetime',
|
||||
'cancelled_by' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceRecordSummary;
|
||||
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
|
||||
use App\Modules\Machines\Domain\Services\MaintenanceStatus;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceRecordModel;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EloquentMaintenanceQueries implements MaintenanceQueries
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountQueries $users,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
public function itemsOf(int $machineId, bool $includeInactive = false): array
|
||||
{
|
||||
$models = MaintenanceItemModel::query()
|
||||
->with('lastRecord')
|
||||
->where('machine_id', $machineId)
|
||||
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return $this->sorted($this->statuses($models));
|
||||
}
|
||||
|
||||
public function findItem(int $itemId): ?MaintenanceItemStatus
|
||||
{
|
||||
$model = MaintenanceItemModel::query()->with('lastRecord')->find($itemId);
|
||||
|
||||
return $model === null ? null : $this->statuses(collect([$model]))[0];
|
||||
}
|
||||
|
||||
public function due(): array
|
||||
{
|
||||
$models = MaintenanceItemModel::query()
|
||||
->with('lastRecord')
|
||||
->where('is_active', true)
|
||||
->whereIn('machine_id', MachineModel::query()->select('id')->where('is_active', true))
|
||||
->get();
|
||||
|
||||
return $this->sorted(array_values(array_filter(
|
||||
$this->statuses($models),
|
||||
fn (MaintenanceItemStatus $item): bool => $item->level !== MaintenanceLevel::Ok,
|
||||
)));
|
||||
}
|
||||
|
||||
public function history(int $machineId, ?int $itemId = null, ?string $from = null, ?string $to = null, int $limit = 200): array
|
||||
{
|
||||
$timezone = (string) config('app.business_timezone');
|
||||
$models = MaintenanceRecordModel::query()
|
||||
->join('maintenance_items', 'maintenance_items.id', '=', 'maintenance_records.maintenance_item_id')
|
||||
->where('maintenance_items.machine_id', $machineId)
|
||||
->when($itemId !== null, fn (Builder $query) => $query->where('maintenance_records.maintenance_item_id', $itemId))
|
||||
->when($from !== null, fn (Builder $query) => $query->where('maintenance_records.performed_at', '>=', Carbon::parse((string) $from, $timezone)->startOfDay()->utc()))
|
||||
->when($to !== null, fn (Builder $query) => $query->where('maintenance_records.performed_at', '<=', Carbon::parse((string) $to, $timezone)->endOfDay()->utc()))
|
||||
->orderByDesc('maintenance_records.performed_at')
|
||||
->orderByDesc('maintenance_records.id')
|
||||
->limit($limit)
|
||||
->get(['maintenance_records.*', 'maintenance_items.name as item_name']);
|
||||
|
||||
$names = $this->users->namesByIds($models->flatMap(fn (MaintenanceRecordModel $model): array => array_filter([$model->user_id, $model->cancelled_by]))->unique()->values()->all());
|
||||
|
||||
return $models->map(fn (MaintenanceRecordModel $model): MaintenanceRecordSummary => new MaintenanceRecordSummary(
|
||||
id: $model->id,
|
||||
itemId: $model->maintenance_item_id,
|
||||
itemName: (string) $model->getAttribute('item_name'),
|
||||
performedAt: $this->localTime($model->performed_at),
|
||||
userName: $names[$model->user_id] ?? '',
|
||||
readingMilli: $model->counter_reading_milli,
|
||||
note: $model->note,
|
||||
cancelledAt: $model->cancelled_at === null ? null : $this->localTime($model->cancelled_at),
|
||||
cancelledByName: $model->cancelled_by === null ? null : ($names[$model->cancelled_by] ?? ''),
|
||||
))->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, MaintenanceItemModel> $models
|
||||
* @return list<MaintenanceItemStatus>
|
||||
*/
|
||||
private function statuses(Collection $models): array
|
||||
{
|
||||
if ($models->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$today = $this->clock->today();
|
||||
$machines = MachineModel::query()->whereIn('id', $models->pluck('machine_id')->unique())->get(['id', 'name', 'responsible_user_id'])->keyBy('id');
|
||||
$counterIds = $models->pluck('machine_counter_id')->filter()->unique()->values();
|
||||
$counters = MachineCounterModel::query()->whereIn('id', $counterIds)->get()->keyBy('id');
|
||||
$readings = MachineCounterReadingModel::query()
|
||||
->whereIn('machine_counter_id', $counterIds)
|
||||
->orderBy('read_at')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->groupBy('machine_counter_id')
|
||||
->map(fn (Collection $rows): int => (int) $rows->last()?->reading_milli);
|
||||
$names = $this->users->namesByIds($models->map(fn (MaintenanceItemModel $model): ?int => $model->lastRecord?->user_id)->filter()->unique()->values()->all());
|
||||
|
||||
return $models->map(function (MaintenanceItemModel $model) use ($today, $machines, $counters, $readings, $names): MaintenanceItemStatus {
|
||||
$last = $model->lastRecord;
|
||||
$counter = $model->machine_counter_id === null ? null : $counters->get($model->machine_counter_id);
|
||||
$reading = $model->machine_counter_id === null ? null : $readings->get($model->machine_counter_id);
|
||||
$baseline = $last->counter_reading_milli ?? $model->counter_baseline_milli;
|
||||
$since = $last === null
|
||||
? new DateTimeImmutable(substr($model->starts_on, 0, 10))
|
||||
: new DateTimeImmutable(Carbon::instance($last->performed_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d'));
|
||||
|
||||
$state = MaintenanceStatus::evaluate($model->interval_milli, $baseline, $reading, $model->period, $model->period_count, $since, $model->warning_percent, $today);
|
||||
$machine = $machines->get($model->machine_id);
|
||||
|
||||
return new MaintenanceItemStatus(
|
||||
id: $model->id,
|
||||
machineId: $model->machine_id,
|
||||
machineName: (string) $machine?->name,
|
||||
responsibleUserId: $machine?->responsible_user_id,
|
||||
name: $model->name,
|
||||
counterId: $model->machine_counter_id,
|
||||
counterName: $counter?->name,
|
||||
counterUnit: $counter?->unit,
|
||||
intervalMilli: $model->interval_milli,
|
||||
period: $model->period,
|
||||
periodCount: $model->period_count,
|
||||
warningPercent: $model->warning_percent,
|
||||
instructions: $model->instructions,
|
||||
stockItemId: $model->stock_item_id,
|
||||
stockQuantityMilli: $model->stock_quantity_milli,
|
||||
isActive: $model->is_active,
|
||||
level: $state->level,
|
||||
remainingMilli: $state->remainingMilli,
|
||||
dueOn: $state->dueOn,
|
||||
readingMilli: $reading,
|
||||
lastRecordId: $last?->id,
|
||||
lastPerformedAt: $last === null ? null : $this->localTime($last->performed_at),
|
||||
lastPerformedByName: $last === null ? null : ($names[$last->user_id] ?? ''),
|
||||
);
|
||||
})->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Late items first, then those coming up, then by name.
|
||||
*
|
||||
* @param list<MaintenanceItemStatus> $items
|
||||
* @return list<MaintenanceItemStatus>
|
||||
*/
|
||||
private function sorted(array $items): array
|
||||
{
|
||||
usort($items, fn (MaintenanceItemStatus $a, MaintenanceItemStatus $b): int => [$b->level->rank(), $a->machineName, $a->name] <=> [$a->level->rank(), $b->machineName, $b->name]);
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function localTime(DateTimeInterface $moment): string
|
||||
{
|
||||
return Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i');
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Machines\Domain\Contracts\MaintenanceRepository;
|
||||
use App\Modules\Machines\Domain\Entities\MaintenanceItem;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceRecordModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentMaintenanceRepository implements MaintenanceRepository
|
||||
{
|
||||
public function findItem(int $id): ?MaintenanceItem
|
||||
{
|
||||
$model = MaintenanceItemModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : MaintenanceItem::reconstitute(
|
||||
$model->id,
|
||||
$model->machine_id,
|
||||
$model->name,
|
||||
$model->machine_counter_id,
|
||||
$model->interval_milli,
|
||||
$model->counter_baseline_milli,
|
||||
$model->period,
|
||||
$model->period_count,
|
||||
new DateTimeImmutable(substr($model->starts_on, 0, 10)),
|
||||
$model->warning_percent,
|
||||
$model->instructions,
|
||||
$model->stock_item_id,
|
||||
$model->stock_quantity_milli,
|
||||
$model->is_active,
|
||||
);
|
||||
}
|
||||
|
||||
public function saveItem(MaintenanceItem $item): MaintenanceItem
|
||||
{
|
||||
$model = $item->id() === null ? new MaintenanceItemModel : MaintenanceItemModel::query()->findOrFail($item->id());
|
||||
|
||||
$model->fill([
|
||||
'machine_id' => $item->machineId(),
|
||||
'name' => $item->name(),
|
||||
'machine_counter_id' => $item->counterId(),
|
||||
'interval_milli' => $item->intervalMilli(),
|
||||
'counter_baseline_milli' => $item->baselineMilli(),
|
||||
'period' => $item->period(),
|
||||
'period_count' => $item->periodCount(),
|
||||
'starts_on' => $item->startsOn()->format('Y-m-d'),
|
||||
'warning_percent' => $item->warningPercent(),
|
||||
'instructions' => $item->instructions(),
|
||||
'stock_item_id' => $item->stockItemId(),
|
||||
'stock_quantity_milli' => $item->stockQuantityMilli(),
|
||||
'is_active' => $item->isActive(),
|
||||
])->save();
|
||||
|
||||
return $this->findItem($model->id) ?? $item;
|
||||
}
|
||||
|
||||
public function machineOfCounter(int $counterId): ?int
|
||||
{
|
||||
$machineId = MachineCounterModel::query()->whereKey($counterId)->value('machine_id');
|
||||
|
||||
return $machineId === null ? null : (int) $machineId;
|
||||
}
|
||||
|
||||
public function latestReading(int $counterId): ?int
|
||||
{
|
||||
$reading = MachineCounterReadingModel::query()
|
||||
->where('machine_counter_id', $counterId)
|
||||
->orderByDesc('read_at')
|
||||
->orderByDesc('id')
|
||||
->value('reading_milli');
|
||||
|
||||
return $reading === null ? null : (int) $reading;
|
||||
}
|
||||
|
||||
public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void
|
||||
{
|
||||
MachineCounterReadingModel::query()->create([
|
||||
'machine_counter_id' => $counterId,
|
||||
'reading_milli' => $readingMilli,
|
||||
'user_id' => $userId,
|
||||
'read_at' => $at->format('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function addRecord(int $itemId, DateTimeImmutable $performedAt, int $userId, ?int $readingMilli, ?string $note): int
|
||||
{
|
||||
return MaintenanceRecordModel::query()->create([
|
||||
'maintenance_item_id' => $itemId,
|
||||
'performed_at' => $performedAt->format('Y-m-d H:i:s'),
|
||||
'user_id' => $userId,
|
||||
'counter_reading_milli' => $readingMilli,
|
||||
'note' => $note,
|
||||
])->id;
|
||||
}
|
||||
|
||||
public function findRecord(int $id): ?array
|
||||
{
|
||||
$model = MaintenanceRecordModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : ['id' => $model->id, 'itemId' => $model->maintenance_item_id, 'cancelled' => $model->cancelled_at !== null];
|
||||
}
|
||||
|
||||
public function cancelRecord(int $id, int $userId, DateTimeImmutable $at): void
|
||||
{
|
||||
MaintenanceRecordModel::query()->whereKey($id)->update(['cancelled_at' => $at->format('Y-m-d H:i:s'), 'cancelled_by' => $userId]);
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,18 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries;
|
||||
use App\Modules\Jobs\Domain\Events\TaskCompleted;
|
||||
use App\Modules\Machines\Application\Contracts\MachineQueries;
|
||||
use App\Modules\Machines\Application\Contracts\MachineTasks;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
|
||||
use App\Modules\Machines\Application\UseCases\MachineWorkList;
|
||||
use App\Modules\Machines\Domain\Contracts\MachineRepository;
|
||||
use App\Modules\Machines\Domain\Contracts\MaintenanceRepository;
|
||||
use App\Modules\Machines\Domain\Contracts\QueueRepository;
|
||||
use App\Modules\Machines\Infrastructure\Adapters\JobsForMachines;
|
||||
use App\Modules\Machines\Infrastructure\Adapters\StockForMachines;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMachineQueries;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMachineRepository;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMaintenanceQueries;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMaintenanceRepository;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentQueueRepository;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
@@ -35,6 +41,9 @@ class MachinesServiceProvider extends ServiceProvider
|
||||
QueueRepository::class => EloquentQueueRepository::class,
|
||||
MachineQueries::class => EloquentMachineQueries::class,
|
||||
MachineTasks::class => JobsForMachines::class,
|
||||
MaintenanceRepository::class => EloquentMaintenanceRepository::class,
|
||||
MaintenanceQueries::class => EloquentMaintenanceQueries::class,
|
||||
MaintenanceMaterials::class => StockForMachines::class,
|
||||
];
|
||||
|
||||
public function boot(): void
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
|
||||
|
||||
/**
|
||||
* Texts of a maintenance item's state, shared by the machine page and the
|
||||
* machine console: the level, the counter amount left and the due day.
|
||||
*/
|
||||
trait DescribesMaintenance
|
||||
{
|
||||
use FormatsMachines;
|
||||
|
||||
public function levelLabel(MaintenanceItemStatus $item): string
|
||||
{
|
||||
return __('machines.maintenance.levels.'.$item->level->value);
|
||||
}
|
||||
|
||||
public function levelIcon(MaintenanceItemStatus $item): string
|
||||
{
|
||||
return match ($item->level->value) {
|
||||
'overdue' => 'exclamation-triangle',
|
||||
'approaching' => 'clock',
|
||||
default => 'check-circle',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* E.g. "jäljellä 1 200 kpl, erääntyy 30.11.2026".
|
||||
*/
|
||||
public function stateText(MaintenanceItemStatus $item): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
if ($item->remainingMilli !== null && $item->counterUnit !== null) {
|
||||
$unit = __('machines.counter_units.'.$item->counterUnit->value);
|
||||
$parts[] = $item->remainingMilli >= 0
|
||||
? __('machines.maintenance.remaining', ['amount' => $this->reading($item->remainingMilli), 'unit' => $unit])
|
||||
: __('machines.maintenance.over', ['amount' => $this->reading(-$item->remainingMilli), 'unit' => $unit]);
|
||||
}
|
||||
|
||||
if ($item->dueOn !== null) {
|
||||
$parts[] = __($item->level->value === 'overdue' ? 'machines.maintenance.was_due' : 'machines.maintenance.due', ['date' => $this->dateLabel($item->dueOn)]);
|
||||
}
|
||||
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* E.g. "20 000 tulosteet" or "joka 2. viikko".
|
||||
*/
|
||||
public function intervalText(MaintenanceItemStatus $item): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
if ($item->intervalMilli !== null && $item->counterUnit !== null) {
|
||||
$parts[] = __('machines.maintenance.every_amount', [
|
||||
'amount' => $this->reading($item->intervalMilli),
|
||||
'unit' => __('machines.counter_units.'.$item->counterUnit->value),
|
||||
'counter' => (string) $item->counterName,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($item->period !== null) {
|
||||
$parts[] = trans_choice('machines.maintenance.every_period.'.$item->period->value, $item->periodCount, ['count' => $item->periodCount]);
|
||||
}
|
||||
|
||||
return implode(__('machines.maintenance.or'), $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
||||
use App\Modules\Machines\Application\Contracts\MachineQueries;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
|
||||
use App\Modules\Machines\Application\DTOs\MachineSummary;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemData;
|
||||
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
use App\Modules\Machines\Domain\Exceptions\CounterNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidMaintenanceItem;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
|
||||
use App\Modules\Machines\Domain\Exceptions\MachineNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNeedsInterval;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNotFound;
|
||||
use App\Modules\Machines\Presentation\Livewire\Concerns\FormatsMachines;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* Add and edit page of a machine's maintenance item (management, spec
|
||||
* 19.5): name, a counter interval (counter and amount), a time interval
|
||||
* (daily, weekly, monthly or yearly maintenance, every N periods), the
|
||||
* advance warning, instructions and a stock item used up at each
|
||||
* maintenance. A counter interval, a time interval or both are needed.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsMachines;
|
||||
|
||||
#[Locked]
|
||||
public int $machineId;
|
||||
|
||||
#[Locked]
|
||||
public ?int $itemId = null;
|
||||
|
||||
#[Locked]
|
||||
public bool $isActive = true;
|
||||
|
||||
public string $name = '';
|
||||
|
||||
public string $counterId = '';
|
||||
|
||||
public string $interval = '';
|
||||
|
||||
public string $period = '';
|
||||
|
||||
public string $periodCount = '1';
|
||||
|
||||
public string $warningPercent = '90';
|
||||
|
||||
public string $instructions = '';
|
||||
|
||||
public string $stockItemId = '';
|
||||
|
||||
public string $stockQuantity = '1';
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
public function mount(MachineQueries $machines, MaintenanceQueries $maintenance, int $machine, ?int $item = null): void
|
||||
{
|
||||
$this->authorize('machines.manage');
|
||||
|
||||
$this->machineId = ($machines->findMachine($machine) ?? abort(404))->id;
|
||||
|
||||
if ($item === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$status = $maintenance->findItem($item);
|
||||
abort_if($status === null || $status->machineId !== $this->machineId, 404);
|
||||
|
||||
$this->itemId = $status->id;
|
||||
$this->isActive = $status->isActive;
|
||||
$this->name = $status->name;
|
||||
$this->counterId = (string) ($status->counterId ?? '');
|
||||
$this->interval = $status->intervalMilli === null ? '' : str_replace("\u{00A0}", '', $this->reading($status->intervalMilli));
|
||||
$this->period = $status->period->value ?? '';
|
||||
$this->periodCount = (string) $status->periodCount;
|
||||
$this->warningPercent = (string) $status->warningPercent;
|
||||
$this->instructions = (string) $status->instructions;
|
||||
$this->stockItemId = (string) ($status->stockItemId ?? '');
|
||||
$this->stockQuantity = $status->stockQuantityMilli === null ? '1' : str_replace("\u{00A0}", '', $this->reading($status->stockQuantityMilli));
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function machine(): MachineSummary
|
||||
{
|
||||
return app(MachineQueries::class)->findMachine($this->machineId) ?? abort(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<StockItemSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function stockItems(): array
|
||||
{
|
||||
return app(StockQueries::class)->items();
|
||||
}
|
||||
|
||||
public function save(MachineMaintenance $maintenance): void
|
||||
{
|
||||
$this->authorize('machines.manage');
|
||||
$this->resetErrorBag();
|
||||
|
||||
$this->validate([
|
||||
'counterId' => ['nullable', 'integer'],
|
||||
'period' => ['nullable', 'in:'.implode(',', array_column(MaintenancePeriod::cases(), 'value'))],
|
||||
'periodCount' => ['required', 'integer', 'min:1', 'max:365'],
|
||||
'warningPercent' => ['required', 'integer', 'min:1', 'max:99'],
|
||||
'stockItemId' => ['nullable', 'integer'],
|
||||
'instructions' => ['nullable', 'string', 'max:5000'],
|
||||
], [
|
||||
'periodCount.*' => __('machines.maintenance.errors.period_count'),
|
||||
'warningPercent.*' => __('machines.maintenance.errors.warning'),
|
||||
]);
|
||||
|
||||
$data = new MaintenanceItemData(
|
||||
$this->name,
|
||||
$this->counterId === '' ? null : (int) $this->counterId,
|
||||
$this->counterId === '' ? '' : $this->interval,
|
||||
$this->period === '' ? null : $this->period,
|
||||
(int) $this->periodCount,
|
||||
(int) $this->warningPercent,
|
||||
$this->instructions,
|
||||
$this->stockItemId === '' ? null : (int) $this->stockItemId,
|
||||
$this->stockQuantity,
|
||||
);
|
||||
|
||||
try {
|
||||
$this->itemId = $maintenance->saveItem($this->machineId, $this->itemId, $data);
|
||||
} catch (InvalidReading) {
|
||||
$this->addError($this->counterId !== '' && trim($this->interval) !== '' ? 'interval' : 'stockQuantity', __('machines.maintenance.errors.amount'));
|
||||
|
||||
return;
|
||||
} catch (MaintenanceItemNeedsInterval) {
|
||||
$this->addError('period', __('machines.maintenance.errors.needs_interval'));
|
||||
|
||||
return;
|
||||
} catch (InvalidMaintenanceItem) {
|
||||
$this->addError('name', __('machines.maintenance.errors.invalid'));
|
||||
|
||||
return;
|
||||
} catch (CounterNotFound) {
|
||||
$this->addError('counterId', __('machines.maintenance.errors.counter'));
|
||||
|
||||
return;
|
||||
} catch (MachineNotFound|MaintenanceItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
session()->flash('status', __('machines.maintenance.saved', ['name' => trim($this->name)]));
|
||||
$this->redirect(route('machines.show', $this->machineId).'#maintenance-heading', navigate: true);
|
||||
}
|
||||
|
||||
public function toggleActive(MachineMaintenance $maintenance): void
|
||||
{
|
||||
$this->authorize('machines.manage');
|
||||
|
||||
if ($this->itemId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$maintenance->setItemActive($this->itemId, ! $this->isActive);
|
||||
$this->isActive = ! $this->isActive;
|
||||
$this->message = __($this->isActive ? 'machines.maintenance.activated' : 'machines.maintenance.deactivated');
|
||||
}
|
||||
|
||||
public function heading(): string
|
||||
{
|
||||
return __($this->itemId === null ? 'machines.maintenance.create_title' : 'machines.maintenance.edit_title');
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title($this->heading());
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-1">
|
||||
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
|
||||
<p class="text-sm">{{ $this->machine->name }}</p>
|
||||
</div>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
<x-input id="item-name" wire:model="name" :label="__('machines.maintenance.name')" :hint="__('machines.maintenance.name_hint')" autocomplete="off" maxlength="150" required />
|
||||
|
||||
<fieldset class="space-y-3">
|
||||
<legend class="font-semibold">{{ __('machines.maintenance.counter_interval') }}</legend>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('machines.maintenance.counter_interval_hint') }}</p>
|
||||
@if ($this->machine->counters === [])
|
||||
<p class="text-sm">{{ __('machines.maintenance.no_counters') }}</p>
|
||||
@else
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native id="item-counter" wire:model.live="counterId" :label="__('machines.maintenance.counter')" :aria-label="__('machines.maintenance.counter')">
|
||||
<option value="">{{ __('machines.maintenance.no_counter') }}</option>
|
||||
@foreach ($this->machine->counters as $counter)
|
||||
<option value="{{ $counter->id }}">{{ $counter->name }} ({{ __('machines.counter_units.'.$counter->unit->value) }})</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
@if ($counterId !== '')
|
||||
<x-input id="item-interval" wire:model="interval" inputmode="decimal" :label="__('machines.maintenance.interval')" :hint="__('machines.maintenance.interval_hint')" autocomplete="off" />
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="space-y-3">
|
||||
<legend class="font-semibold">{{ __('machines.maintenance.time_interval') }}</legend>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('machines.maintenance.time_interval_hint') }}</p>
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<x-select.native id="item-period" wire:model.live="period" :label="__('machines.maintenance.period')" :aria-label="__('machines.maintenance.period')">
|
||||
<option value="">{{ __('machines.maintenance.no_period') }}</option>
|
||||
@foreach (MaintenancePeriod::cases() as $option)
|
||||
<option value="{{ $option->value }}">{{ __('machines.maintenance.periods.'.$option->value) }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
@if ($period !== '')
|
||||
<x-input id="item-period-count" wire:model="periodCount" type="number" min="1" max="365" :label="__('machines.maintenance.period_count')" :hint="__('machines.maintenance.period_count_hint')" />
|
||||
@endif
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<x-input id="item-warning" wire:model="warningPercent" type="number" min="1" max="99" :label="__('machines.maintenance.warning')" :hint="__('machines.maintenance.warning_hint')" />
|
||||
|
||||
<x-textarea id="item-instructions" wire:model="instructions" :label="__('machines.maintenance.instructions')" resize-auto />
|
||||
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<x-select.native id="item-stock" wire:model.live="stockItemId" :label="__('machines.maintenance.stock_item')" :aria-label="__('machines.maintenance.stock_item')" :hint="__('machines.maintenance.stock_item_hint')">
|
||||
<option value="">{{ __('machines.maintenance.no_stock_item') }}</option>
|
||||
@foreach ($this->stockItems as $stockItem)
|
||||
<option value="{{ $stockItem->id }}">{{ $stockItem->name }} ({{ __('inventory.units.'.$stockItem->unit->value) }})</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
@if ($stockItemId !== '')
|
||||
<x-input id="item-stock-quantity" wire:model="stockQuantity" inputmode="decimal" :label="__('machines.maintenance.stock_quantity')" autocomplete="off" />
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<x-button submit :text="__('machines.form.save')" />
|
||||
<x-button :href="route('machines.show', $machineId)" wire:navigate subtle color="black" :text="__('machines.form.cancel')" />
|
||||
@if ($itemId !== null)
|
||||
<x-button wire:click="toggleActive" subtle color="black" :icon="$isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'" :text="$isActive ? __('machines.form.deactivate') : __('machines.form.activate')" />
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,371 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Machines\Application\Contracts\MachineQueries;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
|
||||
use App\Modules\Machines\Application\DTOs\MachineSummary;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
|
||||
use App\Modules\Machines\Application\DTOs\MaintenanceRecordSummary;
|
||||
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
|
||||
use App\Modules\Machines\Domain\Exceptions\CounterNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceItemNotFound;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceRecordCancelled;
|
||||
use App\Modules\Machines\Domain\Exceptions\MaintenanceRecordNotFound;
|
||||
use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A machine's counters, maintenance items and maintenance history on its
|
||||
* page (spec 19.5). Anyone using the machine records counter readings and
|
||||
* maintenance done (the reading prefilled); management keeps the items
|
||||
* and cancels mistaken records. The history is filtered by item and days.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use DescribesMaintenance;
|
||||
|
||||
#[Locked]
|
||||
public int $machineId;
|
||||
|
||||
/**
|
||||
* Readings typed, by counter id.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $readings = [];
|
||||
|
||||
#[Locked]
|
||||
public ?int $recordingItemId = null;
|
||||
|
||||
public string $recordReading = '';
|
||||
|
||||
public string $recordNote = '';
|
||||
|
||||
public string $historyItem = '';
|
||||
|
||||
public string $historyFrom = '';
|
||||
|
||||
public string $historyTo = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $cancelRecordId = null;
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
abort_if(app(MachineQueries::class)->findMachine($this->machineId) === null, 404);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function machine(): MachineSummary
|
||||
{
|
||||
return app(MachineQueries::class)->findMachine($this->machineId) ?? abort(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<MaintenanceItemStatus>
|
||||
*/
|
||||
#[Computed]
|
||||
public function items(): array
|
||||
{
|
||||
return app(MaintenanceQueries::class)->itemsOf($this->machineId, auth()->user()?->can('machines.manage') === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<MaintenanceRecordSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function history(): array
|
||||
{
|
||||
return app(MaintenanceQueries::class)->history(
|
||||
$this->machineId,
|
||||
$this->historyItem === '' ? null : (int) $this->historyItem,
|
||||
$this->validDay($this->historyFrom),
|
||||
$this->validDay($this->historyTo),
|
||||
);
|
||||
}
|
||||
|
||||
public function updated(string $property): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
|
||||
if (str_starts_with($property, 'history')) {
|
||||
unset($this->history);
|
||||
}
|
||||
}
|
||||
|
||||
public function saveReading(int $counterId, MachineMaintenance $maintenance): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
$this->resetErrorBag('readings.'.$counterId);
|
||||
|
||||
$counter = collect($this->machine->counters)->firstWhere('id', $counterId) ?? abort(404);
|
||||
|
||||
try {
|
||||
$milli = $maintenance->recordReading($counterId, $this->readings[$counterId] ?? '', (int) auth()->id());
|
||||
} catch (InvalidReading) {
|
||||
$this->addError('readings.'.$counterId, __('machines.maintenance.errors.reading'));
|
||||
|
||||
return;
|
||||
} catch (CounterNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->message = __('machines.maintenance.reading_saved', ['counter' => $counter->name, 'reading' => $this->reading($milli), 'unit' => __('machines.counter_units.'.$counter->unit->value)]);
|
||||
unset($this->readings[$counterId], $this->machine, $this->items);
|
||||
}
|
||||
|
||||
public function startRecord(int $itemId): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
|
||||
$item = $this->item($itemId);
|
||||
$this->recordingItemId = $itemId;
|
||||
$this->recordReading = $item->readingMilli === null ? '' : str_replace("\u{00A0}", '', $this->reading($item->readingMilli));
|
||||
$this->recordNote = '';
|
||||
$this->resetErrorBag();
|
||||
$this->js("setTimeout(() => document.getElementById('record-reading')?.focus() ?? document.getElementById('record-note')?.focus())");
|
||||
}
|
||||
|
||||
public function cancelRecording(): void
|
||||
{
|
||||
$itemId = $this->recordingItemId;
|
||||
$this->recordingItemId = null;
|
||||
$this->js("document.getElementById('item-{$itemId}-done')?.focus()");
|
||||
}
|
||||
|
||||
public function record(MachineMaintenance $maintenance): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
|
||||
$item = $this->item((int) $this->recordingItemId);
|
||||
|
||||
try {
|
||||
$result = $maintenance->recordMaintenance($item->id, (int) auth()->id(), $item->counterId === null ? '' : $this->recordReading, $this->recordNote);
|
||||
} catch (InvalidReading) {
|
||||
$this->addError('recordReading', __('machines.maintenance.errors.reading'));
|
||||
|
||||
return;
|
||||
} catch (MaintenanceItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->message = __('machines.maintenance.recorded', ['name' => $item->name])
|
||||
.($result['stockRecorded'] ? '' : ' '.__('machines.maintenance.stock_not_recorded'));
|
||||
$this->recordingItemId = null;
|
||||
unset($this->items, $this->history, $this->machine);
|
||||
$this->js("document.getElementById('maintenance-status')?.focus()");
|
||||
}
|
||||
|
||||
public function confirmCancel(int $recordId): void
|
||||
{
|
||||
$this->authorize('machines.manage');
|
||||
|
||||
$this->cancelRecordId = $recordId;
|
||||
$this->js("document.getElementById('cancel-record-dialog').showModal()");
|
||||
}
|
||||
|
||||
public function cancelRecord(MachineMaintenance $maintenance): void
|
||||
{
|
||||
$this->authorize('machines.manage');
|
||||
|
||||
$record = collect($this->history)->firstWhere('id', $this->cancelRecordId) ?? abort(404);
|
||||
|
||||
try {
|
||||
$maintenance->cancelRecord($record->id, (int) auth()->id());
|
||||
$this->message = __('machines.maintenance.cancelled', ['name' => $record->itemName]);
|
||||
} catch (MaintenanceRecordNotFound|MaintenanceRecordCancelled) {
|
||||
$this->message = __('machines.errors.not_found');
|
||||
}
|
||||
|
||||
$this->cancelRecordId = null;
|
||||
unset($this->items, $this->history);
|
||||
$this->js("document.getElementById('cancel-record-dialog').close(); document.getElementById('maintenance-status').focus()");
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view();
|
||||
}
|
||||
|
||||
private function item(int $itemId): MaintenanceItemStatus
|
||||
{
|
||||
return collect($this->items)->firstWhere('id', $itemId) ?? abort(404);
|
||||
}
|
||||
|
||||
private function validDay(string $value): ?string
|
||||
{
|
||||
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value);
|
||||
|
||||
return $date !== null && $date->format('Y-m-d') === $value ? $value : null;
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="space-y-6">
|
||||
<p id="maintenance-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
|
||||
|
||||
@if ($this->machine->counters !== [])
|
||||
<section aria-labelledby="counters-heading" class="space-y-3">
|
||||
<h2 id="counters-heading" class="text-xl font-semibold">{{ __('machines.maintenance.counters') }}</h2>
|
||||
<ul class="space-y-3">
|
||||
@foreach ($this->machine->counters as $counter)
|
||||
<li wire:key="counter-{{ $counter->id }}" class="flex flex-wrap items-end gap-3 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600">
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="font-medium">{{ $counter->name }}</p>
|
||||
<p class="text-sm">
|
||||
@if ($counter->readingMilli === null)
|
||||
{{ __('machines.maintenance.no_reading') }}
|
||||
@else
|
||||
{{ __('machines.maintenance.latest_reading', ['reading' => $this->reading($counter->readingMilli), 'unit' => __('machines.counter_units.'.$counter->unit->value), 'at' => $this->dateLabel((string) $counter->readAt)]) }}
|
||||
@endif
|
||||
</p>
|
||||
</div>
|
||||
<form wire:submit="saveReading({{ $counter->id }})" class="flex flex-wrap items-end gap-2" novalidate>
|
||||
<div class="w-40">
|
||||
<x-input
|
||||
id="reading-{{ $counter->id }}"
|
||||
wire:model="readings.{{ $counter->id }}"
|
||||
inputmode="decimal"
|
||||
:label="__('machines.maintenance.new_reading', ['unit' => __('machines.counter_units.'.$counter->unit->value)])"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<x-button submit sm :text="__('machines.maintenance.save_reading')" :aria-label="__('machines.maintenance.save_reading_named', ['counter' => $counter->name])" />
|
||||
</form>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</section>
|
||||
@endif
|
||||
|
||||
<section aria-labelledby="maintenance-heading" class="space-y-3">
|
||||
<h2 id="maintenance-heading" class="text-xl font-semibold">{{ __('machines.maintenance.items') }}</h2>
|
||||
@can('machines.manage')
|
||||
<p><x-button :href="route('machines.maintenance.create', $machineId)" wire:navigate sm icon="plus" :text="__('machines.maintenance.add')" /></p>
|
||||
@endcan
|
||||
|
||||
@if ($this->items === [])
|
||||
<p class="text-sm">{{ __('machines.maintenance.none') }}</p>
|
||||
@else
|
||||
<ul class="space-y-3">
|
||||
@foreach ($this->items as $item)
|
||||
<li wire:key="item-{{ $item->id }}" class="space-y-2 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600">
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div class="min-w-0 space-y-1">
|
||||
<p class="font-medium break-words">{{ $item->name }}@unless ($item->isActive) ({{ __('machines.index.inactive') }})@endunless</p>
|
||||
<p class="flex flex-wrap items-center gap-1 text-sm font-medium @if ($item->level->value === 'overdue') text-red-700 dark:text-red-400 @elseif ($item->level->value === 'approaching') text-amber-800 dark:text-amber-300 @endif">
|
||||
<x-icon :name="$this->levelIcon($item)" class="size-4" aria-hidden="true" />
|
||||
{{ $this->levelLabel($item) }}@if ($this->stateText($item) !== ''): {{ $this->stateText($item) }}@endif
|
||||
</p>
|
||||
<p class="text-sm text-zinc-700 dark:text-zinc-300">{{ __('machines.maintenance.interval_text', ['interval' => $this->intervalText($item)]) }}</p>
|
||||
<p class="text-sm text-zinc-700 dark:text-zinc-300">
|
||||
@if ($item->lastPerformedAt === null)
|
||||
{{ __('machines.maintenance.never_done') }}
|
||||
@else
|
||||
{{ __('machines.maintenance.last_done', ['at' => $this->dateLabel($item->lastPerformedAt), 'name' => $item->lastPerformedByName]) }}
|
||||
@endif
|
||||
</p>
|
||||
</div>
|
||||
@can('machines.manage')
|
||||
<x-link :href="route('machines.maintenance.edit', [$machineId, $item->id])" navigate class="text-sm">{{ __('machines.maintenance.edit_named', ['name' => $item->name]) }}</x-link>
|
||||
@endcan
|
||||
</div>
|
||||
|
||||
@if ($item->instructions !== null)
|
||||
<details class="text-sm">
|
||||
<summary class="cursor-pointer font-medium">{{ __('machines.maintenance.instructions') }}</summary>
|
||||
<p class="mt-1 whitespace-pre-line">{{ $item->instructions }}</p>
|
||||
</details>
|
||||
@endif
|
||||
|
||||
@if ($item->isActive)
|
||||
@if ($recordingItemId === $item->id)
|
||||
<form wire:submit="record" class="flex flex-wrap items-end gap-2" novalidate>
|
||||
@if ($item->counterId !== null)
|
||||
<div class="w-40">
|
||||
<x-input id="record-reading" wire:model="recordReading" inputmode="decimal" :label="__('machines.maintenance.reading_at', ['counter' => (string) $item->counterName])" autocomplete="off" />
|
||||
</div>
|
||||
@endif
|
||||
<div class="min-w-48 flex-1">
|
||||
<x-input id="record-note" wire:model="recordNote" :label="__('machines.maintenance.note')" autocomplete="off" maxlength="2000" />
|
||||
</div>
|
||||
<x-button submit sm icon="check" :text="__('machines.maintenance.confirm_done')" />
|
||||
<x-button wire:click="cancelRecording" subtle color="black" sm :text="__('machines.task.cancel')" />
|
||||
</form>
|
||||
@else
|
||||
<x-button id="item-{{ $item->id }}-done" wire:click="startRecord({{ $item->id }})" sm icon="wrench" :text="__('machines.maintenance.done')" :aria-label="__('machines.maintenance.done_named', ['name' => $item->name])" />
|
||||
@endif
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="history-heading" class="space-y-3">
|
||||
<h2 id="history-heading" class="text-xl font-semibold">{{ __('machines.maintenance.history') }}</h2>
|
||||
<div class="grid gap-3 sm:grid-cols-3">
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native id="history-item" wire:model.live="historyItem" :label="__('machines.maintenance.history_item')" :aria-label="__('machines.maintenance.history_item')">
|
||||
<option value="">{{ __('machines.maintenance.all_items') }}</option>
|
||||
@foreach ($this->items as $item)
|
||||
<option value="{{ $item->id }}">{{ $item->name }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
<x-input id="history-from" wire:model.live="historyFrom" type="date" :label="__('machines.maintenance.from')" />
|
||||
<x-input id="history-to" wire:model.live="historyTo" type="date" :label="__('machines.maintenance.to')" />
|
||||
</div>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm">{{ trans_choice('machines.maintenance.history_count', count($this->history), ['count' => count($this->history)]) }}</p>
|
||||
|
||||
@if ($this->history !== [])
|
||||
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 text-sm dark:divide-zinc-700 dark:border-zinc-600">
|
||||
@foreach ($this->history as $record)
|
||||
<li wire:key="record-{{ $record->id }}" class="flex flex-wrap items-center justify-between gap-2 p-3">
|
||||
<div class="min-w-0">
|
||||
<p class="font-medium">{{ $record->itemName }} · {{ $this->dateLabel($record->performedAt) }} · {{ $record->userName }}</p>
|
||||
@if ($record->readingMilli !== null)
|
||||
<p>{{ __('machines.maintenance.reading_was', ['reading' => $this->reading($record->readingMilli)]) }}</p>
|
||||
@endif
|
||||
@if ($record->note !== null)
|
||||
<p class="whitespace-pre-line">{{ $record->note }}</p>
|
||||
@endif
|
||||
@if ($record->cancelledAt !== null)
|
||||
<p class="flex items-center gap-1 font-medium">
|
||||
<x-icon name="x-circle" class="size-4" aria-hidden="true" />
|
||||
{{ __('machines.maintenance.cancelled_by', ['at' => $this->dateLabel($record->cancelledAt), 'name' => $record->cancelledByName]) }}
|
||||
</p>
|
||||
@endif
|
||||
</div>
|
||||
@if ($record->cancelledAt === null)
|
||||
@can('machines.manage')
|
||||
<x-button wire:click="confirmCancel({{ $record->id }})" subtle color="black" sm icon="x-mark" :text="__('machines.maintenance.cancel')" :aria-label="__('machines.maintenance.cancel_named', ['name' => $record->itemName, 'at' => $this->dateLabel($record->performedAt)])" />
|
||||
@endcan
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
@can('machines.manage')
|
||||
<x-confirm-dialog id="cancel-record-dialog" :title="__('machines.maintenance.cancel_title')">
|
||||
<p>{{ __('machines.maintenance.cancel_text') }}</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="cancelRecord" color="red" :text="__('machines.maintenance.cancel')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
@endcan
|
||||
</div>
|
||||
@@ -383,4 +383,6 @@ new class extends Component
|
||||
</ol>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<livewire:machines::maintenance :machine-id="$machine->id" :wire:key="'maintenance-'.$machine->id" />
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,8 @@ Route::middleware(['web', 'auth', 'can:machines.use'])
|
||||
Route::middleware('can:machines.manage')->group(function () {
|
||||
Route::livewire('/create', 'machines::form')->name('create');
|
||||
Route::livewire('/{machine}/edit', 'machines::form')->whereNumber('machine')->name('edit');
|
||||
Route::livewire('/{machine}/maintenance/create', 'machines::maintenance-item-form')->whereNumber('machine')->name('maintenance.create');
|
||||
Route::livewire('/{machine}/maintenance/{item}/edit', 'machines::maintenance-item-form')->whereNumber(['machine', 'item'])->name('maintenance.edit');
|
||||
});
|
||||
|
||||
Route::livewire('/{machine}', 'machines::show')->whereNumber('machine')->name('show');
|
||||
|
||||
Reference in New Issue
Block a user