Give the machine console its own session with PIN sign-in, make counters cumulative

The console under console/ has its own session cookie and console guard
(UseConsoleSession), so signing out or changing user there leaves the
normal interface alone. Links open it in a new window through a one-time
handoff key; a signed-out console asks for a PIN code or password on its
own login page. Users set their 4-6 digit PIN on the profile's PIN page,
and the console's change user dialog takes it on a keypad; five wrong
PINs lock PIN sign-in for 15 minutes.

Machine counters are cumulative: users record how much a job used and it
is added to the latest reading. A maintenance record restarts the whole
counter interval from the reading at the record.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-29 09:58:11 +02:00
co-authored by Claude Sonnet 5.5
parent 87e38260dc
commit 32c33e2a64
55 changed files with 1660 additions and 194 deletions
@@ -24,7 +24,7 @@ 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
* management; counter usage 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.
@@ -98,50 +98,52 @@ final class MachineMaintenance
}
/**
* Records a counter's reading, e.g. the machine's own total counter.
* Records how much of a counter one job used (spec 19.5): counters are
* cumulative, so the usage is added to the counter's latest reading.
*
* @return int The counter's new reading.
*
* @throws CounterNotFound
* @throws InvalidReading
*/
public function recordReading(int $counterId, string $reading, int $actorUserId): int
public function recordUsage(int $counterId, string $usage, int $actorUserId): int
{
$milli = Reading::parse($reading) ?? throw new InvalidReading;
$usageMilli = Reading::parse($usage);
$this->transactions->run(function () use ($counterId, $milli, $actorUserId): void {
if ($usageMilli === null || $usageMilli <= 0) {
throw new InvalidReading;
}
return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int {
$this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound;
$this->maintenance->addReading($counterId, $milli, $actorUserId, $this->clock->now());
});
$reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli;
$this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now());
return $milli;
return $reading;
});
}
/**
* Records maintenance done (Huolto tehty) with the counter's reading
* (the latest one when not given) and uses up the item's stock item.
* Records maintenance done (Huolto tehty) at the counter's latest
* reading and uses up the item's stock item. This resets the item: the
* whole counter interval is left again, counted from this reading, and
* the time interval starts again from today.
*
* @return array{recordId: int, stockRecorded: bool}
*
* @throws MaintenanceItemNotFound
* @throws InvalidReading
*/
public function recordMaintenance(int $itemId, int $actorUserId, string $reading = '', ?string $note = null): array
public function recordMaintenance(int $itemId, int $actorUserId, ?string $note = null): array
{
$readingMilli = Reading::parse($reading);
$note = $note === null ? '' : trim($note);
return $this->transactions->run(function () use ($itemId, $actorUserId, $readingMilli, $note): array {
return $this->transactions->run(function () use ($itemId, $actorUserId, $note): array {
$item = $this->maintenance->findItem($itemId) ?? throw new MaintenanceItemNotFound;
$now = $this->clock->now();
$readingMilli = $item->counterId() === null
? null
: ($this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli());
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));
$recordId = $this->maintenance->addRecord($itemId, $this->clock->now(), $actorUserId, $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000));
$stockRecorded = $item->stockItemId() === null
|| $this->materials->use($item->stockItemId(), (int) $item->stockQuantityMilli(), $item->machineId(), $recordId, $actorUserId);
@@ -12,7 +12,8 @@ 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
* latest reading minus its reading at the last maintenance, so a
* maintenance starts the whole interval again; 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.
@@ -2,7 +2,9 @@
namespace App\Modules\Machines\Presentation\Livewire\Concerns;
use App\Modules\Machines\Application\DTOs\CounterSummary;
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
use App\Modules\Machines\Domain\ValueObjects\Reading;
/**
* Texts of a maintenance item's state, shared by the machine page and the
@@ -68,4 +70,17 @@ trait DescribesMaintenance
return implode(__('machines.maintenance.or'), $parts);
}
/**
* E.g. "Laskuriin Tulosteet lisätty 350 kpl, laskuri nyt 20 350 kpl."
*/
public function usageSaved(CounterSummary $counter, string $usage, int $readingMilli): string
{
return __('machines.maintenance.usage_saved', [
'counter' => $counter->name,
'usage' => $this->reading((int) Reading::parse($usage)),
'reading' => $this->reading($readingMilli),
'unit' => __('machines.counter_units.'.$counter->unit->value),
]);
}
}
@@ -17,6 +17,8 @@ use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
use App\Modules\Machines\Application\DTOs\QueueRow;
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
use App\Modules\Machines\Application\UseCases\MachineWorkList;
use App\Modules\Machines\Domain\Enums\CounterUnit;
use App\Modules\Machines\Domain\ValueObjects\Reading;
use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
@@ -36,8 +38,9 @@ use Livewire\Component;
* for the tablet or touch screen next to a machine. It shows today's work
* list (late rows of earlier days included; the next day can be viewed),
* lets the user start and finish tasks, record the material used with
* large item buttons, frequent items first, record today's hours, counter
* readings and maintenance. Touch targets are at least 44 × 44 px. The
* large item buttons, frequent items first, record today's hours (which
* are suggested as the usage of the machine's hour counters), counter
* usage and maintenance. Touch targets are at least 44 × 44 px. The
* view refreshes itself, and the Refresh button fetches the latest state
* at once and tells what changed.
*/
@@ -85,15 +88,15 @@ new #[Layout('layouts.console')] class extends Component
public string $hours = '';
/**
* Usage typed, by counter id.
*
* @var array<int, string>
*/
public array $readings = [];
public array $usage = [];
#[Locked]
public ?int $recordingItemId = null;
public string $recordReading = '';
#[Locked]
public string $message = '';
@@ -487,35 +490,55 @@ new #[Layout('layouts.console')] class extends Component
}
$this->message = __('machines.console.hours_saved', ['hours' => $this->hours, 'title' => $task->title, 'total' => $total]);
$this->suggestHourCounters($this->hours);
$this->hours = '';
}
public function saveReading(int $counterId, MachineMaintenance $maintenance): void
/**
* Hours just booked on the machine are suggested as the usage of its
* hour counters; nothing is recorded until the user saves the counter.
*/
private function suggestHourCounters(string $hours): void
{
$milli = Reading::parse($hours);
if ($milli === null || $milli <= 0) {
return;
}
foreach ($this->machine->counters as $counter) {
if ($counter->unit === CounterUnit::Hour) {
$this->usage[$counter->id] = str_replace("\u{00A0}", '', $this->reading($milli));
$this->message .= ' '.__('machines.console.hour_suggestion', ['hours' => $this->reading($milli), 'counter' => $counter->name]);
}
}
}
public function saveUsage(int $counterId, MachineMaintenance $maintenance): void
{
$this->authorize('machines.use');
$this->resetErrorBag('readings.'.$counterId);
$this->resetErrorBag('usage.'.$counterId);
$counter = collect($this->machine->counters)->firstWhere('id', $counterId) ?? abort(404);
$usage = $this->usage[$counterId] ?? '';
try {
$milli = $maintenance->recordReading($counterId, $this->readings[$counterId] ?? '', (int) auth()->id());
$milli = $maintenance->recordUsage($counterId, $usage, (int) auth()->id());
} catch (DomainException) {
$this->addError('readings.'.$counterId, __('machines.maintenance.errors.reading'));
$this->addError('usage.'.$counterId, __('machines.maintenance.errors.usage'));
return;
}
$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->maintenance);
$this->message = $this->usageSaved($counter, $usage, $milli);
unset($this->usage[$counterId], $this->machine, $this->maintenance);
}
public function startMaintenance(int $itemId): void
{
$this->authorize('machines.use');
$item = collect($this->maintenance)->firstWhere('id', $itemId) ?? abort(404);
$this->recordingItemId = $itemId;
$this->recordReading = $item->readingMilli === null ? '' : str_replace("\u{00A0}", '', $this->reading($item->readingMilli));
$this->recordingItemId = (collect($this->maintenance)->firstWhere('id', $itemId) ?? abort(404))->id;
$this->js("setTimeout(() => document.getElementById('maintenance-confirm')?.focus())");
}
@@ -526,11 +549,9 @@ new #[Layout('layouts.console')] class extends Component
$item = collect($this->maintenance)->firstWhere('id', $this->recordingItemId) ?? abort(404);
try {
$result = $maintenance->recordMaintenance($item->id, (int) auth()->id(), $item->counterId === null ? '' : $this->recordReading);
$result = $maintenance->recordMaintenance($item->id, (int) auth()->id());
} catch (DomainException) {
$this->addError('recordReading', __('machines.maintenance.errors.reading'));
return;
abort(404);
}
$this->message = __('machines.maintenance.recorded', ['name' => $item->name]).($result['stockRecorded'] ? '' : ' '.__('machines.maintenance.stock_not_recorded'));
@@ -612,14 +633,8 @@ new #[Layout('layouts.console')] class extends Component
<x-icon name="arrow-path" class="size-6" aria-hidden="true" />
{{ __('machines.console.refresh') }}
</button>
<form method="POST" action="{{ route('logout') }}">
@csrf
<input type="hidden" name="return_to" value="{{ route('machines.console', $machine->id) }}">
<button type="submit" class="{{ $touch }} border border-zinc-300 text-zinc-100 hover:bg-zinc-700">
<x-icon name="user-circle" class="size-6" aria-hidden="true" />
{{ __('machines.console.change_user') }}
</button>
</form>
<livewire:users::pin-switch :return-to="route('machines.console', $machine->id)" />
{{-- The normal user interface has a session of its own (Users' UseConsoleSession). --}}
<a href="{{ route('machines.show', $machine->id) }}" class="{{ $touch }} border border-zinc-300 text-zinc-100 hover:bg-zinc-700">
<x-icon name="arrow-left" class="size-6" aria-hidden="true" />
{{ __('machines.console.back') }}
@@ -811,7 +826,7 @@ new #[Layout('layouts.console')] class extends Component
aria-label="{{ __('inventory.task.choose', ['item' => $item->name, 'balance' => $this->quantity($item->balanceMilli, $item->unit)]) }}"
>
@if ($item->hasImage)
<img src="{{ route('inventory.items.image', [$item->id, 'thumbnail']) }}" alt="" class="h-14 w-full rounded object-cover" />
<img src="{{ route('inventory.items.console-image', [$item->id, 'thumbnail']) }}" alt="" class="h-14 w-full rounded object-cover" />
@endif
<span class="font-semibold break-words">{{ $item->name }}</span>
<span class="text-base">{{ $this->quantity($item->balanceMilli, $item->unit) }}</span>
@@ -847,23 +862,24 @@ new #[Layout('layouts.console')] class extends Component
@endcan
</div>
@if ($machine->counters !== [] || $this->maintenance !== [])
<section aria-labelledby="console-maintenance-heading" class="space-y-3">
<h2 id="console-maintenance-heading" class="text-xl font-semibold">{{ __('machines.console.counters_and_maintenance') }}</h2>
<div class="grid gap-3 md:grid-cols-2">
@foreach ($machine->counters as $counter)
<form wire:key="console-counter-{{ $counter->id }}" wire:submit="saveReading({{ $counter->id }})" class="flex flex-wrap items-end gap-2 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600" novalidate>
<form wire:key="console-counter-{{ $counter->id }}" wire:submit="saveUsage({{ $counter->id }})" class="flex flex-wrap items-end gap-2 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600" novalidate>
<div class="min-w-40 flex-1">
<x-input
id="console-reading-{{ $counter->id }}"
wire:model="readings.{{ $counter->id }}"
id="console-usage-{{ $counter->id }}"
wire:model="usage.{{ $counter->id }}"
inputmode="decimal"
:label="$counter->name.' ('.__('machines.counter_units.'.$counter->unit->value).')'"
:label="__('machines.console.usage', ['counter' => $counter->name, 'unit' => __('machines.counter_units.'.$counter->unit->value)])"
:hint="$counter->readingMilli === null ? __('machines.maintenance.no_reading') : __('machines.console.latest', ['reading' => $this->reading($counter->readingMilli)])"
autocomplete="off"
/>
</div>
<button type="submit" class="{{ $primary }}" aria-label="{{ __('machines.maintenance.save_reading_named', ['counter' => $counter->name]) }}">{{ __('machines.maintenance.save_reading') }}</button>
<button type="submit" class="{{ $primary }}" aria-label="{{ __('machines.maintenance.save_usage_named', ['counter' => $counter->name]) }}">{{ __('machines.maintenance.save_usage') }}</button>
</form>
@endforeach
</div>
@@ -878,11 +894,6 @@ new #[Layout('layouts.console')] class extends Component
</p>
@if ($recordingItemId === $item->id)
<form wire:submit="recordMaintenance" class="flex flex-wrap items-end gap-2" novalidate>
@if ($item->counterId !== null)
<div class="w-40">
<x-input id="maintenance-reading" wire:model="recordReading" inputmode="decimal" :label="__('machines.maintenance.reading_at', ['counter' => (string) $item->counterName])" autocomplete="off" />
</div>
@endif
<button type="submit" id="maintenance-confirm" class="{{ $primary }}">{{ __('machines.maintenance.confirm_done') }}</button>
</form>
@else
@@ -895,4 +906,5 @@ new #[Layout('layouts.console')] class extends Component
@endforeach
</ul>
</section>
@endif
</div>
@@ -128,7 +128,7 @@ new class extends Component
@endunless
</p>
</div>
<x-link :href="route('machines.console', $machine->id)" class="text-sm">{{ __('machines.index.console_named', ['name' => $machine->name]) }}</x-link>
<x-link :href="route('console.handoff', ['to' => route('machines.console', $machine->id)])" blank class="text-sm">{{ __('machines.index.console_named', ['name' => $machine->name]) }}<span class="sr-only"> ({{ __('layout.opens_in_new_window') }})</span></x-link>
</li>
@endforeach
</ul>
@@ -19,9 +19,11 @@ 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.
* page (spec 19.5). Anyone using the machine records how much of a
* counter a job used (counters are cumulative) and maintenance done;
* management keeps the items and cancels mistaken records. The history is
* filtered by item and days. Without counters and maintenance items the
* sections are left out, except the add button for management.
*/
new class extends Component
{
@@ -31,17 +33,15 @@ new class extends Component
public int $machineId;
/**
* Readings typed, by counter id.
* Usage typed, by counter id.
*
* @var array<int, string>
*/
public array $readings = [];
public array $usage = [];
#[Locked]
public ?int $recordingItemId = null;
public string $recordReading = '';
public string $recordNote = '';
public string $historyItem = '';
@@ -100,37 +100,36 @@ new class extends Component
}
}
public function saveReading(int $counterId, MachineMaintenance $maintenance): void
public function saveUsage(int $counterId, MachineMaintenance $maintenance): void
{
$this->authorize('machines.use');
$this->resetErrorBag('readings.'.$counterId);
$this->resetErrorBag('usage.'.$counterId);
$counter = collect($this->machine->counters)->firstWhere('id', $counterId) ?? abort(404);
$usage = $this->usage[$counterId] ?? '';
try {
$milli = $maintenance->recordReading($counterId, $this->readings[$counterId] ?? '', (int) auth()->id());
$milli = $maintenance->recordUsage($counterId, $usage, (int) auth()->id());
} catch (InvalidReading) {
$this->addError('readings.'.$counterId, __('machines.maintenance.errors.reading'));
$this->addError('usage.'.$counterId, __('machines.maintenance.errors.usage'));
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);
$this->message = $this->usageSaved($counter, $usage, $milli);
unset($this->usage[$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->recordingItemId = $this->item($itemId)->id;
$this->recordNote = '';
$this->resetErrorBag();
$this->js("setTimeout(() => document.getElementById('record-reading')?.focus() ?? document.getElementById('record-note')?.focus())");
$this->js("setTimeout(() => document.getElementById('record-note')?.focus())");
}
public function cancelRecording(): void
@@ -147,11 +146,7 @@ new class extends Component
$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;
$result = $maintenance->recordMaintenance($item->id, (int) auth()->id(), $this->recordNote);
} catch (MaintenanceItemNotFound) {
abort(404);
}
@@ -231,17 +226,17 @@ new class extends Component
@endif
</p>
</div>
<form wire:submit="saveReading({{ $counter->id }})" class="flex flex-wrap items-end gap-2" novalidate>
<form wire:submit="saveUsage({{ $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 }}"
id="usage-{{ $counter->id }}"
wire:model="usage.{{ $counter->id }}"
inputmode="decimal"
:label="__('machines.maintenance.new_reading', ['unit' => __('machines.counter_units.'.$counter->unit->value)])"
:label="__('machines.maintenance.usage', ['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])" />
<x-button submit sm :text="__('machines.maintenance.save_usage')" :aria-label="__('machines.maintenance.save_usage_named', ['counter' => $counter->name])" />
</form>
</li>
@endforeach
@@ -249,6 +244,9 @@ new class extends Component
</section>
@endif
@php($hasMaintenance = $this->machine->counters !== [] || $this->items !== [])
@if ($hasMaintenance || auth()->user()?->can('machines.manage'))
<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')
@@ -292,11 +290,6 @@ new class extends Component
@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>
@@ -312,7 +305,9 @@ new class extends Component
</ul>
@endif
</section>
@endif
@if ($hasMaintenance)
<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">
@@ -358,6 +353,7 @@ new class extends Component
</ul>
@endif
</section>
@endif
@can('machines.manage')
<x-confirm-dialog id="cancel-record-dialog" :title="__('machines.maintenance.cancel_title')">
@@ -258,7 +258,8 @@ new class extends Component
<p class="text-sm whitespace-pre-line">{{ $machine->description }}</p>
@endif
<div class="flex flex-wrap gap-2">
<x-button :href="route('machines.console', $machine->id)" sm icon="device-tablet" :text="__('machines.show.console')" />
{{-- The console opens in its own window with its own session, signed in as the same user. --}}
<x-button :href="route('console.handoff', ['to' => route('machines.console', $machine->id)])" target="_blank" sm icon="arrow-top-right-on-square" :text="__('machines.show.console')" :aria-label="__('machines.show.console').' ('.__('layout.opens_in_new_window').')'" />
@can('machines.manage')
<x-button :href="route('machines.edit', $machine->id)" wire:navigate subtle color="black" sm icon="pencil" :text="__('machines.show.edit')" />
@endcan
@@ -16,5 +16,10 @@ Route::middleware(['web', 'auth', 'can:machines.use'])
});
Route::livewire('/{machine}', 'machines::show')->whereNumber('machine')->name('show');
Route::livewire('/{machine}/console', 'machines::console')->whereNumber('machine')->name('console');
});
// The console has its own session (Users' UseConsoleSession: paths under console/).
Route::livewire('/console/machines/{machine}', 'machines::console')
->middleware(['web', 'auth', 'can:machines.use'])
->whereNumber('machine')
->name('machines.console');