Fix console hours, sign-in landing and counter usage races

- Hours the counter reading cannot parse (",5") no longer fail after
  they are saved; they just get no hour counter suggestion.
- The console's sign-in falls back to a console machine list
  (machines::console-picker at /console/machines) instead of /machines,
  so it stays in the console's own session.
- Recording counter usage locks the counter first, so usage saved at
  the same time from two devices is not lost.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-29 10:05:02 +02:00
co-authored by Claude Sonnet 5.5
parent 32c33e2a64
commit 6692396a63
14 changed files with 139 additions and 12 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -115,7 +115,10 @@ final class MachineMaintenance
}
return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int {
$this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound;
if (! $this->maintenance->lockCounter($counterId)) {
throw new CounterNotFound;
}
$reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli;
$this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now());
@@ -21,6 +21,14 @@ interface MaintenanceRepository
*/
public function machineOfCounter(int $counterId): ?int;
/**
* Locks the counter until the transaction ends, so usage recorded at
* the same time is added one after the other.
*
* @return bool Whether the counter exists.
*/
public function lockCounter(int $counterId): bool;
public function latestReading(int $counterId): ?int;
public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void;
@@ -64,6 +64,11 @@ class EloquentMaintenanceRepository implements MaintenanceRepository
return $machineId === null ? null : (int) $machineId;
}
public function lockCounter(int $counterId): bool
{
return MachineCounterModel::query()->whereKey($counterId)->lockForUpdate()->exists();
}
public function latestReading(int $counterId): ?int
{
$reading = MachineCounterReadingModel::query()
@@ -0,0 +1,62 @@
<?php
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Machines\Application\DTOs\MachineSummary;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
/**
* The machine console's own start page (spec 19.6): where the console's
* sign-in goes when no machine asked for it, e.g. on a tablet that opened
* the sign-in page directly. It stays in the console's own session and
* lists the active machines as large links to their consoles.
*/
new #[Layout('layouts.console')] class extends Component
{
public function mount(): void
{
$this->authorize('machines.use');
}
/**
* @return list<MachineSummary>
*/
#[Computed]
public function machines(): array
{
return app(MachineQueries::class)->machines(false);
}
public function render(): mixed
{
return $this->view()->title(__('machines.console_picker.title'));
}
};
?>
<div class="mx-auto max-w-3xl space-y-6 p-3 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('machines.console_picker.title') }}</h1>
@if ($this->machines === [])
<p>{{ __('machines.console_picker.empty') }}</p>
@else
<p>{{ __('machines.console_picker.intro') }}</p>
<ul class="grid gap-3 sm:grid-cols-2">
@foreach ($this->machines as $machine)
<li wire:key="console-machine-{{ $machine->id }}">
<a
href="{{ route('machines.console', $machine->id) }}"
class="flex min-h-14 flex-col justify-center rounded-lg border border-zinc-400 bg-white px-4 py-3 text-xl font-semibold text-zinc-900 hover:bg-zinc-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:hover:bg-zinc-700 dark:focus-visible:outline-blue-400"
>
{{ $machine->name }}
@if ($machine->serviceUnitNames !== [])
<span class="text-base font-normal">{{ implode(', ', $machine->serviceUnitNames) }}</span>
@endif
</a>
</li>
@endforeach
</ul>
@endif
</div>
@@ -500,7 +500,12 @@ new #[Layout('layouts.console')] class extends Component
*/
private function suggestHourCounters(string $hours): void
{
$milli = Reading::parse($hours);
// The hours are already saved; hours Reading does not read (",5") get no suggestion.
try {
$milli = Reading::parse($hours);
} catch (DomainException) {
return;
}
if ($milli === null || $milli <= 0) {
return;
@@ -19,7 +19,7 @@ Route::middleware(['web', 'auth', 'can:machines.use'])
});
// 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');
Route::middleware(['web', 'auth', 'can:machines.use'])->group(function () {
Route::livewire('/console/machines', 'machines::console-picker')->name('machines.console-picker');
Route::livewire('/console/machines/{machine}', 'machines::console')->whereNumber('machine')->name('machines.console');
});
@@ -27,7 +27,7 @@ new #[Layout('layouts.console')] class extends Component
public function loginWithPin(LoginPins $pins): void
{
if ($this->signInWithPin($pins)) {
$this->redirectIntended(route('machines.index'));
$this->redirectIntended(route('machines.console-picker'));
}
}
@@ -35,7 +35,7 @@ new #[Layout('layouts.console')] class extends Component
{
$this->signInWithPassword($checkLoginAllowed);
$this->redirectIntended(route('machines.index'));
$this->redirectIntended(route('machines.console-picker'));
}
public function render(): mixed
+1 -1
View File
@@ -15,7 +15,7 @@ return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware): void {
// The machine console has its own session and sign-in page.
$middleware->redirectGuestsTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('console.login') : route('login'));
$middleware->redirectUsersTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('machines.index') : route('home'));
$middleware->redirectUsersTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('machines.console-picker') : route('home'));
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
+5
View File
@@ -220,6 +220,11 @@ return [
'usage' => 'Enter the amount the job used as a number greater than zero, e.g. 350, at most three decimals.',
],
],
'console_picker' => [
'title' => 'Machine console',
'intro' => 'Choose the machine you are working at.',
'empty' => 'There are no machines in use.',
],
'console' => [
'ordered_at' => 'ordered at :time',
'order_step' => 'step :step/:steps',
+5
View File
@@ -220,6 +220,11 @@ return [
'usage' => 'Anna työn kulutus nollaa suurempana lukuna, esim. 350, enintään kolme desimaalia.',
],
],
'console_picker' => [
'title' => 'Konekäyttöliittymä',
'intro' => 'Valitse kone, jonka vieressä olet.',
'empty' => 'Käytössä olevia koneita ei ole.',
],
'console' => [
'ordered_at' => 'tilattu klo :time',
'order_step' => 'vaihe :step/:steps',
+2 -1
View File
@@ -51,6 +51,7 @@ it('has no accessibility issues on the machine pages', function (string $page, s
'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),
'console picker' => route('machines.console-picker'),
};
$visit = visit($url);
@@ -64,7 +65,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', 'maintenance'])->with([
})->with(['index', 'show', 'form', 'job', 'maintenance', 'console picker'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
@@ -155,6 +155,21 @@ it('suggests the hours booked as the usage of the machine\'s hour counter and le
expect(MachineCounterReadingModel::query()->sole()->reading_milli)->toBe(1_500);
});
it('saves hours written as ",5" without a counter suggestion it cannot read', function () {
$hours = MachineCounterModel::query()->create(['machine_id' => $this->machine->id, 'name' => 'Käyttötunnit', 'unit' => 'hour', 'sort_order' => 1]);
console($this)
->call('selectRow', MachineQueueEntryModel::query()->sole()->id)
->set('hours', ',5')
->call('saveHours')
->assertHasNoErrors()
->assertSet('hours', '')
->assertSet('usage', []);
expect(TimeEntryModel::query()->sole()->hours)->toEqual(0.5)
->and(MachineCounterReadingModel::query()->where('machine_counter_id', $hours->id)->exists())->toBeFalse();
});
it('changes the console\'s user with a PIN code', function () {
$console = route('machines.console', $this->machine->id);
$other = User::factory()->employee()->create(['name' => 'Olli Operaattori', 'pin_hash' => Hash::make('2468')]);
@@ -49,7 +49,7 @@ it('asks a signed-out console to sign in on the console\'s own page and keeps /l
$this->actingAs($this->user, 'console');
$this->get(route('login'))->assertOk();
$this->get(route('console.login'))->assertRedirect(route('machines.index'));
$this->get(route('console.login'))->assertRedirect(route('machines.console-picker'));
});
it('signs out of the console without signing out of the normal user interface', function () {
@@ -83,6 +83,24 @@ it('signs in to the console with a PIN code or a password', function () {
->assertRedirect($this->console);
});
it('goes to the console\'s machine list, in the console\'s own session, when no machine asked for the sign-in', function () {
$this->user->forceFill(['pin_hash' => Hash::make('2468')])->save();
Livewire::test('users::console-login')
->set('userId', (string) $this->user->id)
->set('pin', '2468')
->call('loginWithPin')
->assertRedirect(route('machines.console-picker'));
expect(UseConsoleSession::isConsoleUrl(route('machines.console-picker')))->toBeTrue();
$this->actingAs($this->user, 'console')
->get(route('machines.console-picker'))
->assertOk()
->assertSee('Suurkuvatulostin')
->assertSee($this->console);
});
it('tells console requests by their path or by where their Livewire component was rendered', function () {
$livewire = fn (string $path): Request => tap(
Request::create('/livewire-1234/update', 'POST', ['components' => [['snapshot' => json_encode(['memo' => ['path' => $path]])]]]),