From 3e1c6719492f2ce794d58d0030c14fb194c1f4c0 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Thu, 26 Nov 2026 16:52:49 +0200 Subject: [PATCH] Track machine counters and maintenance with counter and time intervals Co-Authored-By: Claude Sonnet 5.5 --- .../Application/Contracts/DashboardAdmin.php | 16 +- .../Application/DTOs/ManagementOverview.php | 3 + .../UseCases/ManagementOverviewQuery.php | 2 + .../Adapters/AdminForDashboard.php | 28 +- .../Livewire/⚡management.blade.php | 23 ++ .../Contracts/MaintenanceMaterials.php | 16 + .../Contracts/MaintenanceQueries.php | 36 ++ .../Application/DTOs/MaintenanceItemData.php | 26 ++ .../DTOs/MaintenanceItemStatus.php | 43 ++ .../DTOs/MaintenanceRecordSummary.php | 24 ++ .../UseCases/MachineMaintenance.php | 169 ++++++++ .../Contracts/MaintenanceRepository.php | 39 ++ .../Domain/Entities/MaintenanceItem.php | 213 ++++++++++ .../Domain/Enums/MaintenanceLevel.php | 25 ++ .../Domain/Enums/MaintenancePeriod.php | 52 +++ .../Domain/Exceptions/CounterNotFound.php | 15 + .../Exceptions/InvalidMaintenanceItem.php | 15 + .../Domain/Exceptions/InvalidReading.php | 15 + .../MaintenanceItemNeedsInterval.php | 15 + .../Exceptions/MaintenanceItemNotFound.php | 15 + .../Exceptions/MaintenanceRecordCancelled.php | 15 + .../Exceptions/MaintenanceRecordNotFound.php | 15 + .../Domain/Services/MaintenanceStatus.php | 73 ++++ .../Domain/ValueObjects/MaintenanceState.php | 21 + .../Machines/Domain/ValueObjects/Reading.php | 34 ++ .../Adapters/StockForMachines.php | 34 ++ .../Eloquent/MaintenanceItemModel.php | 65 +++ .../Eloquent/MaintenanceRecordModel.php | 40 ++ .../EloquentMaintenanceQueries.php | 172 ++++++++ .../EloquentMaintenanceRepository.php | 110 ++++++ .../Providers/MachinesServiceProvider.php | 9 + .../Concerns/DescribesMaintenance.php | 71 ++++ .../⚡maintenance-item-form.blade.php | 256 ++++++++++++ .../Livewire/⚡maintenance.blade.php | 371 ++++++++++++++++++ .../Presentation/Livewire/⚡show.blade.php | 2 + .../Machines/Presentation/Routes/web.php | 2 + .../UseCases/NotifyMaintenanceDue.php | 58 +++ .../Domain/Enums/NotificationType.php | 5 + .../Domain/ValueObjects/NewNotification.php | 11 + .../NotificationsServiceProvider.php | 3 +- .../Console/NotifyMaintenanceDueCommand.php | 22 ++ .../Presentation/Livewire/⚡bell.blade.php | 5 + ...11_26_144417_create_maintenance_tables.php | 66 ++++ lang/en/dashboard.php | 3 + lang/en/machines.php | 95 +++++ lang/en/notifications.php | 4 + lang/fi/dashboard.php | 3 + lang/fi/machines.php | 95 +++++ lang/fi/notifications.php | 4 + routes/console.php | 6 + tests/Browser/MachinesAccessibilityTest.php | 22 +- .../Modules/Machines/MaintenanceTest.php | 122 ++++++ .../Machines/MaintenanceStatusTest.php | 38 ++ 53 files changed, 2636 insertions(+), 6 deletions(-) create mode 100644 app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php create mode 100644 app/Modules/Machines/Application/Contracts/MaintenanceQueries.php create mode 100644 app/Modules/Machines/Application/DTOs/MaintenanceItemData.php create mode 100644 app/Modules/Machines/Application/DTOs/MaintenanceItemStatus.php create mode 100644 app/Modules/Machines/Application/DTOs/MaintenanceRecordSummary.php create mode 100644 app/Modules/Machines/Application/UseCases/MachineMaintenance.php create mode 100644 app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php create mode 100644 app/Modules/Machines/Domain/Entities/MaintenanceItem.php create mode 100644 app/Modules/Machines/Domain/Enums/MaintenanceLevel.php create mode 100644 app/Modules/Machines/Domain/Enums/MaintenancePeriod.php create mode 100644 app/Modules/Machines/Domain/Exceptions/CounterNotFound.php create mode 100644 app/Modules/Machines/Domain/Exceptions/InvalidMaintenanceItem.php create mode 100644 app/Modules/Machines/Domain/Exceptions/InvalidReading.php create mode 100644 app/Modules/Machines/Domain/Exceptions/MaintenanceItemNeedsInterval.php create mode 100644 app/Modules/Machines/Domain/Exceptions/MaintenanceItemNotFound.php create mode 100644 app/Modules/Machines/Domain/Exceptions/MaintenanceRecordCancelled.php create mode 100644 app/Modules/Machines/Domain/Exceptions/MaintenanceRecordNotFound.php create mode 100644 app/Modules/Machines/Domain/Services/MaintenanceStatus.php create mode 100644 app/Modules/Machines/Domain/ValueObjects/MaintenanceState.php create mode 100644 app/Modules/Machines/Domain/ValueObjects/Reading.php create mode 100644 app/Modules/Machines/Infrastructure/Adapters/StockForMachines.php create mode 100644 app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceItemModel.php create mode 100644 app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceRecordModel.php create mode 100644 app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceQueries.php create mode 100644 app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php create mode 100644 app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php create mode 100644 app/Modules/Machines/Presentation/Livewire/⚡maintenance-item-form.blade.php create mode 100644 app/Modules/Machines/Presentation/Livewire/⚡maintenance.blade.php create mode 100644 app/Modules/Notifications/Application/UseCases/NotifyMaintenanceDue.php create mode 100644 app/Modules/Notifications/Presentation/Console/NotifyMaintenanceDueCommand.php create mode 100644 database/migrations/2026_11_26_144417_create_maintenance_tables.php create mode 100644 tests/Feature/Modules/Machines/MaintenanceTest.php create mode 100644 tests/Unit/Modules/Machines/MaintenanceStatusTest.php diff --git a/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php b/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php index 425b14a..53b1c40 100644 --- a/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php +++ b/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php @@ -5,8 +5,8 @@ declare(strict_types=1); namespace App\Modules\Dashboard\Application\Contracts; /** - * What the management panel needs from Billing, Sales, Users and the - * holiday calendar. Days are Y-m-d. + * What the management panel needs from Billing, Sales, Users, Machines, + * Inventory and the holiday calendar. Days are Y-m-d. */ interface DashboardAdmin { @@ -35,4 +35,16 @@ interface DashboardAdmin * @return list */ public function holidaysBetween(string $from, string $to): array; + + /** + * Machine maintenance that is late (maintenance requests), by machine. + * + * @return list + */ + public function lateMaintenance(): array; + + /** + * How many stock items are at or below their reorder level. + */ + public function stockItemsToOrder(): int; } diff --git a/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php b/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php index 1711227..029eb01 100644 --- a/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php +++ b/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php @@ -22,6 +22,7 @@ final readonly class ManagementOverview * @param array $jobCounts * @param list $oldestOverdueTasks * @param list $workloads + * @param list $lateMaintenance */ public function __construct( public array $pendingApprovals, @@ -42,5 +43,7 @@ final readonly class ManagementOverview public string $thisMonday, public string $nextMonday, public array $workloads, + public array $lateMaintenance = [], + public int $stockItemsToOrder = 0, ) {} } diff --git a/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php b/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php index 30e47ee..444994e 100644 --- a/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php +++ b/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php @@ -62,6 +62,8 @@ final readonly class ManagementOverviewQuery $thisMonday->format('Y-m-d'), $nextMonday->format('Y-m-d'), $this->workloads($thisMonday, $nextMonday), + $this->admin->lateMaintenance(), + $this->admin->stockItemsToOrder(), ); } diff --git a/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php b/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php index f8db49f..6ddf7a6 100644 --- a/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php +++ b/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php @@ -5,14 +5,18 @@ namespace App\Modules\Dashboard\Infrastructure\Adapters; use App\Modules\Billing\Application\Contracts\BillingQueries; use App\Modules\Billing\Domain\Enums\ExportStatus; use App\Modules\Dashboard\Application\Contracts\DashboardAdmin; +use App\Modules\Inventory\Application\Contracts\StockQueries; +use App\Modules\Machines\Application\Contracts\MaintenanceQueries; +use App\Modules\Machines\Domain\Enums\MaintenanceLevel; use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Shared\Application\UseCases\HolidayCalendar; use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Domain\Enums\Role; /** - * Billing drafts, cash days, people and holidays for the management panel - * through the Billing, Sales, Users and Shared modules. + * Billing drafts, cash days, people, holidays, late maintenance and stock + * to order for the management panel through the Billing, Sales, Users, + * Shared, Machines and Inventory modules. */ class AdminForDashboard implements DashboardAdmin { @@ -21,6 +25,8 @@ class AdminForDashboard implements DashboardAdmin private QuickSaleQueries $sales, private UserAccountQueries $users, private HolidayCalendar $holidays, + private MaintenanceQueries $maintenance, + private StockQueries $stock, ) {} public function openDraftId(): ?int @@ -56,4 +62,22 @@ class AdminForDashboard implements DashboardAdmin { return $this->holidays->activeDatesBetween($from, $to); } + + public function lateMaintenance(): array + { + $late = []; + + foreach ($this->maintenance->due() as $item) { + if ($item->level === MaintenanceLevel::Overdue) { + $late[] = ['machineId' => $item->machineId, 'machine' => $item->machineName, 'item' => $item->name]; + } + } + + return $late; + } + + public function stockItemsToOrder(): int + { + return count($this->stock->items(onlyReorder: true)); + } } diff --git a/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php b/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php index d3f9700..faf3cbd 100644 --- a/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php +++ b/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php @@ -104,6 +104,29 @@ new class extends Component @endif @endcan + @can('machines.use') + @if ($overview->lateMaintenance !== []) +
  • + + {{ trans_choice('dashboard.todo.maintenance', count($overview->lateMaintenance), ['count' => count($overview->lateMaintenance)]) }} + +
      + @foreach ($overview->lateMaintenance as $late) +
    • {{ __('dashboard.todo.maintenance_line', ['machine' => $late['machine'], 'item' => $late['item']]) }}
    • + @endforeach +
    +
  • + @endif + @endcan + @can('inventory.view') + @if ($overview->stockItemsToOrder > 0) +
  • + + {{ trans_choice('dashboard.todo.stock', $overview->stockItemsToOrder, ['count' => $overview->stockItemsToOrder]) }} + +
  • + @endif + @endcan @can('reports.view')
  • {{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }} diff --git a/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php b/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php new file mode 100644 index 0000000..80d922f --- /dev/null +++ b/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php @@ -0,0 +1,16 @@ + + */ + 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 + */ + public function due(): array; + + /** + * A machine's maintenance history, newest first, filtered by item and + * by days (Y-m-d, both inclusive). + * + * @return list + */ + public function history(int $machineId, ?int $itemId = null, ?string $from = null, ?string $to = null, int $limit = 200): array; +} diff --git a/app/Modules/Machines/Application/DTOs/MaintenanceItemData.php b/app/Modules/Machines/Application/DTOs/MaintenanceItemData.php new file mode 100644 index 0000000..0e18eb0 --- /dev/null +++ b/app/Modules/Machines/Application/DTOs/MaintenanceItemData.php @@ -0,0 +1,26 @@ +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()); + }); + } +} diff --git a/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php b/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php new file mode 100644 index 0000000..f7532bd --- /dev/null +++ b/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php @@ -0,0 +1,39 @@ +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; + } +} diff --git a/app/Modules/Machines/Domain/Enums/MaintenanceLevel.php b/app/Modules/Machines/Domain/Enums/MaintenanceLevel.php new file mode 100644 index 0000000..ca077ad --- /dev/null +++ b/app/Modules/Machines/Domain/Enums/MaintenanceLevel.php @@ -0,0 +1,25 @@ + 0, + self::Approaching => 1, + self::Overdue => 2, + }; + } +} diff --git a/app/Modules/Machines/Domain/Enums/MaintenancePeriod.php b/app/Modules/Machines/Domain/Enums/MaintenancePeriod.php new file mode 100644 index 0000000..1594ac5 --- /dev/null +++ b/app/Modules/Machines/Domain/Enums/MaintenancePeriod.php @@ -0,0 +1,52 @@ +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); + } +} diff --git a/app/Modules/Machines/Domain/Exceptions/CounterNotFound.php b/app/Modules/Machines/Domain/Exceptions/CounterNotFound.php new file mode 100644 index 0000000..d3eca06 --- /dev/null +++ b/app/Modules/Machines/Domain/Exceptions/CounterNotFound.php @@ -0,0 +1,15 @@ += $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; + } +} diff --git a/app/Modules/Machines/Domain/ValueObjects/MaintenanceState.php b/app/Modules/Machines/Domain/ValueObjects/MaintenanceState.php new file mode 100644 index 0000000..011b668 --- /dev/null +++ b/app/Modules/Machines/Domain/ValueObjects/MaintenanceState.php @@ -0,0 +1,21 @@ +recordUse->execute(new StockUseData( + $stockItemId, + StockQuantity::inputValue($quantityMilli), + machineId: $machineId, + maintenanceRecordId: $maintenanceRecordId, + ), $userId); + } catch (DomainException) { + return false; + } + + return true; + } +} diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceItemModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceItemModel.php new file mode 100644 index 0000000..33f5124 --- /dev/null +++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceItemModel.php @@ -0,0 +1,65 @@ + + */ + 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 + */ + 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', + ]; + } +} diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceRecordModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceRecordModel.php new file mode 100644 index 0000000..d443cfc --- /dev/null +++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MaintenanceRecordModel.php @@ -0,0 +1,40 @@ + + */ + 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', + ]; + } +} diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceQueries.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceQueries.php new file mode 100644 index 0000000..b274f09 --- /dev/null +++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceQueries.php @@ -0,0 +1,172 @@ +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 $models + * @return list + */ + 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 $items + * @return list + */ + 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'); + } +} diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php new file mode 100644 index 0000000..40a8284 --- /dev/null +++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php @@ -0,0 +1,110 @@ +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]); + } +} diff --git a/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php index 69ad43a..695dad5 100644 --- a/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php +++ b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php @@ -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 diff --git a/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php b/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php new file mode 100644 index 0000000..63fc52d --- /dev/null +++ b/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php @@ -0,0 +1,71 @@ +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); + } +} diff --git a/app/Modules/Machines/Presentation/Livewire/⚡maintenance-item-form.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡maintenance-item-form.blade.php new file mode 100644 index 0000000..6f5a611 --- /dev/null +++ b/app/Modules/Machines/Presentation/Livewire/⚡maintenance-item-form.blade.php @@ -0,0 +1,256 @@ +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 + */ + #[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()); + } +}; +?> + +
    +
    +

    {{ $this->heading() }}

    +

    {{ $this->machine->name }}

    +
    + +

    {{ $message }}

    + +
    + + +
    + {{ __('machines.maintenance.counter_interval') }} +

    {{ __('machines.maintenance.counter_interval_hint') }}

    + @if ($this->machine->counters === []) +

    {{ __('machines.maintenance.no_counters') }}

    + @else +
    + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->machine->counters as $counter) + + @endforeach + + @if ($counterId !== '') + + @endif +
    + @endif +
    + +
    + {{ __('machines.maintenance.time_interval') }} +

    {{ __('machines.maintenance.time_interval_hint') }}

    +
    + + + @foreach (MaintenancePeriod::cases() as $option) + + @endforeach + + @if ($period !== '') + + @endif +
    +
    + + + + + +
    + + + @foreach ($this->stockItems as $stockItem) + + @endforeach + + @if ($stockItemId !== '') + + @endif +
    + +
    + + + @if ($itemId !== null) + + @endif +
    + +
    diff --git a/app/Modules/Machines/Presentation/Livewire/⚡maintenance.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡maintenance.blade.php new file mode 100644 index 0000000..be823f7 --- /dev/null +++ b/app/Modules/Machines/Presentation/Livewire/⚡maintenance.blade.php @@ -0,0 +1,371 @@ + + */ + 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 + */ + #[Computed] + public function items(): array + { + return app(MaintenanceQueries::class)->itemsOf($this->machineId, auth()->user()?->can('machines.manage') === true); + } + + /** + * @return list + */ + #[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; + } +}; +?> + +
    +

    {{ $message }}

    + + @if ($this->machine->counters !== []) +
    +

    {{ __('machines.maintenance.counters') }}

    +
      + @foreach ($this->machine->counters as $counter) +
    • +
      +

      {{ $counter->name }}

      +

      + @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 +

      +
      +
      +
      + +
      + + +
    • + @endforeach +
    +
    + @endif + +
    +

    {{ __('machines.maintenance.items') }}

    + @can('machines.manage') +

    + @endcan + + @if ($this->items === []) +

    {{ __('machines.maintenance.none') }}

    + @else +
      + @foreach ($this->items as $item) +
    • +
      +
      +

      {{ $item->name }}@unless ($item->isActive) ({{ __('machines.index.inactive') }})@endunless

      +

      +

      +

      {{ __('machines.maintenance.interval_text', ['interval' => $this->intervalText($item)]) }}

      +

      + @if ($item->lastPerformedAt === null) + {{ __('machines.maintenance.never_done') }} + @else + {{ __('machines.maintenance.last_done', ['at' => $this->dateLabel($item->lastPerformedAt), 'name' => $item->lastPerformedByName]) }} + @endif +

      +
      + @can('machines.manage') + {{ __('machines.maintenance.edit_named', ['name' => $item->name]) }} + @endcan +
      + + @if ($item->instructions !== null) +
      + {{ __('machines.maintenance.instructions') }} +

      {{ $item->instructions }}

      +
      + @endif + + @if ($item->isActive) + @if ($recordingItemId === $item->id) +
      + @if ($item->counterId !== null) +
      + +
      + @endif +
      + +
      + + + + @else + + @endif + @endif +
    • + @endforeach +
    + @endif +
    + +
    +

    {{ __('machines.maintenance.history') }}

    +
    + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->items as $item) + + @endforeach + + + +
    + +

    {{ trans_choice('machines.maintenance.history_count', count($this->history), ['count' => count($this->history)]) }}

    + + @if ($this->history !== []) +
      + @foreach ($this->history as $record) +
    • +
      +

      {{ $record->itemName }} · {{ $this->dateLabel($record->performedAt) }} · {{ $record->userName }}

      + @if ($record->readingMilli !== null) +

      {{ __('machines.maintenance.reading_was', ['reading' => $this->reading($record->readingMilli)]) }}

      + @endif + @if ($record->note !== null) +

      {{ $record->note }}

      + @endif + @if ($record->cancelledAt !== null) +

      +

      + @endif +
      + @if ($record->cancelledAt === null) + @can('machines.manage') + + @endcan + @endif +
    • + @endforeach +
    + @endif +
    + + @can('machines.manage') + +

    {{ __('machines.maintenance.cancel_text') }}

    + + + + +
    + @endcan +
    diff --git a/app/Modules/Machines/Presentation/Livewire/⚡show.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡show.blade.php index 8006179..c3d4c9e 100644 --- a/app/Modules/Machines/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Machines/Presentation/Livewire/⚡show.blade.php @@ -383,4 +383,6 @@ new class extends Component @endif + + diff --git a/app/Modules/Machines/Presentation/Routes/web.php b/app/Modules/Machines/Presentation/Routes/web.php index d994628..1f6ae29 100644 --- a/app/Modules/Machines/Presentation/Routes/web.php +++ b/app/Modules/Machines/Presentation/Routes/web.php @@ -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'); diff --git a/app/Modules/Notifications/Application/UseCases/NotifyMaintenanceDue.php b/app/Modules/Notifications/Application/UseCases/NotifyMaintenanceDue.php new file mode 100644 index 0000000..f4d811e --- /dev/null +++ b/app/Modules/Notifications/Application/UseCases/NotifyMaintenanceDue.php @@ -0,0 +1,58 @@ +clock->now(); + + return $this->transactions->run(function () use ($now): int { + $added = 0; + + foreach ($this->maintenance->due() as $item) { + if ($item->responsibleUserId === null) { + continue; + } + + $notification = NewNotification::maintenanceDue($item->responsibleUserId, $item->id, $item->lastRecordId, $item->level->value, [ + 'machine_id' => $item->machineId, + 'machine' => $item->machineName, + 'item' => $item->name, + 'level' => $item->level->value, + ], $now); + + if ($this->notifications->addIfNew($notification)) { + $added++; + } + } + + return $added; + }); + } +} diff --git a/app/Modules/Notifications/Domain/Enums/NotificationType.php b/app/Modules/Notifications/Domain/Enums/NotificationType.php index 1f5cdab..8c5c9d6 100644 --- a/app/Modules/Notifications/Domain/Enums/NotificationType.php +++ b/app/Modules/Notifications/Domain/Enums/NotificationType.php @@ -24,4 +24,9 @@ enum NotificationType: string * Someone else gave the user a role on a customer job. */ case JobAssigned = 'job_assigned'; + + /** + * Maintenance of a machine the user is responsible for is coming up or late. + */ + case MaintenanceDue = 'maintenance_due'; } diff --git a/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php b/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php index f6f3a38..e7d951f 100644 --- a/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php +++ b/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php @@ -31,6 +31,17 @@ final readonly class NewNotification return new self($userId, NotificationType::TaskStartsSoon, $params, "task_starts:{$taskId}:{$startsOn}:{$userId}", $at); } + /** + * One notification per maintenance need: the item, its last maintenance + * and the level (coming up or late). + * + * @param array $params + */ + public static function maintenanceDue(int $userId, int $itemId, ?int $lastRecordId, string $level, array $params, DateTimeImmutable $at): self + { + return new self($userId, NotificationType::MaintenanceDue, $params, 'maintenance:'.$itemId.':'.($lastRecordId ?? 'start').':'.$level.':'.$userId, $at); + } + /** * Each assignment is its own notification: one removed and added again * is told again. diff --git a/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php b/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php index b1eef4b..2915a73 100644 --- a/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php +++ b/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php @@ -9,6 +9,7 @@ use App\Modules\Notifications\Application\UseCases\NotifyAddedPeople; use App\Modules\Notifications\Domain\Contracts\NotificationRepository; use App\Modules\Notifications\Infrastructure\Persistence\Repositories\EloquentNotificationQueries; use App\Modules\Notifications\Infrastructure\Persistence\Repositories\EloquentNotificationRepository; +use App\Modules\Notifications\Presentation\Console\NotifyMaintenanceDueCommand; use App\Modules\Notifications\Presentation\Console\NotifyTasksStartingSoonCommand; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; @@ -39,7 +40,7 @@ class NotificationsServiceProvider extends ServiceProvider Event::listen(PeopleAddedToJob::class, fn (PeopleAddedToJob $event) => app(NotifyAddedPeople::class)->forJob($event)); if ($this->app->runningInConsole()) { - $this->commands([NotifyTasksStartingSoonCommand::class]); + $this->commands([NotifyTasksStartingSoonCommand::class, NotifyMaintenanceDueCommand::class]); } } } diff --git a/app/Modules/Notifications/Presentation/Console/NotifyMaintenanceDueCommand.php b/app/Modules/Notifications/Presentation/Console/NotifyMaintenanceDueCommand.php new file mode 100644 index 0000000..02b1d3a --- /dev/null +++ b/app/Modules/Notifications/Presentation/Console/NotifyMaintenanceDueCommand.php @@ -0,0 +1,22 @@ +execute(); + + $this->components->info("{$added} notifications added."); + + return self::SUCCESS; + } +} diff --git a/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php b/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php index 5d0b868..7c9e03c 100644 --- a/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php +++ b/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php @@ -76,6 +76,10 @@ new class extends Component 'job' => (string) $notification->params['job_name'], 'roles' => $this->roleList((string) $notification->params['roles']), ]), + NotificationType::MaintenanceDue => __('notifications.types.maintenance_due.'.$notification->params['level'], [ + 'machine' => (string) $notification->params['machine'], + 'item' => (string) $notification->params['item'], + ]), }; } @@ -84,6 +88,7 @@ new class extends Component return match ($notification->type) { NotificationType::TaskStartsSoon, NotificationType::TaskAssigned => route('jobs.show', (int) $notification->params['job_id']).'#task-'.$notification->params['task_id'], NotificationType::JobAssigned => route('jobs.show', (int) $notification->params['job_id']), + NotificationType::MaintenanceDue => route('machines.show', (int) $notification->params['machine_id']).'#maintenance-heading', }; } diff --git a/database/migrations/2026_11_26_144417_create_maintenance_tables.php b/database/migrations/2026_11_26_144417_create_maintenance_tables.php new file mode 100644 index 0000000..7303eb1 --- /dev/null +++ b/database/migrations/2026_11_26_144417_create_maintenance_tables.php @@ -0,0 +1,66 @@ +id(); + $table->foreignId('machine_id')->constrained()->cascadeOnDelete(); + $table->string('name', 150); + $table->foreignId('machine_counter_id')->nullable()->constrained()->nullOnDelete(); + $table->bigInteger('interval_milli')->nullable(); + $table->bigInteger('counter_baseline_milli')->default(0); + $table->string('period', 10)->nullable(); + $table->unsignedSmallInteger('period_count')->default(1); + $table->date('starts_on'); + $table->unsignedTinyInteger('warning_percent')->default(90); + $table->text('instructions')->nullable(); + $table->foreignId('stock_item_id')->nullable()->constrained()->restrictOnDelete(); + $table->bigInteger('stock_quantity_milli')->nullable(); + $table->boolean('is_active')->default(true); + $table->timestamps(); + }); + + Schema::create('maintenance_records', function (Blueprint $table) { + $table->id(); + $table->foreignId('maintenance_item_id')->constrained()->cascadeOnDelete(); + $table->timestamp('performed_at'); + $table->foreignId('user_id')->constrained()->restrictOnDelete(); + $table->bigInteger('counter_reading_milli')->nullable(); + $table->text('note')->nullable(); + $table->timestamp('cancelled_at')->nullable(); + $table->foreignId('cancelled_by')->nullable()->constrained('users')->restrictOnDelete(); + $table->timestamps(); + + $table->index(['maintenance_item_id', 'performed_at']); + }); + + Schema::table('stock_movements', function (Blueprint $table) { + $table->foreign('maintenance_record_id', 'stock_movements_maintenance_foreign')->references('id')->on('maintenance_records')->restrictOnDelete(); + }); + } + + public function down(): void + { + // SQLite (tests) cannot drop a foreign key; there the table is dropped by the earlier migration's rollback. + if (Schema::getConnection()->getDriverName() !== 'sqlite') { + Schema::table('stock_movements', function (Blueprint $table) { + $table->dropForeign('stock_movements_maintenance_foreign'); + }); + } + + Schema::dropIfExists('maintenance_records'); + Schema::dropIfExists('maintenance_items'); + } +}; diff --git a/lang/en/dashboard.php b/lang/en/dashboard.php index c228524..e601afc 100644 --- a/lang/en/dashboard.php +++ b/lang/en/dashboard.php @@ -50,6 +50,9 @@ return [ ], 'todo' => [ + 'maintenance' => '{1} 1 machine maintenance late|[2,*] :count machine maintenances late', + 'maintenance_line' => ':machine: :item', + 'stock' => '{1} 1 stock item to order|[2,*] :count stock items to order', 'title' => 'To do', 'approvals' => '{0} No hours waiting for approval|{1} One person has hours waiting for approval|[2,*] :count people have hours waiting for approval', 'approval_line' => ':name: :hours h over :weeks weeks', diff --git a/lang/en/machines.php b/lang/en/machines.php index 4fec7e8..96b43a7 100644 --- a/lang/en/machines.php +++ b/lang/en/machines.php @@ -125,6 +125,101 @@ return [ 'no_machines' => 'There are no machines in use in the task\'s service unit.', ], + 'maintenance' => [ + 'create_title' => 'New maintenance item', + 'edit_title' => 'Edit maintenance item', + 'name' => 'Name', + 'name_hint' => 'E.g. emptying the waste ink tank, cleaning the print head, changing the blade.', + 'counter_interval' => 'Counter-based interval', + 'counter_interval_hint' => 'Maintenance is due when the counter has grown by the interval since the last maintenance. Optional.', + 'no_counters' => 'The machine has no counters. Add counters on the machine form.', + 'counter' => 'Counter', + 'no_counter' => 'No counter-based interval', + 'interval' => 'Interval in the counter unit', + 'interval_hint' => 'E.g. 20000.', + 'time_interval' => 'Time-based interval', + 'time_interval_hint' => 'Daily, weekly, monthly or yearly maintenance. Optional; a machine may have several items with different intervals. With a counter interval too, maintenance is due when either comes first.', + 'period' => 'Interval', + 'no_period' => 'No time-based interval', + 'periods' => [ + 'day' => 'Daily maintenance', + 'week' => 'Weekly maintenance', + 'month' => 'Monthly maintenance', + 'year' => 'Yearly maintenance', + ], + 'period_count' => 'Every … periods', + 'period_count_hint' => '1 = every day / week / month / year, 2 = every other and so on.', + 'warning' => 'Advance warning (% of the interval)', + 'warning_hint' => 'Maintenance shows as coming up when this share of the interval has passed. No advance warning for daily maintenance.', + 'instructions' => 'Instructions', + 'stock_item' => 'Stock item used at maintenance', + 'stock_item_hint' => 'Optional, e.g. a spare drum. Recorded as used at every maintenance.', + 'no_stock_item' => 'No item', + 'stock_quantity' => 'Quantity per maintenance', + 'saved' => 'Maintenance item :name saved.', + 'activated' => 'The maintenance item was taken into use.', + 'deactivated' => 'The maintenance item was taken out of use. Its history is kept.', + 'counters' => 'Counters', + 'no_reading' => 'No readings.', + 'latest_reading' => 'Latest reading :reading :unit (:at).', + 'new_reading' => 'New reading (:unit)', + 'save_reading' => 'Record reading', + 'save_reading_named' => 'Record reading: :counter', + 'reading_saved' => 'Reading :reading :unit of :counter recorded.', + 'items' => 'Maintenance', + 'add' => 'New maintenance item', + 'none' => 'The machine has no maintenance items.', + 'levels' => [ + 'ok' => 'In order', + 'approaching' => 'Maintenance coming up', + 'overdue' => 'Maintenance late', + ], + 'remaining' => ':amount :unit left', + 'over' => ':amount :unit over', + 'due' => 'due :date', + 'was_due' => 'was due :date', + 'every_amount' => ':amount :unit (:counter)', + 'every_period' => [ + 'day' => '{1} every day|[2,*] every :count days', + 'week' => '{1} every week|[2,*] every :count weeks', + 'month' => '{1} every month|[2,*] every :count months', + 'year' => '{1} every year|[2,*] every :count years', + ], + 'or' => ' or ', + 'interval_text' => 'Interval: :interval', + 'never_done' => 'No maintenance yet.', + 'last_done' => 'Last maintained :at (:name).', + 'edit_named' => 'Edit: :name', + 'done' => 'Maintenance done', + 'done_named' => 'Maintenance done: :name', + 'reading_at' => 'Reading (:counter)', + 'note' => 'Note', + 'confirm_done' => 'Record maintenance', + 'recorded' => 'Maintenance :name recorded.', + 'stock_not_recorded' => 'The stock item of the maintenance could not be recorded as used.', + 'history' => 'Maintenance history', + 'history_item' => 'Maintenance item', + 'all_items' => 'All maintenance items', + 'from' => 'From', + 'to' => 'To', + 'history_count' => '{0} No maintenance.|{1} 1 maintenance.|[2,*] :count maintenances.', + 'reading_was' => 'Reading :reading', + 'cancelled_by' => 'Cancelled :at (:name)', + 'cancel' => 'Mark as cancelled', + 'cancel_named' => 'Mark as cancelled: :name :at', + 'cancel_title' => 'Mark the maintenance as cancelled?', + 'cancel_text' => 'The record stays in the history marked as cancelled, and it no longer restarts the interval.', + 'cancelled' => 'Maintenance :name marked as cancelled.', + 'errors' => [ + 'needs_interval' => 'Give a counter-based interval, a time-based interval or both.', + 'invalid' => 'Check the name (1–150 characters), the interval and the advance warning.', + 'amount' => 'Enter an amount greater than zero, at most three decimals.', + 'counter' => 'Choose a counter of the machine.', + 'period_count' => 'Enter the period as a whole number 1–365.', + 'warning' => 'Enter the advance warning as a percentage 1–99.', + 'reading' => 'Enter a reading of zero or more, at most three decimals.', + ], + ], 'errors' => [ 'name' => 'Enter a name (1–150 characters).', 'name_taken' => 'The name is already in use.', diff --git a/lang/en/notifications.php b/lang/en/notifications.php index e65d7a9..1a0fed6 100644 --- a/lang/en/notifications.php +++ b/lang/en/notifications.php @@ -14,6 +14,10 @@ return [ 'member' => 'You were made a member of task :task (job :number :job).', ], 'job_assigned' => 'You were made :roles of job :number :job.', + 'maintenance_due' => [ + 'approaching' => 'Maintenance :item of :machine is coming up.', + 'overdue' => 'Maintenance :item of :machine is late.', + ], ], 'job_roles' => [ 'responsible' => 'the responsible person', diff --git a/lang/fi/dashboard.php b/lang/fi/dashboard.php index 47a990d..9bd5e67 100644 --- a/lang/fi/dashboard.php +++ b/lang/fi/dashboard.php @@ -50,6 +50,9 @@ return [ ], 'todo' => [ + 'maintenance' => '{1} 1 konehuolto myöhässä|[2,*] :count konehuoltoa myöhässä', + 'maintenance_line' => ':machine: :item', + 'stock' => '{1} 1 varastonimike tilattavana|[2,*] :count varastonimikettä tilattavana', 'title' => 'Vaatii toimia', 'approvals' => '{0} Ei hyväksymättömiä tunteja|{1} Yhdellä henkilöllä hyväksymättömiä tunteja|[2,*] :count henkilöllä hyväksymättömiä tunteja', 'approval_line' => ':name: :hours h, :weeks viikolta', diff --git a/lang/fi/machines.php b/lang/fi/machines.php index 87f2d84..75b29dd 100644 --- a/lang/fi/machines.php +++ b/lang/fi/machines.php @@ -125,6 +125,101 @@ return [ 'no_machines' => 'Tehtävän palveluyksikössä ei ole käytössä olevia koneita.', ], + 'maintenance' => [ + 'create_title' => 'Uusi huoltokohde', + 'edit_title' => 'Muokkaa huoltokohdetta', + 'name' => 'Nimi', + 'name_hint' => 'Esim. jätemustesäiliön tyhjennys, tulostuspään puhdistus, terän vaihto.', + 'counter_interval' => 'Laskuriin perustuva huoltoväli', + 'counter_interval_hint' => 'Huolto erääntyy, kun laskuri on kasvanut viimeisestä huollosta huoltovälin verran. Vapaaehtoinen.', + 'no_counters' => 'Koneella ei ole laskureita. Lisää laskurit koneen lomakkeella.', + 'counter' => 'Laskuri', + 'no_counter' => 'Ei laskuriin perustuvaa väliä', + 'interval' => 'Huoltoväli laskurin yksikköinä', + 'interval_hint' => 'Esim. 20000.', + 'time_interval' => 'Aikaan perustuva huoltoväli', + 'time_interval_hint' => 'Päivä-, viikko-, kuukausi- tai vuosihuolto. Vapaaehtoinen; koneella voi olla useita eri välein huollettavia kohteita. Jos myös laskuriväli on annettu, huolto erääntyy kumman tahansa täyttyessä ensin.', + 'period' => 'Huoltoväli', + 'no_period' => 'Ei aikaan perustuvaa väliä', + 'periods' => [ + 'day' => 'Päivähuolto', + 'week' => 'Viikkohuolto', + 'month' => 'Kuukausihuolto', + 'year' => 'Vuosihuolto', + ], + 'period_count' => 'Joka … jakso', + 'period_count_hint' => '1 = joka päivä / viikko / kuukausi / vuosi, 2 = joka toinen jne.', + 'warning' => 'Ennakkovaroitus (% välistä)', + 'warning_hint' => 'Huolto näytetään lähestyvänä, kun tämä osuus välistä on kulunut. Päivähuollolla ei ennakkovaroitusta.', + 'instructions' => 'Ohje', + 'stock_item' => 'Huollossa käytettävä varastonimike', + 'stock_item_hint' => 'Vapaaehtoinen, esim. vaihtorumpu. Kirjataan käytetyksi jokaisessa huollossa.', + 'no_stock_item' => 'Ei nimikettä', + 'stock_quantity' => 'Määrä huoltoa kohden', + 'saved' => 'Huoltokohde :name tallennettu.', + 'activated' => 'Huoltokohde otettu käyttöön.', + 'deactivated' => 'Huoltokohde poistettu käytöstä. Sen historia säilyy.', + 'counters' => 'Laskurit', + 'no_reading' => 'Ei lukemia.', + 'latest_reading' => 'Viimeisin lukema :reading :unit (:at).', + 'new_reading' => 'Uusi lukema (:unit)', + 'save_reading' => 'Kirjaa lukema', + 'save_reading_named' => 'Kirjaa lukema: :counter', + 'reading_saved' => 'Laskurin :counter lukema :reading :unit kirjattu.', + 'items' => 'Huollot', + 'add' => 'Uusi huoltokohde', + 'none' => 'Koneelle ei ole huoltokohteita.', + 'levels' => [ + 'ok' => 'Kunnossa', + 'approaching' => 'Huolto lähestyy', + 'overdue' => 'Huolto myöhässä', + ], + 'remaining' => 'jäljellä :amount :unit', + 'over' => 'yli :amount :unit', + 'due' => 'erääntyy :date', + 'was_due' => 'erääntyi :date', + 'every_amount' => ':amount :unit (:counter)', + 'every_period' => [ + 'day' => '{1} joka päivä|[2,*] joka :count. päivä', + 'week' => '{1} joka viikko|[2,*] joka :count. viikko', + 'month' => '{1} joka kuukausi|[2,*] joka :count. kuukausi', + 'year' => '{1} joka vuosi|[2,*] joka :count. vuosi', + ], + 'or' => ' tai ', + 'interval_text' => 'Huoltoväli: :interval', + 'never_done' => 'Ei vielä huoltoja.', + 'last_done' => 'Viimeksi huollettu :at (:name).', + 'edit_named' => 'Muokkaa: :name', + 'done' => 'Huolto tehty', + 'done_named' => 'Huolto tehty: :name', + 'reading_at' => 'Lukema (:counter)', + 'note' => 'Huomautus', + 'confirm_done' => 'Kirjaa huolto', + 'recorded' => 'Huolto :name kirjattu.', + 'stock_not_recorded' => 'Huollon varastonimikettä ei voitu kirjata käytetyksi.', + 'history' => 'Huoltohistoria', + 'history_item' => 'Huoltokohde', + 'all_items' => 'Kaikki huoltokohteet', + 'from' => 'Alkaen', + 'to' => 'Päättyen', + 'history_count' => '{0} Ei huoltoja.|{1} 1 huolto.|[2,*] :count huoltoa.', + 'reading_was' => 'Lukema :reading', + 'cancelled_by' => 'Peruttu :at (:name)', + 'cancel' => 'Merkitse perutuksi', + 'cancel_named' => 'Merkitse perutuksi: :name :at', + 'cancel_title' => 'Merkitäänkö huolto perutuksi?', + 'cancel_text' => 'Huoltokirjaus jää historiaan perutuksi merkittynä, eikä se enää nollaa huoltovälin kertymää.', + 'cancelled' => 'Huolto :name merkitty perutuksi.', + 'errors' => [ + 'needs_interval' => 'Anna laskuriin perustuva huoltoväli, aikaan perustuva huoltoväli tai molemmat.', + 'invalid' => 'Tarkista nimi (1–150 merkkiä), huoltoväli ja ennakkovaroitus.', + 'amount' => 'Anna määrä nollaa suurempana lukuna, enintään kolme desimaalia.', + 'counter' => 'Valitse koneen laskuri.', + 'period_count' => 'Anna jakso kokonaislukuna 1–365.', + 'warning' => 'Anna ennakkovaroitus prosentteina 1–99.', + 'reading' => 'Anna lukema nollana tai suurempana lukuna, enintään kolme desimaalia.', + ], + ], 'errors' => [ 'name' => 'Anna nimi (1–150 merkkiä).', 'name_taken' => 'Nimi on jo käytössä.', diff --git a/lang/fi/notifications.php b/lang/fi/notifications.php index f1ba824..e076a3d 100644 --- a/lang/fi/notifications.php +++ b/lang/fi/notifications.php @@ -14,6 +14,10 @@ return [ 'member' => 'Sinut lisättiin tehtävän :task jäseneksi (työ :number :job).', ], 'job_assigned' => 'Sinut lisättiin työn :number :job :roles.', + 'maintenance_due' => [ + 'approaching' => 'Koneen :machine huolto :item lähestyy.', + 'overdue' => 'Koneen :machine huolto :item on myöhässä.', + ], ], 'job_roles' => [ 'responsible' => 'vastuuhenkilöksi', diff --git a/routes/console.php b/routes/console.php index cd3367c..e305f11 100644 --- a/routes/console.php +++ b/routes/console.php @@ -13,3 +13,9 @@ Schedule::command('notifications:task-starts') ->dailyAt('14:00') ->timezone((string) config('app.business_timezone')) ->onOneServer(); + +// Maintenance coming up or late: notify each machine's responsible person in the morning. +Schedule::command('notifications:maintenance-due') + ->dailyAt('07:00') + ->timezone((string) config('app.business_timezone')) + ->onOneServer(); diff --git a/tests/Browser/MachinesAccessibilityTest.php b/tests/Browser/MachinesAccessibilityTest.php index 3bf38c7..15a4c39 100644 --- a/tests/Browser/MachinesAccessibilityTest.php +++ b/tests/Browser/MachinesAccessibilityTest.php @@ -6,7 +6,9 @@ use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; use App\Modules\Machines\Application\UseCases\MachineWorkList; +use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel; use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel; +use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; @@ -30,6 +32,12 @@ beforeEach(function () { 'description' => 'Kaksi kappaletta', ]); app(MachineWorkList::class)->planTask($this->task->id, $this->machine->id, null); + + $counter = MachineCounterModel::query()->create(['machine_id' => $this->machine->id, 'name' => 'Tulosteet', 'unit' => 'piece', 'sort_order' => 1]); + MaintenanceItemModel::query()->create([ + 'machine_id' => $this->machine->id, 'name' => 'Pään puhdistus', 'machine_counter_id' => $counter->id, 'interval_milli' => 1_000_000, + 'period' => 'day', 'period_count' => 1, 'starts_on' => now()->subDays(2)->toDateString(), 'warning_percent' => 90, + ]); }); it('has no accessibility issues on the machine pages', function (string $page, string $device, string $colorScheme) { @@ -38,6 +46,7 @@ it('has no accessibility issues on the machine pages', function (string $page, s 'show' => route('machines.show', $this->machine->id), 'form' => route('machines.edit', $this->machine->id), 'job' => route('jobs.show', $this->job->id).'#task-'.$this->task->id, + 'maintenance' => route('machines.maintenance.create', $this->machine->id), }; $visit = visit($url); @@ -47,7 +56,7 @@ it('has no accessibility issues on the machine pages', function (string $page, s $visit->assertSee($page === 'form' ? __('machines.form.edit_title') : 'Suurkuvatulostin') ->assertNoJavaScriptErrors() ->assertNoAccessibilityIssues(level: 2); -})->with(['index', 'show', 'form', 'job'])->with([ +})->with(['index', 'show', 'form', 'job', 'maintenance'])->with([ 'desktop, light' => ['desktop', 'light'], 'desktop, dark' => ['desktop', 'dark'], 'mobile, light' => ['mobile', 'light'], @@ -64,3 +73,14 @@ it('moves a task to another machine with the keyboard from the work list', funct ->assertSee('Tehtävä siirretty koneen Tarraleikkuri työlistalle') ->assertDontSee('Kiiltävä laminointi'); }); + +it('records maintenance done with the keyboard', function () { + visit(route('machines.show', $this->machine->id)) + ->assertSee('Huolto myöhässä') + ->click(__('machines.maintenance.done')) + ->fill('#record-note', 'Puhdistettu') + ->click(__('machines.maintenance.confirm_done')) + ->assertSee('Huolto Pään puhdistus kirjattu.') + ->assertSee('Kunnossa') + ->assertNoAccessibilityIssues(level: 2); +}); diff --git a/tests/Feature/Modules/Machines/MaintenanceTest.php b/tests/Feature/Modules/Machines/MaintenanceTest.php new file mode 100644 index 0000000..7cb3eef --- /dev/null +++ b/tests/Feature/Modules/Machines/MaintenanceTest.php @@ -0,0 +1,122 @@ +travelTo(now()->setTimezone(config('app.business_timezone'))->setTime(10, 0)); + $this->manager = User::factory()->management()->create(['name' => 'Maija Johto']); + $this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']); + + $print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole(); + $print->update(['uses_stock' => true]); + $this->machine = MachineModel::factory()->inUnits([$print->id])->create(['name' => 'Suurkuvatulostin', 'responsible_user_id' => $this->employee->id]); + $this->prints = MachineCounterModel::query()->create(['machine_id' => $this->machine->id, 'name' => 'Tulosteet', 'unit' => 'piece', 'sort_order' => 1]); + $this->drum = StockItemModel::factory()->create(['name' => 'Vaihtorumpu']); +}); + +it('adds maintenance items with a counter interval, time intervals or both, and needs one of them', function () { + $this->actingAs($this->manager); + + Livewire::test('machines::maintenance-item-form', ['machine' => $this->machine->id]) + ->set('name', 'Pään puhdistus') + ->call('save') + ->assertHasErrors('period') + ->set('period', 'day') + ->call('save') + ->assertHasNoErrors(); + + Livewire::test('machines::maintenance-item-form', ['machine' => $this->machine->id]) + ->set('name', 'Rummun vaihto') + ->set('counterId', (string) $this->prints->id) + ->set('interval', '20000') + ->set('period', 'month') + ->set('periodCount', '6') + ->set('stockItemId', (string) $this->drum->id) + ->call('save') + ->assertHasNoErrors(); + + expect(MaintenanceItemModel::query()->where('name', 'Rummun vaihto')->sole()->only(['interval_milli', 'period_count', 'stock_quantity_milli'])) + ->toBe(['interval_milli' => 20_000_000, 'period_count' => 6, 'stock_quantity_milli' => 1_000]); + + $this->actingAs($this->employee); + $this->get(route('machines.maintenance.create', $this->machine->id))->assertForbidden(); +}); + +it('shows a maintenance request when due and starts the interval again with a maintenance record that uses the stock item', function () { + $item = MaintenanceItemModel::query()->create([ + 'machine_id' => $this->machine->id, 'name' => 'Rummun vaihto', 'machine_counter_id' => $this->prints->id, 'interval_milli' => 20_000_000, + 'counter_baseline_milli' => 0, 'period' => 'week', 'period_count' => 1, 'starts_on' => now()->toDateString(), 'warning_percent' => 90, + 'stock_item_id' => $this->drum->id, 'stock_quantity_milli' => 1_000, + ]); + $this->actingAs($this->employee); + + Livewire::test('machines::maintenance', ['machineId' => $this->machine->id]) + ->assertSee('Kunnossa') + ->set('readings.'.$this->prints->id, '19 000') + ->call('saveReading', $this->prints->id) + ->assertSee('Huolto lähestyy') + ->assertSee("jäljellä 1\u{00A0}000 kpl", false); + + $this->travel(8)->days(); + + Livewire::test('machines::maintenance', ['machineId' => $this->machine->id]) + ->assertSee('Huolto myöhässä') + ->call('startRecord', $item->id) + ->assertSet('recordReading', '19000') + ->set('recordReading', '19500') + ->set('recordNote', 'Rumpu vaihdettu') + ->call('record') + ->assertSet('message', 'Huolto Rummun vaihto kirjattu.') + ->assertSee('Kunnossa') + ->assertSee('Rumpu vaihdettu'); + + $record = MaintenanceRecordModel::query()->sole(); + $use = StockMovementModel::query()->sole(); + + expect($record->counter_reading_milli)->toBe(19_500_000) + ->and($use->only(['stock_item_id', 'machine_id', 'maintenance_record_id', 'quantity_milli'])) + ->toBe(['stock_item_id' => $this->drum->id, 'machine_id' => $this->machine->id, 'maintenance_record_id' => $record->id, 'quantity_milli' => -1_000]); + + Livewire::test('machines::maintenance', ['machineId' => $this->machine->id])->call('confirmCancel', $record->id)->assertForbidden(); + + $this->actingAs($this->manager); + Livewire::test('machines::maintenance', ['machineId' => $this->machine->id]) + ->call('confirmCancel', $record->id) + ->call('cancelRecord') + ->assertSee('Peruttu') + ->assertSee('Huolto myöhässä'); +}); + +it('notifies the responsible person of a maintenance request once', function () { + MaintenanceItemModel::query()->create([ + 'machine_id' => $this->machine->id, 'name' => 'Pään puhdistus', 'period' => 'day', 'period_count' => 1, + 'starts_on' => now()->subDay()->toDateString(), 'warning_percent' => 90, + ]); + + $this->artisan('notifications:maintenance-due')->assertSuccessful(); + $this->artisan('notifications:maintenance-due')->assertSuccessful(); + + $notification = NotificationModel::query()->sole(); + + expect($notification->user_id)->toBe($this->employee->id) + ->and($notification->type->value)->toBe('maintenance_due'); + + $this->actingAs($this->employee); + Livewire::test('notifications::bell')->assertSee('Koneen Suurkuvatulostin huolto Pään puhdistus on myöhässä.'); + + $this->actingAs($this->manager); + $this->get(route('home'))->assertOk(); + Livewire::test('dashboard::management')->assertSee('1 konehuolto myöhässä')->assertSee('Suurkuvatulostin: Pään puhdistus'); +}); diff --git a/tests/Unit/Modules/Machines/MaintenanceStatusTest.php b/tests/Unit/Modules/Machines/MaintenanceStatusTest.php new file mode 100644 index 0000000..5eb1573 --- /dev/null +++ b/tests/Unit/Modules/Machines/MaintenanceStatusTest.php @@ -0,0 +1,38 @@ + new DateTimeImmutable($date); + +it('counts a counter interval from the reading at the last maintenance', function () use ($day) { + $state = fn (int $reading) => MaintenanceStatus::evaluate(20_000_000, 100_000_000, $reading, null, 1, $day('2026-11-01'), 90, $day('2026-11-26')); + + expect($state(110_000_000)->level)->toBe(MaintenanceLevel::Ok) + ->and($state(110_000_000)->remainingMilli)->toBe(10_000_000) + ->and($state(118_000_000)->level)->toBe(MaintenanceLevel::Approaching) + ->and($state(120_000_000)->level)->toBe(MaintenanceLevel::Overdue) + ->and($state(121_000_000)->remainingMilli)->toBe(-1_000_000); +}); + +it('makes a daily, weekly, monthly or yearly maintenance due after its periods', function (MaintenancePeriod $period, int $count, string $since, string $due) use ($day) { + expect(MaintenanceStatus::evaluate(null, 0, null, $period, $count, $day($since), 90, $day($since))->dueOn)->toBe($due); +})->with([ + 'daily' => [MaintenancePeriod::Day, 1, '2026-11-26', '2026-11-27'], + 'every other week' => [MaintenancePeriod::Week, 2, '2026-11-26', '2026-12-10'], + 'monthly from the 31st' => [MaintenancePeriod::Month, 1, '2026-01-31', '2026-02-28'], + 'yearly from 29 February' => [MaintenancePeriod::Year, 1, '2028-02-29', '2029-02-28'], +]); + +it('warns before a time interval but not before daily maintenance, and takes the worse of two intervals', function () use ($day) { + $weekly = fn (string $today) => MaintenanceStatus::evaluate(null, 0, null, MaintenancePeriod::Week, 1, $day('2026-11-16'), 80, $day($today))->level; + $daily = fn (string $today) => MaintenanceStatus::evaluate(null, 0, null, MaintenancePeriod::Day, 1, $day('2026-11-26'), 50, $day($today))->level; + + expect($weekly('2026-11-20'))->toBe(MaintenanceLevel::Ok) + ->and($weekly('2026-11-22'))->toBe(MaintenanceLevel::Approaching) + ->and($weekly('2026-11-23'))->toBe(MaintenanceLevel::Overdue) + ->and($daily('2026-11-26'))->toBe(MaintenanceLevel::Ok) + ->and($daily('2026-11-27'))->toBe(MaintenanceLevel::Overdue) + ->and(MaintenanceStatus::evaluate(1_000, 0, 100, MaintenancePeriod::Month, 1, $day('2026-10-01'), 90, $day('2026-11-02'))->level)->toBe(MaintenanceLevel::Overdue); +});