Add the touch-screen machine console

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:57:56 +02:00
co-authored by Claude Sonnet 5.5
parent 3e1c671949
commit 920fecdeb2
12 changed files with 1078 additions and 3 deletions
@@ -58,6 +58,14 @@ interface StockQueries
*/
public function taskSuggestions(int $taskId): array;
/**
* Items used most often on the machine in the last 90 days, then the
* ones used most recently, for the machine console (spec 19.6).
*
* @return array{frequent: list<int>, recent: list<int>}
*/
public function machineFavourites(int $machineId, int $limit = 8): array;
/**
* The private-disk path of the item's image or its thumbnail.
*/
@@ -130,6 +130,22 @@ class EloquentStockQueries implements StockQueries
->all();
}
public function machineFavourites(int $machineId, int $limit = 8): array
{
$uses = StockMovementModel::query()
->where('machine_id', $machineId)
->whereIn('kind', ['consumption', 'write_off'])
->whereNull('reverses_movement_id')
->where('recorded_at', '>=', now()->subDays(90))
->orderByDesc('id')
->get(['id', 'stock_item_id']);
$frequent = $uses->countBy('stock_item_id')->sortDesc()->keys()->take($limit)->map(fn ($id): int => (int) $id)->values()->all();
$recent = $uses->pluck('stock_item_id')->unique()->take($limit)->map(fn ($id): int => (int) $id)->values()->all();
return ['frequent' => $frequent, 'recent' => $recent];
}
public function imagePathOf(int $itemId, bool $thumbnail): ?string
{
$model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']);
@@ -0,0 +1,726 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
use App\Modules\Inventory\Domain\Services\StockSearch;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Machines\Application\Contracts\MachineTasks;
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
use App\Modules\Machines\Application\DTOs\MachineSummary;
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
use App\Modules\Machines\Application\DTOs\QueueRow;
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
use App\Modules\Machines\Application\UseCases\MachineWorkList;
use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\Users\Application\Contracts\Clock;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The machine console (konekäyttöliittymä, spec 19.6): a full-screen view
* 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
* view refreshes itself, and the Refresh button fetches the latest state
* at once and tells what changed.
*/
new #[Layout('layouts.console')] class extends Component
{
use DescribesMaintenance;
use FormatsStock {
FormatsStock::dateLabel insteadof DescribesMaintenance;
}
public const int ITEM_LIMIT = 24;
#[Locked]
public int $machineId;
#[Locked]
public bool $nextDay = false;
#[Locked]
public ?int $selectedEntryId = null;
/**
* Rows already seen, to tell how many are new after a refresh.
*
* @var list<int>
*/
#[Locked]
public array $knownEntryIds = [];
public string $search = '';
#[Locked]
public ?int $groupId = null;
#[Locked]
public ?int $selectedItemId = null;
public string $quantity = '1';
public string $reason = '';
#[Locked]
public ?int $lastMovementId = null;
public string $hours = '';
/**
* @var array<int, string>
*/
public array $readings = [];
#[Locked]
public ?int $recordingItemId = null;
public string $recordReading = '';
#[Locked]
public string $message = '';
#[Locked]
public string $refreshMessage = '';
public function mount(int $machine): void
{
$this->authorize('machines.use');
$this->machineId = (app(MachineQueries::class)->findMachine($machine) ?? abort(404))->id;
$this->knownEntryIds = array_map(fn (QueueRow $row): int => $row->entryId, $this->rows);
}
#[Computed]
public function machine(): MachineSummary
{
return app(MachineQueries::class)->findMachine($this->machineId) ?? abort(404);
}
#[Computed]
public function today(): string
{
return app(Clock::class)->today()->format('Y-m-d');
}
public function day(): string
{
return $this->nextDay ? CarbonImmutable::parse($this->today)->addDay()->format('Y-m-d') : $this->today;
}
/**
* @return list<QueueRow>
*/
#[Computed]
public function rows(): array
{
return app(MachineQueries::class)->rowsOn($this->machineId, $this->day(), $this->today);
}
#[Computed]
public function selectedRow(): ?QueueRow
{
return $this->selectedEntryId === null ? null : collect($this->rows)->firstWhere('entryId', $this->selectedEntryId);
}
/**
* @return list<MaintenanceItemStatus>
*/
#[Computed]
public function maintenance(): array
{
return app(MaintenanceQueries::class)->itemsOf($this->machineId);
}
/**
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return app(StockQueries::class)->groups(includeInactive: false);
}
/**
* Items to show as buttons: the search or group results, or else this
* machine's frequent and recent items.
*
* @return list<StockItemSummary>
*/
#[Computed]
public function items(): array
{
$stock = app(StockQueries::class);
$search = trim($this->search);
if ($search !== '' || $this->groupId !== null) {
return array_slice($stock->items($search === '' ? null : $search, $this->groupId), 0, self::ITEM_LIMIT);
}
$favourites = $stock->machineFavourites($this->machineId);
$ids = array_values(array_unique([...$favourites['frequent'], ...$favourites['recent']]));
$items = $stock->itemsByIds($ids);
return array_values(array_filter(array_map(fn (int $id): ?StockItemSummary => $items[$id] ?? null, $ids), fn ($item): bool => $item !== null && $item->isActive));
}
#[Computed]
public function selectedItem(): ?StockItemSummary
{
return $this->selectedItemId === null ? null : app(StockQueries::class)->findItem($this->selectedItemId);
}
/**
* The polled refresh: new rows are announced, the rest updates quietly.
*/
public function refreshList(): void
{
$this->authorize('machines.use');
$new = $this->reload();
if ($new > 0) {
$this->refreshMessage = trans_choice('machines.console.new_rows', $new, ['count' => $new]);
}
}
public function refresh(Clock $clock): void
{
$this->authorize('machines.use');
$new = $this->reload();
$this->refreshMessage = __('machines.console.refreshed', ['time' => $clock->now()->setTimezone(new DateTimeZone((string) config('app.business_timezone')))->format('H.i')])
.' '.trans_choice('machines.console.new_rows', $new, ['count' => $new]);
}
public function showDay(bool $next): void
{
$this->authorize('machines.use');
$this->nextDay = $next;
$this->selectedEntryId = null;
unset($this->rows);
}
public function selectRow(int $entryId): void
{
$this->authorize('machines.use');
$this->selectedEntryId = $this->selectedEntryId === $entryId ? null : $entryId;
$this->hours = '';
unset($this->selectedRow);
if ($this->selectedEntryId !== null) {
$this->js("setTimeout(() => document.getElementById('selected-task')?.focus())");
}
}
public function setStatus(int $entryId, string $status, MachineTasks $tasks): void
{
$this->authorize('machines.use');
abort_unless(in_array($status, ['in_progress', 'in_review'], true), 404);
$row = $this->row($entryId);
abort_if($row->task === null || ! $this->canFinish($row), 403);
$this->authorize('jobs.update-task-status', $row->task->jobId);
$tasks->changeStatus((int) $row->taskId, $status);
$this->message = __('machines.console.status_changed', ['title' => $row->task->title, 'status' => __('jobs.tasks.statuses.'.$status)]);
unset($this->rows, $this->selectedRow);
}
public function finish(int $entryId, MachineWorkList $workList): void
{
$this->authorize('machines.use');
$row = $this->row($entryId);
abort_if($row->task === null || ! $this->canFinish($row), 403);
$this->authorize('jobs.update-task-status', $row->task->jobId);
try {
$workList->finish($entryId, (int) auth()->id());
} catch (DomainException) {
$this->message = __('machines.errors.not_found');
$this->reload();
return;
}
$this->message = __('machines.console.finished', ['title' => $row->task->title]);
$this->selectedEntryId = $this->selectedEntryId === $entryId ? null : $this->selectedEntryId;
$this->reload();
$this->js("document.getElementById('console-status')?.focus()");
}
public function chooseGroup(?int $groupId): void
{
$this->authorize('inventory.record-use');
$this->groupId = $this->groupId === $groupId ? null : $groupId;
$this->selectedItemId = null;
unset($this->items);
}
public function selectItem(int $itemId): void
{
$this->authorize('inventory.record-use');
$this->selectedItemId = $itemId;
$this->quantity = '1';
$this->resetErrorBag();
unset($this->selectedItem);
$this->js("setTimeout(() => document.getElementById('material-quantity')?.focus())");
}
public function changeQuantity(int $step): void
{
$current = StockQuantity::parse($this->quantity)?->milli ?? 0;
$next = max(1000, intdiv($current, 1000) * 1000 + $step * 1000);
$this->quantity = StockQuantity::inputValue($next);
}
public function recordMaterial(RecordStockUse $recordUse): void
{
$this->authorize('inventory.record-use');
$this->resetErrorBag();
$item = $this->selectedItem ?? abort(404);
$row = $this->selectedRow;
$task = $row?->task;
try {
$result = $recordUse->execute(new StockUseData(
$item->id,
$this->quantity,
taskId: $task?->taskId,
jobId: $task?->jobId,
machineId: $this->machineId,
reason: $task === null ? $this->reason : null,
), (int) auth()->id());
} catch (DomainException $exception) {
$this->addError($exception instanceof App\Modules\Inventory\Domain\Exceptions\StockReasonRequired ? 'reason' : 'quantity', __(match (true) {
$exception instanceof App\Modules\Inventory\Domain\Exceptions\StockReasonRequired => 'machines.console.reason_required',
$exception instanceof App\Modules\Inventory\Domain\Exceptions\StockItemInactive => 'inventory.errors.inactive',
default => 'inventory.errors.quantity',
}));
return;
}
$this->lastMovementId = $result->movementId;
$this->message = __('machines.console.material_recorded', [
'item' => $result->itemName,
'quantity' => $this->quantity($result->quantityMilli, $item->unit),
'balance' => $this->quantity($result->balanceMilli, $item->unit),
]);
$this->selectedItemId = null;
$this->quantity = '1';
unset($this->items, $this->selectedItem);
$this->js("document.getElementById('console-status')?.focus()");
}
public function undoLast(ReverseStockMovement $reverse): void
{
$this->authorize('inventory.record-use');
if ($this->lastMovementId === null) {
return;
}
try {
$reverse->execute($this->lastMovementId, (int) auth()->id(), Gate::allows('inventory.reverse-any'));
$this->message = __('machines.console.material_undone');
} catch (DomainException) {
$this->message = __('inventory.errors.reversal_not_allowed');
}
$this->lastMovementId = null;
unset($this->items);
$this->js("document.getElementById('console-status')?.focus()");
}
public function saveHours(AddTaskHours $addHours, Clock $clock): void
{
$this->authorize('time.use');
$task = $this->selectedRow?->task ?? abort(404);
$this->authorize('time.book', $task->jobId);
try {
$total = $addHours->execute((int) auth()->id(), $task->taskId, $clock->today()->format('Y-m-d'), $this->hours, __('machines.console.hours_note', ['machine' => $this->machine->name]));
} catch (DomainException) {
$this->addError('hours', __('machines.console.hours_error'));
return;
}
$this->message = __('machines.console.hours_saved', ['hours' => $this->hours, 'title' => $task->title, 'total' => $total]);
$this->hours = '';
}
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 (DomainException) {
$this->addError('readings.'.$counterId, __('machines.maintenance.errors.reading'));
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);
}
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->js("setTimeout(() => document.getElementById('maintenance-confirm')?.focus())");
}
public function recordMaintenance(MachineMaintenance $maintenance): void
{
$this->authorize('machines.use');
$item = collect($this->maintenance)->firstWhere('id', $this->recordingItemId) ?? abort(404);
try {
$result = $maintenance->recordMaintenance($item->id, (int) auth()->id(), $item->counterId === null ? '' : $this->recordReading);
} catch (DomainException) {
$this->addError('recordReading', __('machines.maintenance.errors.reading'));
return;
}
$this->message = __('machines.maintenance.recorded', ['name' => $item->name]).($result['stockRecorded'] ? '' : ' '.__('machines.maintenance.stock_not_recorded'));
$this->recordingItemId = null;
unset($this->maintenance);
$this->js("document.getElementById('console-status')?.focus()");
}
/**
* Rows of today and late rows are made; the next day's are only shown.
*/
public function canFinish(QueueRow $row): bool
{
return ! $this->nextDay;
}
/**
* The first open task row of today: marked as next with text.
*/
public function nextEntryId(): ?int
{
if ($this->nextDay) {
return null;
}
foreach ($this->rows as $row) {
return $row->entryId;
}
return null;
}
public function render(): mixed
{
return $this->view()->title(__('machines.console.title', ['name' => $this->machine->name]));
}
/**
* @return int How many rows are new since the last look.
*/
private function reload(): int
{
unset($this->rows, $this->maintenance, $this->items, $this->selectedRow, $this->machine);
$ids = array_map(fn (QueueRow $row): int => $row->entryId, $this->rows);
$new = count(array_diff($ids, $this->knownEntryIds));
$this->knownEntryIds = array_values(array_unique([...$this->knownEntryIds, ...$ids]));
if ($this->selectedEntryId !== null && ! in_array($this->selectedEntryId, $ids, true)) {
$this->selectedEntryId = null;
}
return $new;
}
private function row(int $entryId): QueueRow
{
return collect($this->rows)->firstWhere('entryId', $entryId) ?? abort(404);
}
};
?>
@php
$touch = 'inline-flex min-h-11 min-w-11 items-center justify-center gap-2 rounded-lg px-4 py-2 font-medium focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400';
$primary = $touch.' bg-primary-600 text-white hover:bg-primary-700';
$secondary = $touch.' border border-zinc-500 bg-white text-zinc-900 hover:bg-zinc-100 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100 dark:hover:bg-zinc-700';
$machine = $this->machine;
$lateMaintenance = array_values(array_filter($this->maintenance, fn ($item) => $item->level->value === 'overdue'));
@endphp
<div wire:poll.30s="refreshList" class="mx-auto max-w-6xl space-y-6 p-3 sm:p-4">
<header class="flex flex-wrap items-center justify-between gap-3 rounded-lg bg-zinc-800 p-3 text-zinc-100 dark">
<div class="min-w-0">
<h1 class="text-2xl font-semibold break-words">{{ $machine->name }}</h1>
<p class="text-base">{{ __('machines.console.user', ['name' => auth()->user()?->name]) }}</p>
</div>
<div class="flex flex-wrap gap-2">
<button type="button" id="console-refresh" wire:click="refresh" class="{{ $touch }} bg-white text-lg text-zinc-900 hover:bg-zinc-200">
<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>
<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') }}
</a>
</div>
</header>
<div class="space-y-1">
<p role="status" aria-live="polite" class="font-medium">{{ $refreshMessage }}</p>
<p id="console-status" tabindex="-1" role="status" aria-live="polite" class="font-medium focus:outline-none">{{ $message }}</p>
</div>
@if ($lateMaintenance !== [])
<div class="space-y-1 rounded-lg border-2 border-red-700 p-3 dark:border-red-400">
@foreach ($lateMaintenance as $late)
<p wire:key="late-{{ $late->id }}" class="flex items-center gap-2 font-semibold text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-6 shrink-0" aria-hidden="true" />
{{ __('machines.console.maintenance_late', ['name' => $late->name]) }}
</p>
@endforeach
</div>
@endif
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="console-list-heading" class="space-y-3">
<h2 id="console-list-heading" class="text-xl font-semibold">{{ $nextDay ? __('machines.console.next_list', ['date' => $this->dateLabel($this->day())]) : __('machines.console.today_list') }}</h2>
<div class="flex flex-wrap gap-2" role="group" aria-label="{{ __('machines.show.day_navigation') }}">
<button type="button" wire:click="showDay(false)" class="{{ $nextDay ? $secondary : $primary }}" @unless ($nextDay) aria-pressed="true" @else aria-pressed="false" @endunless>{{ __('machines.show.today') }}</button>
<button type="button" wire:click="showDay(true)" class="{{ $nextDay ? $primary : $secondary }}" @if ($nextDay) aria-pressed="true" @else aria-pressed="false" @endif>{{ __('machines.show.next_day') }}</button>
</div>
@if ($this->rows === [])
<p>{{ __('machines.show.none') }}</p>
@else
<ol class="space-y-3">
@foreach ($this->rows as $row)
@php($task = $row->task)
<li wire:key="console-row-{{ $row->entryId }}" class="space-y-2 rounded-lg border-2 p-3 {{ $selectedEntryId === $row->entryId ? 'border-primary-600 dark:border-primary-400' : 'border-zinc-300 dark:border-zinc-600' }}">
@if ($this->nextEntryId() === $row->entryId)
<p class="text-base font-semibold">{{ __('machines.console.next') }}</p>
@endif
@if ($row->isOrder())
<p class="font-semibold">{{ __('machines.show.order') }}</p>
@elseif ($task !== null)
<p class="text-xl font-semibold break-words">{{ $task->title }}</p>
<p class="text-base">{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->customerName }}</p>
<p class="text-base">
{{ __('machines.show.status', ['status' => __('jobs.tasks.statuses.'.$task->status)]) }}
· {{ __('machines.show.priority', ['priority' => __('jobs.priorities.'.$task->priority)]) }}
@if ($task->dueOn !== null)
· {{ __('machines.show.due', ['date' => $this->dateLabel($task->dueOn)]) }}
@endif
</p>
@endif
@if ($row->isLate)
<p class="flex items-center gap-1 text-base font-semibold text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-5" aria-hidden="true" />
{{ __('machines.show.late', ['date' => CarbonImmutable::parse($row->plannedOn)->format('j.n.')]) }}
</p>
@endif
@if ($task !== null)
<div class="flex flex-wrap gap-2">
<button type="button" wire:click="selectRow({{ $row->entryId }})" class="{{ $selectedEntryId === $row->entryId ? $primary : $secondary }}" aria-pressed="{{ $selectedEntryId === $row->entryId ? 'true' : 'false' }}" aria-label="{{ __('machines.console.select_named', ['title' => $task->title]) }}">
{{ __('machines.console.select') }}
</button>
@if ($this->canFinish($row))
<button type="button" wire:click="setStatus({{ $row->entryId }}, 'in_progress')" class="{{ $secondary }}" aria-label="{{ __('machines.console.start_named', ['title' => $task->title]) }}">{{ __('machines.console.start') }}</button>
<button type="button" wire:click="setStatus({{ $row->entryId }}, 'in_review')" class="{{ $secondary }}" aria-label="{{ __('machines.console.review_named', ['title' => $task->title]) }}">{{ __('machines.console.review') }}</button>
<button type="button" wire:click="finish({{ $row->entryId }})" class="{{ $primary }}" aria-label="{{ __('machines.console.finish_named', ['title' => $task->title]) }}">
<x-icon name="check" class="size-5" aria-hidden="true" />
{{ __('machines.console.finish') }}
</button>
@endif
</div>
@endif
</li>
@endforeach
</ol>
@endif
@if ($this->selectedRow?->task !== null)
@php($selected = $this->selectedRow->task)
<div id="selected-task" tabindex="-1" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-3 focus:outline-none dark:border-zinc-600 dark:bg-zinc-900">
<h3 class="text-lg font-semibold">{{ __('machines.console.selected', ['title' => $selected->title]) }}</h3>
@if ($selected->instructions !== null)
<div>
<p class="font-medium">{{ __('machines.show.instructions') }}</p>
<p class="whitespace-pre-line">{{ $selected->instructions }}</p>
</div>
@endif
@if ($selected->description !== null)
<div>
<p class="font-medium">{{ __('machines.show.description') }}</p>
<p class="whitespace-pre-line">{{ $selected->description }}</p>
</div>
@endif
@can('time.book', $selected->jobId)
<form wire:submit="saveHours" class="flex flex-wrap items-end gap-2" novalidate>
<div class="w-40">
<x-input id="console-hours" wire:model="hours" inputmode="decimal" :label="__('machines.console.hours')" autocomplete="off" />
</div>
<button type="submit" class="{{ $primary }}">{{ __('machines.console.save_hours') }}</button>
</form>
@endcan
</div>
@endif
</section>
@can('inventory.record-use')
<section aria-labelledby="console-material-heading" class="space-y-3">
<h2 id="console-material-heading" class="text-xl font-semibold">{{ __('machines.console.material') }}</h2>
<p class="text-base">
{{ $this->selectedRow?->task !== null ? __('machines.console.material_for', ['title' => $this->selectedRow->task->title]) : __('machines.console.material_without_task') }}
</p>
<x-input id="console-search" wire:model.live.debounce.300ms="search" type="search" icon="magnifying-glass" :label="__('machines.console.search')" :hint="__('inventory.task.search_hint')" autocomplete="off" />
@if ($this->groups !== [])
<div class="flex flex-wrap gap-2" role="group" aria-label="{{ __('inventory.index.group') }}">
@foreach ($this->groups as $group)
<button type="button" wire:key="group-{{ $group->id }}" wire:click="chooseGroup({{ $group->id }})" class="{{ $groupId === $group->id ? $primary : $secondary }}" aria-pressed="{{ $groupId === $group->id ? 'true' : 'false' }}">{{ $group->name }}</button>
@endforeach
</div>
@endif
<p class="text-base">{{ trim($search) === '' && $groupId === null ? __('machines.console.favourites') : trans_choice('inventory.task.results', count($this->items), ['count' => count($this->items)]) }}</p>
<ul class="grid grid-cols-2 gap-2 sm:grid-cols-3">
@foreach ($this->items as $item)
<li wire:key="console-item-{{ $item->id }}">
<button
type="button"
wire:click="selectItem({{ $item->id }})"
class="flex h-full min-h-24 w-full flex-col items-start gap-1 rounded-lg border-2 p-2 text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 {{ $selectedItemId === $item->id ? 'border-primary-600 dark:border-primary-400' : 'border-zinc-300 bg-white hover:bg-zinc-100 dark:border-zinc-600 dark:bg-zinc-900 dark:hover:bg-zinc-700' }}"
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" />
@endif
<span class="font-semibold break-words">{{ $item->name }}</span>
<span class="text-base">{{ $this->quantity($item->balanceMilli, $item->unit) }}</span>
</button>
</li>
@endforeach
</ul>
@if ($this->selectedItem !== null)
<form wire:submit="recordMaterial" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-3 dark:border-zinc-600 dark:bg-zinc-900" novalidate>
<p class="font-semibold">{{ $this->selectedItem->name }} ({{ __('inventory.task.balance', ['balance' => $this->quantity($this->selectedItem->balanceMilli, $this->selectedItem->unit)]) }})</p>
<div class="flex flex-wrap items-end gap-2">
<button type="button" wire:click="changeQuantity(-1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.less') }}">−</button>
<div class="w-32">
<x-input id="material-quantity" wire:model="quantity" inputmode="decimal" :label="__('inventory.task.quantity', ['unit' => __('inventory.units.'.$this->selectedItem->unit->value)])" autocomplete="off" />
</div>
<button type="button" wire:click="changeQuantity(1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.more') }}">+</button>
</div>
@if ($this->selectedRow?->task === null)
<x-input id="material-reason" wire:model="reason" :label="__('inventory.use.reason')" autocomplete="off" maxlength="255" />
@endif
<button type="submit" class="{{ $primary }} w-full text-xl">{{ __('machines.console.record_material') }}</button>
</form>
@endif
@if ($lastMovementId !== null)
<button type="button" wire:click="undoLast" class="{{ $secondary }}">
<x-icon name="arrow-uturn-left" class="size-5" aria-hidden="true" />
{{ __('machines.console.undo') }}
</button>
@endif
</section>
@endcan
</div>
<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>
<div class="min-w-40 flex-1">
<x-input
id="console-reading-{{ $counter->id }}"
wire:model="readings.{{ $counter->id }}"
inputmode="decimal"
:label="$counter->name.' ('.__('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>
</form>
@endforeach
</div>
<ul class="grid gap-3 md:grid-cols-2">
@foreach ($this->maintenance as $item)
<li wire:key="console-maintenance-{{ $item->id }}" class="space-y-2 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600">
<p class="font-semibold">{{ $item->name }}</p>
<p class="flex items-center gap-2 text-base font-medium @if ($item->level->value === 'overdue') text-red-700 dark:text-red-400 @elseif ($item->level->value === 'approaching') text-amber-800 dark:text-amber-300 @endif">
<x-icon :name="$this->levelIcon($item)" class="size-5" aria-hidden="true" />
{{ $this->levelLabel($item) }}@if ($this->stateText($item) !== ''): {{ $this->stateText($item) }}@endif
</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
<button type="button" wire:click="startMaintenance({{ $item->id }})" class="{{ $secondary }}" aria-label="{{ __('machines.maintenance.done_named', ['name' => $item->name]) }}">
<x-icon name="wrench" class="size-5" aria-hidden="true" />
{{ __('machines.maintenance.done') }}
</button>
@endif
</li>
@endforeach
</ul>
</section>
</div>
@@ -128,6 +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>
</li>
@endforeach
</ul>
@@ -257,9 +257,12 @@ new class extends Component
@if ($machine->description !== null)
<p class="text-sm whitespace-pre-line">{{ $machine->description }}</p>
@endif
@can('machines.manage')
<p><x-button :href="route('machines.edit', $machine->id)" wire:navigate sm icon="pencil" :text="__('machines.show.edit')" /></p>
@endcan
<div class="flex flex-wrap gap-2">
<x-button :href="route('machines.console', $machine->id)" sm icon="device-tablet" :text="__('machines.show.console')" />
@can('machines.manage')
<x-button :href="route('machines.edit', $machine->id)" wire:navigate subtle color="black" sm icon="pencil" :text="__('machines.show.edit')" />
@endcan
</div>
</div>
<p id="work-list-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
@@ -16,4 +16,5 @@ 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');
});
@@ -6,12 +6,14 @@ use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class LogoutController
{
public function __invoke(Request $request): RedirectResponse
{
$locale = app()->getLocale();
$returnTo = $this->returnTo($request);
Auth::guard('web')->logout();
$request->session()->invalidate();
@@ -20,6 +22,23 @@ class LogoutController
// The login page stays in the language the user had chosen.
$request->session()->put(SetLocale::SESSION_KEY, $locale);
// "Change user" on a machine console: the next user signs in back to the console.
if ($returnTo !== null) {
$request->session()->put('url.intended', $returnTo);
}
return redirect()->route('login')->with('status', __('auth.logged_out'));
}
/**
* A page of this application to return to after the next login, never
* another site.
*/
private function returnTo(Request $request): ?string
{
$returnTo = (string) $request->input('return_to', '');
$base = rtrim(url('/'), '/').'/';
return $returnTo !== '' && Str::startsWith($returnTo, $base) && ! Str::contains($returnTo, ['\\', '@']) ? $returnTo : null;
}
}
+44
View File
@@ -32,6 +32,7 @@ return [
'responsible' => 'Responsible: :name',
'open' => 'Work list and details',
'open_named' => 'Work list and details of :name',
'console_named' => 'Machine console: :name',
],
'form' => [
@@ -220,6 +221,49 @@ return [
'reading' => 'Enter a reading of zero or more, at most three decimals.',
],
],
'console' => [
'title' => 'Machine console: :name',
'user' => 'User: :name',
'refresh' => 'Refresh',
'refreshed' => 'Refreshed at :time.',
'new_rows' => '{0} No new rows.|{1} 1 new row on the work list.|[2,*] :count new rows on the work list.',
'change_user' => 'Change user',
'back' => 'To the normal view',
'maintenance_late' => 'Maintenance late: :name',
'today_list' => 'Today\'s work list',
'next_list' => 'Work list :date (viewing)',
'next' => 'Next',
'select' => 'Select',
'select_named' => 'Select task :title',
'start' => 'Start',
'start_named' => 'Start: :title',
'review' => 'To review',
'review_named' => 'To review: :title',
'finish' => 'Done',
'finish_named' => 'Done: :title',
'status_changed' => ':title: status now :status.',
'finished' => ':title marked done and removed from the work list.',
'selected' => 'Selected task: :title',
'hours' => 'Hours today (h)',
'save_hours' => 'Record hours',
'hours_saved' => ':hours h recorded on :title. Day total :total h.',
'hours_error' => 'The hours could not be recorded. Check the amount (in steps of 0.25 h) and that the day\'s hours are not approved yet.',
'hours_note' => 'Machine :machine',
'material' => 'Material used',
'material_for' => 'Recorded on task :title.',
'material_without_task' => 'No task selected: the use is recorded on the machine. You can give a reason (e.g. a test run) or select a task from the work list.',
'search' => 'Search material',
'favourites' => 'The items used most often and most recently on this machine.',
'less' => 'Less',
'more' => 'More',
'record_material' => 'Record use',
'material_recorded' => 'Recorded :item :quantity. Balance now :balance.',
'material_undone' => 'The latest record was undone.',
'undo' => 'Undo the latest record',
'reason_required' => 'Give a reason when no task is selected.',
'counters_and_maintenance' => 'Counters and maintenance',
'latest' => 'Latest reading :reading',
],
'errors' => [
'name' => 'Enter a name (1–150 characters).',
'name_taken' => 'The name is already in use.',
+44
View File
@@ -32,6 +32,7 @@ return [
'responsible' => 'Vastuuhenkilö: :name',
'open' => 'Työlista ja tiedot',
'open_named' => 'Koneen :name työlista ja tiedot',
'console_named' => 'Konekäyttöliittymä: :name',
],
'form' => [
@@ -220,6 +221,49 @@ return [
'reading' => 'Anna lukema nollana tai suurempana lukuna, enintään kolme desimaalia.',
],
],
'console' => [
'title' => 'Konekäyttöliittymä: :name',
'user' => 'Käyttäjä: :name',
'refresh' => 'Päivitä',
'refreshed' => 'Päivitetty klo :time.',
'new_rows' => '{0} Ei uusia rivejä.|{1} 1 uusi rivi työlistalla.|[2,*] :count uutta riviä työlistalla.',
'change_user' => 'Vaihda käyttäjä',
'back' => 'Tavalliseen näkymään',
'maintenance_late' => 'Huolto myöhässä: :name',
'today_list' => 'Tämän päivän työlista',
'next_list' => 'Työlista :date (katselu)',
'next' => 'Seuraavana',
'select' => 'Valitse',
'select_named' => 'Valitse tehtävä :title',
'start' => 'Aloita',
'start_named' => 'Aloita: :title',
'review' => 'Tarkastettavaksi',
'review_named' => 'Tarkastettavaksi: :title',
'finish' => 'Valmis',
'finish_named' => 'Valmis: :title',
'status_changed' => ':title: tila nyt :status.',
'finished' => ':title merkitty valmiiksi ja poistettu työlistalta.',
'selected' => 'Valittu tehtävä: :title',
'hours' => 'Tämän päivän tunnit (h)',
'save_hours' => 'Kirjaa tunnit',
'hours_saved' => 'Tunnit :hours h kirjattu tehtävälle :title. Päivän yhteensä :total h.',
'hours_error' => 'Tunteja ei voitu kirjata. Tarkista määrä (0,25 h tarkkuudella), ja ettei päivän tunteja ole jo hyväksytty.',
'hours_note' => 'Kone :machine',
'material' => 'Materiaalin kirjaus',
'material_for' => 'Kirjataan tehtävälle :title.',
'material_without_task' => 'Ei valittua tehtävää: käyttö kirjataan koneelle. Voit antaa syyn (esim. koeajo) tai valita tehtävän työlistalta.',
'search' => 'Hae materiaali',
'favourites' => 'Tämän koneen yleisimmät ja viimeksi käytetyt nimikkeet.',
'less' => 'Vähemmän',
'more' => 'Enemmän',
'record_material' => 'Kirjaa käyttö',
'material_recorded' => 'Kirjattu :item :quantity. Saldo nyt :balance.',
'material_undone' => 'Viimeisin kirjaus peruttu.',
'undo' => 'Peru viimeisin kirjaus',
'reason_required' => 'Anna syy, kun tehtävää ei ole valittu.',
'counters_and_maintenance' => 'Laskurit ja huollot',
'latest' => 'Viimeisin lukema :reading',
],
'errors' => [
'name' => 'Anna nimi (1–150 merkkiä).',
'name_taken' => 'Nimi on jo käytössä.',
+54
View File
@@ -0,0 +1,54 @@
<!DOCTYPE html>
{{--
Full-screen layout of the machine console (spec 19.6) for the tablet or
touch screen next to a machine: no main menu, large text. The page's own
header has the machine's name, the user, Refresh, Change user and the
way back. The theme follows the stored choice like the main layout.
--}}
<html
lang="{{ str_replace('_', '-', app()->getLocale()) }}"
x-data="tallstackui_darkTheme({ default: 'system' })"
x-bind:class="{ 'dark': darkTheme }"
>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? config('app.name') }}</title>
<script>
(() => {
const applyStoredTheme = () => {
const stored = localStorage.getItem('dark-theme');
const dark = stored === 'dark' || stored === 'true'
|| (stored !== 'light' && stored !== 'false' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.classList.toggle('dark', dark);
};
applyStoredTheme();
document.addEventListener('livewire:navigating', (event) => event.detail.onSwap(applyStoredTheme));
})();
</script>
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=inter:400,500,600&display=swap" rel="stylesheet" />
@include('partials.tallstackui-script')
@livewireStyles
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="min-h-screen bg-zinc-100 text-lg text-zinc-900 antialiased dark:bg-zinc-800 dark:text-zinc-100">
<a
href="#main-content"
class="sr-only focus:not-sr-only focus:fixed focus:start-4 focus:top-4 focus:z-50 focus:rounded-md focus:bg-white focus:px-4 focus:py-2 focus:text-zinc-900 focus:shadow-lg focus:outline-2 focus:outline-offset-2 focus:outline-blue-700"
>
{{ __('layout.skip_to_content') }}
</a>
<main id="main-content" tabindex="-1" class="focus:outline-none">
{{ $slot }}
</main>
@livewireScripts
</body>
</html>
@@ -84,3 +84,30 @@ it('records maintenance done with the keyboard', function () {
->assertSee('Kunnossa')
->assertNoAccessibilityIssues(level: 2);
});
it('has no accessibility issues on the machine console', function (string $device, string $colorScheme) {
$visit = visit(route('machines.console', $this->machine->id));
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee('Banderolli')
->assertSee(__('machines.console.maintenance_late', ['name' => 'Pään puhdistus']))
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('refreshes the console on a tablet and keeps focus on the button', function () {
visit(route('machines.console', $this->machine->id))
->resize(1024, 768)
->click('#console-refresh')
->assertSee('Päivitetty klo')
->assertScript('document.activeElement.id', 'console-refresh')
->click('[aria-label="'.__('machines.console.select_named', ['title' => 'Banderolli']).'"]')
->assertSee(__('machines.console.selected', ['title' => 'Banderolli']))
->assertNoAccessibilityIssues(level: 2);
});
@@ -0,0 +1,132 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
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\MachineModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineQueueEntryModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->travelTo(now()->setTimezone(config('app.business_timezone'))->setTime(10, 0));
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
$this->actingAs($this->employee);
$print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole();
$print->update(['uses_stock' => true]);
$this->machine = MachineModel::factory()->inUnits([$print->id])->create(['name' => 'Suurkuvatulostin']);
$this->job = CustomerJobModel::factory()->create(['name' => 'Messut', 'status' => 'order', 'instructions' => 'Kiiltävä laminointi']);
DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $print->id]);
$this->task = TaskModel::factory()->create([
'customer_job_id' => $this->job->id,
'work_type_id' => WorkTypeModel::query()->where('name', 'painotyö')->value('id'),
'title' => 'Banderolli',
]);
app(MachineWorkList::class)->planTask($this->task->id, $this->machine->id, null);
$papers = StockItemGroupModel::factory()->create(['name' => 'Paperit']);
$this->paper = StockItemModel::factory()->create(['stock_item_group_id' => $papers->id, 'name' => 'Bannerikangas', 'unit' => 'square_metre']);
});
function console(object $test): mixed
{
return Livewire::test('machines::console', ['machine' => $test->machine->id]);
}
it('opens without the main menu and shows today\'s work list', function () {
$this->get(route('machines.console', $this->machine->id))
->assertOk()
->assertSee('Suurkuvatulostin')
->assertSee('Banderolli')
->assertSee(__('machines.console.refresh'))
->assertDontSee(__('layout.main_menu'));
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('machines.console', $this->machine->id))->assertForbidden();
});
it('records material on the selected task, undoes it, and records hours', function () {
console($this)
->call('selectRow', MachineQueueEntryModel::query()->sole()->id)
->assertSee('Kiiltävä laminointi')
->call('chooseGroup', StockItemGroupModel::query()->value('id'))
->assertSee('Bannerikangas')
->call('selectItem', $this->paper->id)
->call('changeQuantity', 1)
->assertSet('quantity', '2')
->call('recordMaterial')
->assertHasNoErrors()
->assertSet('message', "Kirjattu Bannerikangas 2\u{00A0}m². Saldo nyt -2\u{00A0}m².")
->call('undoLast')
->assertSet('message', __('machines.console.material_undone'))
->set('hours', '1,5')
->call('saveHours')
->assertHasNoErrors();
$use = StockMovementModel::query()->where('kind', 'consumption')->sole();
expect($use->only(['task_id', 'machine_id', 'quantity_milli']))->toBe(['task_id' => $this->task->id, 'machine_id' => $this->machine->id, 'quantity_milli' => -2_000])
->and((float) TimeEntryModel::query()->sole()->hours)->toBe(1.5);
// Frequent items come first without a search.
console($this)->assertSee('Bannerikangas');
});
it('records material without a task on the machine, with an optional reason', function () {
console($this)
->set('search', 'banneri')
->call('selectItem', $this->paper->id)
->set('reason', 'Koeajo')
->call('recordMaterial')
->assertHasNoErrors();
expect(StockMovementModel::query()->sole()->only(['task_id', 'machine_id', 'reason']))
->toBe(['task_id' => null, 'machine_id' => $this->machine->id, 'reason' => 'Koeajo']);
});
it('finishes a task from the console, which marks it done', function () {
$entry = MachineQueueEntryModel::query()->sole();
console($this)
->call('setStatus', $entry->id, 'in_progress')
->assertSet('message', 'Banderolli: tila nyt Työn alla.')
->call('finish', $entry->id)
->assertSet('message', __('machines.console.finished', ['title' => 'Banderolli']))
->assertDontSee(__('machines.console.finish_named', ['title' => 'Banderolli']));
expect($this->task->fresh()->status->value)->toBe('done');
});
it('announces new rows when refreshed', function () {
$component = console($this);
$other = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->task->work_type_id, 'title' => 'Juliste']);
app(MachineWorkList::class)->planTask($other->id, $this->machine->id, null);
$component->call('refresh')
->assertSet('refreshMessage', fn (string $message) => str_contains($message, '1 uusi rivi työlistalla.'))
->assertSee('Juliste')
->call('showDay', true)
->assertDontSee('Juliste');
});
it('returns to the console after changing user', function () {
$this->post(route('logout'), ['return_to' => route('machines.console', $this->machine->id)])->assertRedirect(route('login'));
expect(session('url.intended'))->toBe(route('machines.console', $this->machine->id));
$this->actingAs($this->employee);
$this->post(route('logout'), ['return_to' => 'https://example.com/phish']);
expect(session('url.intended'))->toBeNull();
});