Compare commits
5
Commits
acf87aa3cd
...
ef400054b0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef400054b0 | ||
|
|
6692396a63 | ||
|
|
32c33e2a64 | ||
|
|
87e38260dc | ||
|
|
701f05780f |
+1
-1
@@ -33,7 +33,7 @@ use Illuminate\Support\Carbon;
|
||||
* @property-read UserMoneyPermissionsModel|null $moneyPermissions
|
||||
*/
|
||||
#[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id', 'locale'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
#[Hidden(['password', 'remember_token', 'pin_hash'])]
|
||||
class User extends Authenticatable implements HasLocalePreference
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Returns the stock a cancelled maintenance record used (spec 19.5): each
|
||||
* of its use movements not yet reversed gets a reversal, recorded today.
|
||||
*/
|
||||
final class ReverseMaintenanceStockUse
|
||||
{
|
||||
public function __construct(
|
||||
private StockMovementRepository $movements,
|
||||
private ReverseStockMovement $reverse,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int How many movements were reversed.
|
||||
*
|
||||
* @throws StockMovementNotFound
|
||||
* @throws StockMovementNotReversible
|
||||
* @throws StockMovementAlreadyReversed
|
||||
* @throws StockReversalNotAllowed
|
||||
*/
|
||||
public function execute(int $maintenanceRecordId, int $actorUserId): int
|
||||
{
|
||||
return $this->transactions->run(function () use ($maintenanceRecordId, $actorUserId): int {
|
||||
$movementIds = $this->movements->unreversedUseOfMaintenance($maintenanceRecordId);
|
||||
|
||||
foreach ($movementIds as $movementId) {
|
||||
$this->reverse->execute($movementId, $actorUserId, true);
|
||||
}
|
||||
|
||||
return count($movementIds);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,13 @@ interface StockMovementRepository
|
||||
|
||||
public function isReversed(int $movementId): bool;
|
||||
|
||||
/**
|
||||
* The ids of a maintenance record's use movements that are not reversed.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array;
|
||||
|
||||
/**
|
||||
* The item's balance in thousandths: the sum of its movements.
|
||||
*/
|
||||
|
||||
+14
@@ -4,6 +4,7 @@ namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
|
||||
use DateTimeImmutable;
|
||||
@@ -50,6 +51,19 @@ class EloquentStockMovementRepository implements StockMovementRepository
|
||||
return StockMovementModel::query()->where('reverses_movement_id', $movementId)->exists();
|
||||
}
|
||||
|
||||
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array
|
||||
{
|
||||
return StockMovementModel::query()
|
||||
->where('maintenance_record_id', $maintenanceRecordId)
|
||||
->where('kind', StockMovementKind::Consumption)
|
||||
->whereNotIn('id', StockMovementModel::query()->whereNotNull('reverses_movement_id')->select('reverses_movement_id'))
|
||||
->orderBy('id')
|
||||
->pluck('id')
|
||||
->map(fn (mixed $id): int => (int) $id)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function balanceOf(int $itemId): int
|
||||
{
|
||||
return (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
|
||||
|
||||
@@ -272,7 +272,7 @@ new class extends Component
|
||||
|
||||
<div>
|
||||
@if (($this->context?->usesStock ?? false) || $this->movements !== [])
|
||||
<section aria-label="{{ __('inventory.task.list_of', ['title' => $taskTitle]) }}" class="space-y-3">
|
||||
<section data-task-section aria-label="{{ __('inventory.task.list_of', ['title' => $taskTitle]) }}" class="space-y-3">
|
||||
<h4 class="font-medium">{{ __('inventory.task.title') }}</h4>
|
||||
|
||||
<p id="task-{{ $taskId }}-materials-status" tabindex="-1" role="status" aria-live="polite" class="text-sm focus:outline-none">{{ $message }}</p>
|
||||
|
||||
@@ -4,6 +4,13 @@ use App\Modules\Inventory\Presentation\Http\Controllers\DownloadInventoryCount;
|
||||
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
// Pictures on the machine console, which has its own session (paths under console/).
|
||||
Route::middleware(['web', 'auth', 'can:inventory.view'])
|
||||
->get('/console/inventory/items/{item}/image/{size}', ShowStockItemImage::class)
|
||||
->whereNumber('item')
|
||||
->whereIn('size', ['full', 'thumbnail'])
|
||||
->name('inventory.items.console-image');
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:inventory.view'])
|
||||
->prefix('inventory')
|
||||
->name('inventory.')
|
||||
|
||||
@@ -470,14 +470,6 @@ new class extends Component
|
||||
<p class="whitespace-pre-line">{{ $task->description }}</p>
|
||||
@endif
|
||||
|
||||
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'checklist-'.$task->id" />
|
||||
|
||||
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
|
||||
|
||||
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
|
||||
<livewire:inventory::task-materials :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'materials-'.$task->id" />
|
||||
<livewire:machines::task-machine :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'machine-'.$task->id" />
|
||||
|
||||
<div class="flex flex-wrap items-end gap-3">
|
||||
@if ($canChangeStatus)
|
||||
<div class="w-full sm:w-56">
|
||||
@@ -530,6 +522,33 @@ new class extends Component
|
||||
/>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<x-tabs
|
||||
id="task-{{ $task->id }}-tabs"
|
||||
:label="__('jobs.tasks.tabs.label', ['title' => $task->title])"
|
||||
:tabs="[
|
||||
'notes' => __('jobs.tasks.tabs.notes'),
|
||||
'images' => __('jobs.tasks.tabs.images'),
|
||||
'materials' => __('jobs.tasks.tabs.materials'),
|
||||
]"
|
||||
class="pt-2"
|
||||
>
|
||||
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="notes" class="space-y-3">
|
||||
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'checklist-'.$task->id" />
|
||||
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
|
||||
</x-tabs.panel>
|
||||
|
||||
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="images">
|
||||
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
|
||||
</x-tabs.panel>
|
||||
|
||||
{{-- The sections mark themselves data-task-section when they have something to show. --}}
|
||||
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="materials" class="group space-y-3">
|
||||
<livewire:inventory::task-materials :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'materials-'.$task->id" />
|
||||
<livewire:machines::task-machine :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'machine-'.$task->id" />
|
||||
<p class="group-has-[[data-task-section]]:hidden">{{ __('jobs.tasks.tabs.no_materials') }}</p>
|
||||
</x-tabs.panel>
|
||||
</x-tabs>
|
||||
</div>
|
||||
</article>
|
||||
</li>
|
||||
|
||||
@@ -13,4 +13,9 @@ interface MaintenanceMaterials
|
||||
* @return bool False when the stock could not be recorded (e.g. the item is out of use).
|
||||
*/
|
||||
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool;
|
||||
|
||||
/**
|
||||
* Returns the stock a cancelled maintenance record used.
|
||||
*/
|
||||
public function returnUseOf(int $maintenanceRecordId, int $userId): void;
|
||||
}
|
||||
|
||||
@@ -24,10 +24,10 @@ 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.
|
||||
* cancelled by management, never deleted, and its stock use reversed.
|
||||
*/
|
||||
final class MachineMaintenance
|
||||
{
|
||||
@@ -98,50 +98,55 @@ 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 {
|
||||
$this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound;
|
||||
$this->maintenance->addReading($counterId, $milli, $actorUserId, $this->clock->now());
|
||||
if ($usageMilli === null || $usageMilli <= 0) {
|
||||
throw new InvalidReading;
|
||||
}
|
||||
|
||||
return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int {
|
||||
if (! $this->maintenance->lockCounter($counterId)) {
|
||||
throw new CounterNotFound;
|
||||
}
|
||||
|
||||
$reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli;
|
||||
$this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now());
|
||||
|
||||
return $reading;
|
||||
});
|
||||
|
||||
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.
|
||||
* 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);
|
||||
@@ -164,6 +169,7 @@ final class MachineMaintenance
|
||||
}
|
||||
|
||||
$this->maintenance->cancelRecord($recordId, $actorUserId, $this->clock->now());
|
||||
$this->materials->returnUseOf($recordId, $actorUserId);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -4,17 +4,22 @@ namespace App\Modules\Machines\Infrastructure\Adapters;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseData;
|
||||
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
|
||||
use App\Modules\Inventory\Application\UseCases\ReverseMaintenanceStockUse;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
/**
|
||||
* Records stock used at machine maintenance through the Inventory module.
|
||||
* A failure (e.g. the item is out of use) does not undo the maintenance.
|
||||
* Records stock used at machine maintenance through the Inventory module,
|
||||
* and returns it when the maintenance record is cancelled. A failure to
|
||||
* record (e.g. the item is out of use) does not undo the maintenance.
|
||||
*/
|
||||
class StockForMachines implements MaintenanceMaterials
|
||||
{
|
||||
public function __construct(private RecordStockUse $recordUse) {}
|
||||
public function __construct(
|
||||
private RecordStockUse $recordUse,
|
||||
private ReverseMaintenanceStockUse $reverseUse,
|
||||
) {}
|
||||
|
||||
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool
|
||||
{
|
||||
@@ -31,4 +36,9 @@ class StockForMachines implements MaintenanceMaterials
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function returnUseOf(int $maintenanceRecordId, int $userId): void
|
||||
{
|
||||
$this->reverseUse->execute($maintenanceRecordId, $userId);
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -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()
|
||||
|
||||
@@ -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),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -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,60 @@ 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
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
|
||||
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 +554,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 +638,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 +831,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 +867,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 +899,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 +911,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
|
||||
|
||||
@@ -150,7 +150,7 @@ new class extends Component
|
||||
|
||||
<div>
|
||||
@if ($this->canPlan() || $this->row !== null)
|
||||
<section aria-label="{{ __('machines.task.list_of', ['title' => $taskTitle]) }}" class="space-y-2">
|
||||
<section data-task-section aria-label="{{ __('machines.task.list_of', ['title' => $taskTitle]) }}" class="space-y-2">
|
||||
<h4 class="font-medium">{{ __('machines.task.title') }}</h4>
|
||||
|
||||
<p id="task-{{ $taskId }}-machine-status" tabindex="-1" role="status" aria-live="polite" class="text-sm focus:outline-none">{{ $message }}</p>
|
||||
|
||||
@@ -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::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');
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ final readonly class OrderLineSummary
|
||||
public ?int $currentStep,
|
||||
public array $currentMaterials,
|
||||
public bool $isMade,
|
||||
public int $productId = 0,
|
||||
) {}
|
||||
|
||||
public function hasProduction(): bool
|
||||
|
||||
@@ -27,6 +27,7 @@ final readonly class OrderSummary
|
||||
public ?int $saleId,
|
||||
public int $totalCents,
|
||||
public array $lines,
|
||||
public bool $canBeChanged = false,
|
||||
) {}
|
||||
|
||||
public function isPaid(): bool
|
||||
|
||||
@@ -29,6 +29,7 @@ use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
@@ -72,6 +73,70 @@ final class QuickSaleOrders
|
||||
* @throws OrderHasNoProduction
|
||||
*/
|
||||
public function send(int $sellerId, OrderData $data): OrderResult
|
||||
{
|
||||
$lines = $this->lines($data);
|
||||
$now = $this->clock->now();
|
||||
$today = $this->clock->today();
|
||||
|
||||
return $this->transactions->run(function () use ($sellerId, $data, $lines, $now, $today): OrderResult {
|
||||
$order = QuickSaleOrder::place($today, $this->orders->nextPickupNumber($today), $now, $sellerId, $data->customerId, $data->customerName, $lines);
|
||||
$order = $this->orders->save($order);
|
||||
$this->enqueueFirstSteps($order);
|
||||
|
||||
return $this->result($order);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes an order's products and customer before making has started
|
||||
* on any line (spec 19.7): the lines are replaced with the products'
|
||||
* current prices and processes, and the work lists follow. The pickup
|
||||
* number stays.
|
||||
*
|
||||
* @throws QuickSaleOrderNotFound
|
||||
* @throws QuickSaleOrderClosed
|
||||
* @throws QuickSaleOrderInProduction
|
||||
* @throws ProductNotSellable
|
||||
* @throws InvalidQuantity
|
||||
* @throws QuickSaleEmpty
|
||||
* @throws QuickSaleCustomerNotFound
|
||||
* @throws OrderHasNoProduction
|
||||
*/
|
||||
public function change(int $orderId, OrderData $data): OrderResult
|
||||
{
|
||||
$lines = $this->lines($data);
|
||||
|
||||
return $this->transactions->run(function () use ($orderId, $data, $lines): OrderResult {
|
||||
$order = $this->orders->lockById($orderId) ?? throw new QuickSaleOrderNotFound;
|
||||
$oldLines = $order->lines();
|
||||
|
||||
$order->change($data->customerId, $data->customerName, $lines);
|
||||
|
||||
foreach ($oldLines as $line) {
|
||||
if ($line->isInProduction()) {
|
||||
$this->queue->remove((int) $line->id());
|
||||
}
|
||||
}
|
||||
|
||||
$order = $this->orders->save($order);
|
||||
$this->enqueueFirstSteps($order);
|
||||
|
||||
return $this->result($order);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* New order lines of the products with their current prices and
|
||||
* production processes.
|
||||
*
|
||||
* @return list<OrderLine>
|
||||
*
|
||||
* @throws ProductNotSellable
|
||||
* @throws InvalidQuantity
|
||||
* @throws QuickSaleCustomerNotFound
|
||||
* @throws OrderHasNoProduction
|
||||
*/
|
||||
private function lines(OrderData $data): array
|
||||
{
|
||||
$sellable = [];
|
||||
foreach ($this->products->sellable() as $product) {
|
||||
@@ -89,7 +154,6 @@ final class QuickSaleOrders
|
||||
}
|
||||
|
||||
$now = $this->clock->now();
|
||||
$today = $this->clock->today();
|
||||
$lines = [];
|
||||
|
||||
foreach ($data->quantities as $productId => $quantity) {
|
||||
@@ -101,22 +165,25 @@ final class QuickSaleOrders
|
||||
);
|
||||
}
|
||||
|
||||
return $this->transactions->run(function () use ($sellerId, $data, $lines, $now, $today): OrderResult {
|
||||
$order = QuickSaleOrder::place($today, $this->orders->nextPickupNumber($today), $now, $sellerId, $data->customerId, $data->customerName, $lines);
|
||||
$order = $this->orders->save($order);
|
||||
return $lines;
|
||||
}
|
||||
|
||||
foreach ($order->lines() as $line) {
|
||||
$step = $line->currentStep();
|
||||
private function enqueueFirstSteps(QuickSaleOrder $order): void
|
||||
{
|
||||
foreach ($order->lines() as $line) {
|
||||
$step = $line->currentStep();
|
||||
|
||||
if ($step !== null && $step->machineId !== null) {
|
||||
$this->queue->enqueue((int) $line->id(), 0, $step->machineId, $today);
|
||||
}
|
||||
if ($step !== null && $step->machineId !== null) {
|
||||
$this->queue->enqueue((int) $line->id(), 0, $step->machineId, $order->orderedOn());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines()));
|
||||
private function result(QuickSaleOrder $order): OrderResult
|
||||
{
|
||||
$total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines()));
|
||||
|
||||
return new OrderResult((int) $order->id(), $order->pickupNumber(), $total);
|
||||
});
|
||||
return new OrderResult((int) $order->id(), $order->pickupNumber(), $total);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Modules\Sales\Domain\Entities;
|
||||
use App\Modules\Sales\Domain\Enums\OrderStatus;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid;
|
||||
use DateTimeImmutable;
|
||||
|
||||
@@ -121,6 +122,54 @@ final class QuickSaleOrder
|
||||
$this->cancelledBy = $userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether no step has been completed on any line yet.
|
||||
*/
|
||||
public function canBeChanged(): bool
|
||||
{
|
||||
if ($this->paidAt !== null || $this->cancelledAt !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->lines as $line) {
|
||||
if ($line->hasStarted()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the products and the customer before making has started; the
|
||||
* pickup number stays.
|
||||
*
|
||||
* @param list<OrderLine> $lines
|
||||
*
|
||||
* @throws QuickSaleOrderClosed
|
||||
* @throws QuickSaleOrderInProduction
|
||||
* @throws QuickSaleEmpty
|
||||
*/
|
||||
public function change(?int $customerId, ?string $customerName, array $lines): void
|
||||
{
|
||||
if ($this->paidAt !== null || $this->cancelledAt !== null) {
|
||||
throw new QuickSaleOrderClosed;
|
||||
}
|
||||
|
||||
if (! $this->canBeChanged()) {
|
||||
throw new QuickSaleOrderInProduction;
|
||||
}
|
||||
|
||||
if ($lines === []) {
|
||||
throw new QuickSaleEmpty;
|
||||
}
|
||||
|
||||
$customerName = $customerName === null ? null : mb_substr(trim($customerName), 0, 150);
|
||||
$this->customerId = $customerId;
|
||||
$this->customerName = $customerName === '' ? null : $customerName;
|
||||
$this->lines = $lines;
|
||||
}
|
||||
|
||||
public function lineById(int $lineId): ?OrderLine
|
||||
{
|
||||
foreach ($this->lines as $line) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleOrderInProduction extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Making the order has already started, so it cannot be changed.');
|
||||
}
|
||||
}
|
||||
+4
@@ -88,6 +88,9 @@ class EloquentQuickSaleOrderQueries implements QuickSaleOrderQueries
|
||||
saleId: $model->sale?->id,
|
||||
totalCents: array_sum(array_map(fn (OrderLineSummary $line): int => $line->totalCents, $lines)),
|
||||
lines: $lines,
|
||||
canBeChanged: $model->paid_at === null && $model->cancelled_at === null && $model->lines->every(
|
||||
fn (QuickSaleOrderLineModel $line): bool => $line->production_steps === [] || $line->current_step === 0,
|
||||
),
|
||||
);
|
||||
})->values()->all();
|
||||
}
|
||||
@@ -110,6 +113,7 @@ class EloquentQuickSaleOrderQueries implements QuickSaleOrderQueries
|
||||
currentStep: $line->current_step,
|
||||
currentMaterials: array_map(fn (array $material): array => ['stockItemId' => (int) $material['stockItemId'], 'quantityMilli' => (int) $material['quantityMilli']], $current['materials'] ?? []),
|
||||
isMade: $line->made_at !== null,
|
||||
productId: $line->product_id,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -55,6 +55,8 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository
|
||||
'cancelled_by' => $order->cancelledBy(),
|
||||
])->save();
|
||||
|
||||
$keptIds = [];
|
||||
|
||||
foreach ($order->lines() as $index => $line) {
|
||||
$lineModel = $line->id() === null ? new QuickSaleOrderLineModel(['quick_sale_order_id' => $model->id]) : QuickSaleOrderLineModel::query()->findOrFail($line->id());
|
||||
|
||||
@@ -69,8 +71,12 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository
|
||||
'made_at' => $line->madeAt()?->format('Y-m-d H:i:s'),
|
||||
'sort_order' => $index + 1,
|
||||
])->save();
|
||||
$keptIds[] = $lineModel->id;
|
||||
}
|
||||
|
||||
// Lines left out of a changed order are removed (nothing refers to them before making starts).
|
||||
QuickSaleOrderLineModel::query()->where('quick_sale_order_id', $model->id)->whereNotIn('id', $keptIds)->delete();
|
||||
|
||||
return $this->lockById($model->id) ?? $order;
|
||||
}
|
||||
|
||||
|
||||
@@ -226,6 +226,13 @@ new class extends Component
|
||||
$this->js("document.getElementById('orders-status')?.focus()");
|
||||
}
|
||||
|
||||
public function edit(int $orderId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$this->dispatch('edit-quick-sale-order', orderId: $this->order($orderId)->id);
|
||||
}
|
||||
|
||||
public function confirmCancel(int $orderId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
@@ -378,7 +385,7 @@ new class extends Component
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<x-button wire:click="startComplete({{ $line->id }})" subtle color="black" sm icon="check" :text="__('sales.orders.complete_step')" :aria-label="__('sales.orders.complete_step_named', ['number' => $order->pickupNumber, 'product' => $line->productName])" />
|
||||
@if ($line->currentMachineId() !== null)
|
||||
<x-link :href="route('machines.console', $line->currentMachineId())" class="text-sm">{{ __('sales.orders.open_console', ['machine' => $this->machineNames[$line->currentMachineId()] ?? '']) }}</x-link>
|
||||
<x-link :href="route('console.handoff', ['to' => route('machines.console', $line->currentMachineId())])" blank class="text-sm">{{ __('sales.orders.open_console', ['machine' => $this->machineNames[$line->currentMachineId()] ?? '']) }}<span class="sr-only"> ({{ __('layout.opens_in_new_window') }})</span></x-link>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
@@ -408,6 +415,9 @@ new class extends Component
|
||||
@else
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<x-button wire:click="startPay({{ $order->id }})" sm icon="banknotes" :text="__('sales.orders.pay')" :aria-label="__('sales.orders.pay_named', ['number' => $order->pickupNumber])" />
|
||||
@if ($order->canBeChanged)
|
||||
<x-button wire:click="edit({{ $order->id }})" subtle color="black" sm icon="pencil" :text="__('sales.orders.change')" :aria-label="__('sales.orders.change_named', ['number' => $order->pickupNumber])" />
|
||||
@endif
|
||||
<x-button wire:click="confirmCancel({{ $order->id }})" subtle color="black" sm icon="x-mark" :text="__('sales.orders.cancel')" :aria-label="__('sales.orders.cancel_named', ['number' => $order->pickupNumber])" />
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@@ -4,6 +4,10 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Application\DTOs\CustomerSummary;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\Contracts\ProductionProcesses;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound;
|
||||
use App\Modules\Sales\Application\DTOs\OrderData;
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
|
||||
@@ -22,6 +26,7 @@ use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Attributes\On;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
@@ -74,6 +79,57 @@ new class extends Component
|
||||
|
||||
public string $orderCustomerName = '';
|
||||
|
||||
/**
|
||||
* The open order being changed on this form, if any (spec 19.7).
|
||||
*/
|
||||
#[Locked]
|
||||
public ?int $editingOrderId = null;
|
||||
|
||||
#[Locked]
|
||||
public ?int $editingPickupNumber = null;
|
||||
|
||||
/**
|
||||
* Loads an order whose making has not started into the form to change
|
||||
* its products and customer.
|
||||
*/
|
||||
#[On('edit-quick-sale-order')]
|
||||
public function editOrder(int $orderId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$order = app(QuickSaleOrderQueries::class)->findOrder($orderId) ?? abort(404);
|
||||
|
||||
if (! $order->canBeChanged) {
|
||||
$this->addError('sale', __('sales.orders.errors.started'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->reset('quantities', 'cartMessage', 'savedMessage', 'hoursMessage', 'savedSaleId', 'savedPickupNumber');
|
||||
|
||||
foreach ($order->lines as $line) {
|
||||
$this->quantities[$line->productId] = $line->quantity;
|
||||
}
|
||||
|
||||
$this->editingOrderId = $order->id;
|
||||
$this->editingPickupNumber = $order->pickupNumber;
|
||||
$this->customerId = $order->customerId;
|
||||
$this->customerName = $order->customerId === null ? '' : (string) $order->customerName;
|
||||
$this->orderCustomerName = $order->customerId === null ? (string) $order->customerName : '';
|
||||
$this->resetErrorBag();
|
||||
$this->forgetLines();
|
||||
$this->cartMessage = __('sales.orders.editing', ['number' => $order->pickupNumber]);
|
||||
$this->js("document.getElementById('cart-heading')?.focus()");
|
||||
}
|
||||
|
||||
public function stopEditing(): void
|
||||
{
|
||||
$this->reset('quantities', 'customerSearch', 'customerId', 'customerName', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
|
||||
$this->forgetLines();
|
||||
$this->cartMessage = __('sales.orders.editing_stopped');
|
||||
$this->js("document.getElementById('cart-heading')?.focus()");
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
@@ -257,7 +313,7 @@ new class extends Component
|
||||
$this->savedSaleId = null;
|
||||
$this->savedPickupNumber = null;
|
||||
|
||||
if ($this->isOrder()) {
|
||||
if ($this->isOrder() || $this->editingOrderId !== null) {
|
||||
$this->sendOrder($orders);
|
||||
|
||||
return;
|
||||
@@ -334,11 +390,24 @@ new class extends Component
|
||||
{
|
||||
$this->validate(['orderCustomerName' => ['nullable', 'string', 'max:150']]);
|
||||
|
||||
$data = new OrderData($this->quantities, $this->customerId, $this->orderCustomerName);
|
||||
|
||||
try {
|
||||
$result = $orders->send((int) auth()->id(), new OrderData($this->quantities, $this->customerId, $this->orderCustomerName));
|
||||
} catch (QuickSaleEmpty|InvalidQuantity|OrderHasNoProduction) {
|
||||
$result = $this->editingOrderId === null
|
||||
? $orders->send((int) auth()->id(), $data)
|
||||
: $orders->change($this->editingOrderId, $data);
|
||||
} catch (QuickSaleEmpty|InvalidQuantity) {
|
||||
$this->addError('quantities', __('sales.errors.empty'));
|
||||
|
||||
return;
|
||||
} catch (OrderHasNoProduction) {
|
||||
$this->addError('quantities', __($this->editingOrderId === null ? 'sales.errors.empty' : 'sales.orders.errors.no_production'));
|
||||
|
||||
return;
|
||||
} catch (QuickSaleOrderInProduction|QuickSaleOrderClosed|QuickSaleOrderNotFound) {
|
||||
$this->addError('sale', __('sales.orders.errors.started'));
|
||||
$this->stopEditing();
|
||||
|
||||
return;
|
||||
} catch (ProductNotSellable $exception) {
|
||||
unset($this->quantities[$exception->id], $this->products);
|
||||
@@ -354,9 +423,9 @@ new class extends Component
|
||||
}
|
||||
|
||||
$this->savedPickupNumber = $result->pickupNumber;
|
||||
$this->savedMessage = __('sales.orders.sent', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]);
|
||||
$this->savedMessage = __($this->editingOrderId === null ? 'sales.orders.sent' : 'sales.orders.changed', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]);
|
||||
|
||||
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName');
|
||||
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
|
||||
$this->forgetLines();
|
||||
$this->dispatch('quick-sale-orders-changed');
|
||||
|
||||
@@ -536,9 +605,16 @@ new class extends Component
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@php($isOrder = $this->isOrder())
|
||||
@php($isOrder = $this->isOrder() || $editingOrderId !== null)
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
@if ($editingOrderId !== null)
|
||||
<div class="flex flex-wrap items-center gap-3 rounded-lg border border-zinc-400 p-3 text-sm dark:border-zinc-500">
|
||||
<x-icon name="pencil" class="size-5 shrink-0" aria-hidden="true" />
|
||||
<p class="grow">{{ __('sales.orders.editing_notice', ['number' => $editingPickupNumber]) }}</p>
|
||||
<x-button id="stop-editing" wire:click="stopEditing" subtle color="black" sm :text="__('sales.orders.stop_editing')" />
|
||||
</div>
|
||||
@endif
|
||||
@if ($isOrder)
|
||||
<p class="flex items-start gap-2 rounded-lg border border-zinc-400 p-3 text-sm dark:border-zinc-500">
|
||||
<x-icon name="printer" class="size-5 shrink-0" aria-hidden="true" />
|
||||
@@ -616,7 +692,7 @@ new class extends Component
|
||||
/>
|
||||
@endunless
|
||||
|
||||
<x-button submit lg class="w-full" :text="$isOrder ? __('sales.orders.send') : __('sales.sell.save')" />
|
||||
<x-button submit lg class="w-full" :text="$editingOrderId !== null ? __('sales.orders.save_change') : ($isOrder ? __('sales.orders.send') : __('sales.sell.save'))" />
|
||||
</form>
|
||||
@endif
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\Contracts;
|
||||
|
||||
/**
|
||||
* One-way hashing of passwords and PIN codes.
|
||||
*/
|
||||
interface SecretHasher
|
||||
{
|
||||
public function hash(string $secret): string;
|
||||
|
||||
public function check(string $secret, string $hash): bool;
|
||||
}
|
||||
@@ -36,6 +36,14 @@ interface UserAccountQueries
|
||||
*/
|
||||
public function activeUserOptions(): array;
|
||||
|
||||
/**
|
||||
* Users who may sign in today and have a console PIN code, ordered by
|
||||
* name, for switching user on a machine console.
|
||||
*
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
public function pinLoginOptions(): array;
|
||||
|
||||
/**
|
||||
* User names for many ids at once, active or not (for lists and history).
|
||||
*
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\SecretHasher;
|
||||
use App\Modules\Users\Domain\Contracts\LoginSecrets;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
|
||||
use App\Modules\Users\Domain\Exceptions\WrongPassword;
|
||||
use App\Modules\Users\Domain\ValueObjects\LoginPin;
|
||||
|
||||
/**
|
||||
* Users' own PIN codes for switching user on a machine console (spec
|
||||
* 19.6): a user sets one with their password, and the console signs them
|
||||
* in with it while their account may sign in. Only the hash is stored.
|
||||
*/
|
||||
final class LoginPins
|
||||
{
|
||||
public function __construct(
|
||||
private LoginSecrets $secrets,
|
||||
private SecretHasher $hasher,
|
||||
private CheckLoginAllowed $loginAllowed,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidLoginPin
|
||||
* @throws WrongPassword
|
||||
*/
|
||||
public function set(int $userId, string $currentPassword, string $pin): void
|
||||
{
|
||||
$pin = new LoginPin($pin);
|
||||
$this->checkPassword($userId, $currentPassword);
|
||||
|
||||
$this->transactions->run(fn () => $this->secrets->storePinHash($userId, $this->hasher->hash($pin->value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws WrongPassword
|
||||
*/
|
||||
public function remove(int $userId, string $currentPassword): void
|
||||
{
|
||||
$this->checkPassword($userId, $currentPassword);
|
||||
|
||||
$this->transactions->run(fn () => $this->secrets->storePinHash($userId, null));
|
||||
}
|
||||
|
||||
public function has(int $userId): bool
|
||||
{
|
||||
return $this->secrets->pinHashOf($userId) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the PIN code is the user's and the user may sign in today.
|
||||
*/
|
||||
public function verify(int $userId, string $pin): bool
|
||||
{
|
||||
$hash = $this->secrets->pinHashOf($userId);
|
||||
|
||||
return $hash !== null
|
||||
&& preg_match('/^\d{'.LoginPin::MIN_LENGTH.','.LoginPin::MAX_LENGTH.'}$/', trim($pin)) === 1
|
||||
&& $this->hasher->check(trim($pin), $hash)
|
||||
&& $this->loginAllowed->execute($userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws WrongPassword
|
||||
*/
|
||||
private function checkPassword(int $userId, string $password): void
|
||||
{
|
||||
$hash = $this->secrets->passwordHashOf($userId);
|
||||
|
||||
if ($hash === null || ! $this->hasher->check($password, $hash)) {
|
||||
throw new WrongPassword;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Contracts;
|
||||
|
||||
/**
|
||||
* The hashes of a user's password and console PIN code.
|
||||
*/
|
||||
interface LoginSecrets
|
||||
{
|
||||
public function passwordHashOf(int $userId): ?string;
|
||||
|
||||
public function pinHashOf(int $userId): ?string;
|
||||
|
||||
/**
|
||||
* Stores the hash of the user's PIN code, or removes it with null.
|
||||
*/
|
||||
public function storePinHash(int $userId, ?string $hash): void;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidLoginPin extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The PIN code must be 4–6 digits.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class WrongPassword extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The current password is not correct.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
|
||||
|
||||
/**
|
||||
* A user's own PIN code for switching user on a machine console: 4–6
|
||||
* digits. It is never stored as such, only its hash.
|
||||
*/
|
||||
final readonly class LoginPin
|
||||
{
|
||||
public const int MIN_LENGTH = 4;
|
||||
|
||||
public const int MAX_LENGTH = 6;
|
||||
|
||||
public string $value;
|
||||
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$value = trim($value);
|
||||
|
||||
if (preg_match('/^\d{'.self::MIN_LENGTH.','.self::MAX_LENGTH.'}$/', $value) !== 1) {
|
||||
throw new InvalidLoginPin;
|
||||
}
|
||||
|
||||
$this->value = $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Auth;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\SecretHasher;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class LaravelSecretHasher implements SecretHasher
|
||||
{
|
||||
public function hash(string $secret): string
|
||||
{
|
||||
return Hash::make($secret);
|
||||
}
|
||||
|
||||
public function check(string $secret, string $hash): bool
|
||||
{
|
||||
return Hash::check($secret, $hash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Domain\Contracts\LoginSecrets;
|
||||
|
||||
class EloquentLoginSecrets implements LoginSecrets
|
||||
{
|
||||
public function passwordHashOf(int $userId): ?string
|
||||
{
|
||||
$hash = User::query()->whereKey($userId)->value('password');
|
||||
|
||||
return $hash === null ? null : (string) $hash;
|
||||
}
|
||||
|
||||
public function pinHashOf(int $userId): ?string
|
||||
{
|
||||
$hash = User::query()->whereKey($userId)->value('pin_hash');
|
||||
|
||||
return $hash === null ? null : (string) $hash;
|
||||
}
|
||||
|
||||
public function storePinHash(int $userId, ?string $hash): void
|
||||
{
|
||||
User::query()->whereKey($userId)->update(['pin_hash' => $hash]);
|
||||
}
|
||||
}
|
||||
+20
@@ -3,6 +3,7 @@
|
||||
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use App\Modules\Users\Application\DTOs\UserSummary;
|
||||
@@ -12,6 +13,10 @@ use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class EloquentUserAccountQueries implements UserAccountQueries
|
||||
{
|
||||
public function __construct(
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
public function findSummary(int $id): ?UserSummary
|
||||
{
|
||||
$model = User::query()->with(['supervisor:id,name', 'moneyPermissions'])->find($id);
|
||||
@@ -61,6 +66,21 @@ class EloquentUserAccountQueries implements UserAccountQueries
|
||||
->all();
|
||||
}
|
||||
|
||||
public function pinLoginOptions(): array
|
||||
{
|
||||
$today = $this->clock->today()->format('Y-m-d');
|
||||
|
||||
return User::query()
|
||||
->where('is_active', true)
|
||||
->whereNotNull('pin_hash')
|
||||
->where(fn (Builder $query) => $query->whereNull('employment_ends_on')->orWhereDate('employment_ends_on', '>=', $today))
|
||||
->orderBy('name')
|
||||
->get(['id', 'name', 'role'])
|
||||
->map(fn (User $model): UserOption => new UserOption($model->id, $model->name, $model->role))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function namesByIds(array $ids): array
|
||||
{
|
||||
return $ids === [] ? [] : User::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
|
||||
|
||||
@@ -5,11 +5,15 @@ namespace App\Modules\Users\Infrastructure\Providers;
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Application\Contracts\SecretHasher;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Domain\Contracts\LoginSecrets;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Enums\MoneyPermission;
|
||||
use App\Modules\Users\Infrastructure\Auth\LaravelPasswordLinkSender;
|
||||
use App\Modules\Users\Infrastructure\Auth\LaravelSecretHasher;
|
||||
use App\Modules\Users\Infrastructure\Auth\PasswordLinkMail;
|
||||
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentLoginSecrets;
|
||||
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountQueries;
|
||||
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository;
|
||||
use App\Modules\Users\Infrastructure\SystemClock;
|
||||
@@ -17,6 +21,7 @@ use App\Modules\Users\Presentation\Console\CreateAdminCommand;
|
||||
use App\Modules\Users\Presentation\Http\Listeners\StoreLocaleChosenBeforeLogin;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use Illuminate\Auth\Events\Login;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Contracts\Auth\CanResetPassword;
|
||||
@@ -42,6 +47,8 @@ class UsersServiceProvider extends ServiceProvider
|
||||
UserAccountRepository::class => EloquentUserAccountRepository::class,
|
||||
UserAccountQueries::class => EloquentUserAccountQueries::class,
|
||||
PasswordLinkSender::class => LaravelPasswordLinkSender::class,
|
||||
LoginSecrets::class => EloquentLoginSecrets::class,
|
||||
SecretHasher::class => LaravelSecretHasher::class,
|
||||
];
|
||||
|
||||
public function register(): void
|
||||
@@ -59,6 +66,9 @@ class UsersServiceProvider extends ServiceProvider
|
||||
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
|
||||
}
|
||||
|
||||
// The machine console's own session and guard; before the session starts.
|
||||
$router->prependMiddlewareToGroup('web', UseConsoleSession::class);
|
||||
|
||||
$router->pushMiddlewareToGroup('web', EnsureAccountIsUsable::class);
|
||||
|
||||
// Ends the user's other sessions when their password changes.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Opens the machine console in its own window signed in as the same user
|
||||
* (spec 19.6). The normal user interface makes a one-time key valid for a
|
||||
* minute; the console's own session (UseConsoleSession) takes it and signs
|
||||
* the user in there. After that the two sessions live apart.
|
||||
*/
|
||||
class ConsoleHandoff
|
||||
{
|
||||
public const int SECONDS = 60;
|
||||
|
||||
/**
|
||||
* In the normal user interface: a key for the console page in "to".
|
||||
*/
|
||||
public function start(Request $request): RedirectResponse
|
||||
{
|
||||
$to = (string) $request->query('to', '');
|
||||
abort_unless(UseConsoleSession::isConsoleUrl($to), 404);
|
||||
|
||||
$token = Str::random(40);
|
||||
Cache::put(self::cacheKey($token), ['user' => (int) $request->user()?->getAuthIdentifier(), 'to' => $to], self::SECONDS);
|
||||
|
||||
return redirect()->route('console.handoff.accept', $token);
|
||||
}
|
||||
|
||||
/**
|
||||
* In the console's own session: signs in with the key once.
|
||||
*/
|
||||
public function accept(Request $request, string $token, CheckLoginAllowed $checkLoginAllowed): RedirectResponse
|
||||
{
|
||||
/** @var array{user: int, to: string}|null $handoff */
|
||||
$handoff = Cache::pull(self::cacheKey($token));
|
||||
|
||||
if ($handoff === null || ! $checkLoginAllowed->execute($handoff['user'])) {
|
||||
return redirect()->route('console.login');
|
||||
}
|
||||
|
||||
if (Auth::check()) {
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
}
|
||||
|
||||
Auth::loginUsingId($handoff['user']);
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->to($handoff['to']);
|
||||
}
|
||||
|
||||
private static function cacheKey(string $token): string
|
||||
{
|
||||
return 'console-handoff|'.hash('sha256', $token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* Signs out of the machine console's own session only (spec 19.6), e.g. to
|
||||
* sign in there with email and password; the normal user interface stays
|
||||
* signed in. The console's sign-in page returns to the console page.
|
||||
*/
|
||||
class ConsoleLogoutController
|
||||
{
|
||||
public function __invoke(Request $request): RedirectResponse
|
||||
{
|
||||
$locale = app()->getLocale();
|
||||
$returnTo = (string) $request->input('return_to', '');
|
||||
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
$request->session()->put(SetLocale::SESSION_KEY, $locale);
|
||||
|
||||
if (UseConsoleSession::isConsoleUrl($returnTo)) {
|
||||
$request->session()->put('url.intended', $returnTo);
|
||||
}
|
||||
|
||||
return redirect()->route('console.login');
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ class EnsureAccountIsUsable
|
||||
|
||||
// The reason goes in the URL: Livewire follows this redirect with
|
||||
// fetch first, which would consume a flashed message.
|
||||
return redirect()->route('login', ['access' => 'ended']);
|
||||
return redirect()->route(UseConsoleSession::isConsole($request) ? 'console.login' : 'login', ['access' => 'ended']);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Session\SessionManager;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Gives the machine console its own session (spec 19.6), so the console can
|
||||
* run in its own window or on a tablet next to the normal user interface
|
||||
* in the same browser: pages under console/ and the Livewire requests of
|
||||
* components rendered there use a session cookie of their own and the
|
||||
* "console" guard. Signing in or out on one side leaves the other alone,
|
||||
* and /login always signs in to the normal user interface.
|
||||
*
|
||||
* Runs before StartSession. A Livewire request tells where its component
|
||||
* was rendered by the path Livewire keeps in the snapshot (memo.path); it
|
||||
* can only choose between the browser's own sessions, and the CSRF token
|
||||
* of that session must still match.
|
||||
*/
|
||||
class UseConsoleSession
|
||||
{
|
||||
public const string PREFIX = 'console';
|
||||
|
||||
public const string GUARD = 'console';
|
||||
|
||||
public const string DEFAULT_GUARD = 'web';
|
||||
|
||||
public function __construct(private SessionManager $sessions) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$console = self::isConsole($request);
|
||||
$cookie = (string) config('session.cookie');
|
||||
|
||||
$this->sessions->driver()->setName($console ? $cookie.'_console' : $cookie);
|
||||
Auth::shouldUse($console ? self::GUARD : self::DEFAULT_GUARD);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
public static function isConsole(Request $request): bool
|
||||
{
|
||||
if (self::isConsolePath($request->path())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! $request->hasHeader('X-Livewire')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$snapshot = json_decode((string) $request->input('components.0.snapshot', ''), true);
|
||||
$path = is_array($snapshot) ? ($snapshot['memo']['path'] ?? null) : null;
|
||||
|
||||
return is_string($path) && self::isConsolePath($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a URL of this application is on the console.
|
||||
*/
|
||||
public static function isConsoleUrl(string $url): bool
|
||||
{
|
||||
$base = rtrim(url('/'), '/').'/';
|
||||
|
||||
return Str::startsWith($url, $base.self::PREFIX.'/') && ! Str::contains($url, ['\\', '@']);
|
||||
}
|
||||
|
||||
private static function isConsolePath(string $path): bool
|
||||
{
|
||||
$path = trim($path, '/');
|
||||
|
||||
return $path === self::PREFIX || str_starts_with($path, self::PREFIX.'/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Signing in with email and password, on the login page and on the
|
||||
* machine console's sign-in page: 5 failed attempts a minute per email and
|
||||
* address, 20 per address across all accounts (password spraying), and one
|
||||
* message for a wrong password and a disabled account. Signs in to the
|
||||
* request's guard (the console's own on console pages).
|
||||
*
|
||||
* @property string $email
|
||||
* @property string $password
|
||||
*/
|
||||
trait SignsInWithPassword
|
||||
{
|
||||
public string $email = '';
|
||||
|
||||
public string $password = '';
|
||||
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
protected function signInWithPassword(CheckLoginAllowed $checkLoginAllowed, bool $remember = false): void
|
||||
{
|
||||
$this->email = trim($this->email);
|
||||
|
||||
$this->validate(
|
||||
['email' => ['required', 'string', 'email'], 'password' => ['required', 'string']],
|
||||
[
|
||||
'email.required' => __('auth.email_required'),
|
||||
'email.email' => __('auth.email_invalid'),
|
||||
'password.required' => __('auth.password_required'),
|
||||
],
|
||||
);
|
||||
|
||||
$email = Str::lower(trim($this->email));
|
||||
$throttleKey = Str::transliterate($email.'|'.request()->ip());
|
||||
$ipThrottleKey = 'login-ip|'.request()->ip();
|
||||
|
||||
foreach ([$throttleKey => 5, $ipThrottleKey => 20] as $key => $maxAttempts) {
|
||||
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($key)]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$signedIn = Auth::attemptWhen(
|
||||
['email' => $email, 'password' => $this->password],
|
||||
fn ($user): bool => $checkLoginAllowed->execute($user->getAuthIdentifier()),
|
||||
$remember,
|
||||
);
|
||||
|
||||
if (! $signedIn) {
|
||||
RateLimiter::hit($throttleKey);
|
||||
RateLimiter::hit($ipThrottleKey);
|
||||
$this->reset('password');
|
||||
|
||||
// One message for a wrong password and a disabled account, so the
|
||||
// form never confirms that a disabled account's password is right.
|
||||
throw ValidationException::withMessages(['email' => __('auth.failed')]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
session()->regenerate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use App\Modules\Users\Application\UseCases\LoginPins;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Livewire\Attributes\Computed;
|
||||
|
||||
/**
|
||||
* Signing in with a user's own console PIN code (spec 19.6): the user picks
|
||||
* their name and types the PIN. Five wrong PIN codes lock the user's PIN
|
||||
* sign-in for 15 minutes, and one address may try 20 times a minute. Ends
|
||||
* the request's guard's earlier sign-in (the console's own on console
|
||||
* pages) and starts a new session for the user.
|
||||
*/
|
||||
trait SignsInWithPin
|
||||
{
|
||||
public string $userId = '';
|
||||
|
||||
public string $pin = '';
|
||||
|
||||
/**
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
#[Computed]
|
||||
public function pinUsers(): array
|
||||
{
|
||||
return app(UserAccountQueries::class)->pinLoginOptions();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Whether the user is now signed in.
|
||||
*/
|
||||
protected function signInWithPin(LoginPins $pins): bool
|
||||
{
|
||||
$this->resetErrorBag();
|
||||
|
||||
$user = collect($this->pinUsers)->firstWhere('id', (int) $this->userId);
|
||||
|
||||
if ($user === null) {
|
||||
$this->addError('userId', __('users.pin_switch.errors.user'));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$userKey = 'pin-login|user|'.$user->id;
|
||||
$ipKey = 'pin-login|ip|'.request()->ip();
|
||||
|
||||
foreach ([[$userKey, 5], [$ipKey, 20]] as [$key, $max]) {
|
||||
if (RateLimiter::tooManyAttempts($key, $max)) {
|
||||
$this->addError('pin', __('users.pin_switch.errors.locked', ['minutes' => (int) ceil(RateLimiter::availableIn($key) / 60)]));
|
||||
$this->pin = '';
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
RateLimiter::hit($ipKey, 60);
|
||||
|
||||
if (! $pins->verify($user->id, $this->pin)) {
|
||||
RateLimiter::hit($userKey, 900);
|
||||
$this->addError('pin', __('users.pin_switch.errors.pin'));
|
||||
$this->pin = '';
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
RateLimiter::clear($userKey);
|
||||
|
||||
if (Auth::check()) {
|
||||
Auth::logout();
|
||||
session()->invalidate();
|
||||
session()->regenerateToken();
|
||||
}
|
||||
|
||||
Auth::loginUsingId($user->id);
|
||||
session()->regenerate();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use App\Modules\Users\Application\UseCases\LoginPins;
|
||||
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPassword;
|
||||
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPin;
|
||||
use Livewire\Attributes\Layout;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* Signing in to the machine console's own session (spec 19.6), e.g. on a
|
||||
* tablet next to the machine: with the user's own PIN code or with email
|
||||
* and password. Returns to the console page that asked for it.
|
||||
*/
|
||||
new #[Layout('layouts.console')] class extends Component
|
||||
{
|
||||
use SignsInWithPassword;
|
||||
use SignsInWithPin;
|
||||
|
||||
public bool $accessEnded = false;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->accessEnded = request()->query('access') === 'ended';
|
||||
}
|
||||
|
||||
public function loginWithPin(LoginPins $pins): void
|
||||
{
|
||||
if ($this->signInWithPin($pins)) {
|
||||
$this->redirectIntended(route('machines.console-picker'));
|
||||
}
|
||||
}
|
||||
|
||||
public function loginWithPassword(CheckLoginAllowed $checkLoginAllowed): void
|
||||
{
|
||||
$this->signInWithPassword($checkLoginAllowed);
|
||||
|
||||
$this->redirectIntended(route('machines.console-picker'));
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('users.console_login.title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-3xl space-y-6 p-3 sm:p-6">
|
||||
<h1 class="text-2xl font-semibold">{{ __('users.console_login.title') }}</h1>
|
||||
|
||||
<p>{{ __('users.console_login.intro') }}</p>
|
||||
|
||||
@if ($accessEnded)
|
||||
<x-alert role="status" color="yellow" light icon="exclamation-triangle" :text="__('auth.account_disabled')" />
|
||||
@elseif (session('status'))
|
||||
<x-alert role="status" color="green" light icon="information-circle" :text="session('status')" />
|
||||
@endif
|
||||
|
||||
<div class="grid gap-6 md:grid-cols-2">
|
||||
<section aria-labelledby="console-login-pin" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="console-login-pin" class="text-xl font-semibold">{{ __('users.console_login.with_pin') }}</h2>
|
||||
@if ($this->pinUsers === [])
|
||||
<p>{{ __('users.pin_switch.no_users') }}</p>
|
||||
@else
|
||||
<form wire:submit="loginWithPin" class="space-y-4" novalidate>
|
||||
<x-users.pin-fields :users="$this->pinUsers" />
|
||||
<x-button submit icon="arrow-right-end-on-rectangle" :text="__('users.pin_switch.submit')" class="w-full" />
|
||||
</form>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="console-login-password" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="console-login-password" class="text-xl font-semibold">{{ __('users.console_login.with_password') }}</h2>
|
||||
<form wire:submit="loginWithPassword" class="space-y-4" novalidate>
|
||||
<x-input id="console-login-email" wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
|
||||
<x-password-field id="console-login-password-field" wire:model="password" :label="__('auth.password_label')" autocomplete="current-password" required />
|
||||
<x-button submit :text="__('auth.login')" class="w-full" />
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,25 +1,12 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPassword;
|
||||
use Livewire\Component;
|
||||
|
||||
new class extends Component
|
||||
{
|
||||
public const int MAX_ATTEMPTS_PER_MINUTE = 5;
|
||||
|
||||
/**
|
||||
* Failed attempts from one address across all accounts, so one common
|
||||
* password cannot be tried on every account (password spraying).
|
||||
*/
|
||||
public const int MAX_ATTEMPTS_PER_IP_PER_MINUTE = 20;
|
||||
|
||||
public string $email = '';
|
||||
|
||||
public string $password = '';
|
||||
use SignsInWithPassword;
|
||||
|
||||
public bool $remember = false;
|
||||
|
||||
@@ -37,47 +24,7 @@ new class extends Component
|
||||
|
||||
public function login(CheckLoginAllowed $checkLoginAllowed): void
|
||||
{
|
||||
$this->email = trim($this->email);
|
||||
|
||||
$this->validate(
|
||||
['email' => ['required', 'string', 'email'], 'password' => ['required', 'string']],
|
||||
[
|
||||
'email.required' => __('auth.email_required'),
|
||||
'email.email' => __('auth.email_invalid'),
|
||||
'password.required' => __('auth.password_required'),
|
||||
],
|
||||
);
|
||||
|
||||
$email = Str::lower(trim($this->email));
|
||||
$throttleKey = Str::transliterate($email.'|'.request()->ip());
|
||||
$ipThrottleKey = 'login-ip|'.request()->ip();
|
||||
|
||||
foreach ([$throttleKey => self::MAX_ATTEMPTS_PER_MINUTE, $ipThrottleKey => self::MAX_ATTEMPTS_PER_IP_PER_MINUTE] as $key => $maxAttempts) {
|
||||
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($key)]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$signedIn = Auth::attemptWhen(
|
||||
['email' => $email, 'password' => $this->password],
|
||||
fn ($user): bool => $checkLoginAllowed->execute($user->getAuthIdentifier()),
|
||||
$this->remember,
|
||||
);
|
||||
|
||||
if (! $signedIn) {
|
||||
RateLimiter::hit($throttleKey);
|
||||
RateLimiter::hit($ipThrottleKey);
|
||||
$this->reset('password');
|
||||
|
||||
// One message for a wrong password and a disabled account, so the
|
||||
// form never confirms that a disabled account's password is right.
|
||||
throw ValidationException::withMessages(['email' => __('auth.failed')]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
session()->regenerate();
|
||||
$this->signInWithPassword($checkLoginAllowed, $this->remember);
|
||||
|
||||
$this->redirectIntended(route('home'));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\UseCases\LoginPins;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPin;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* "Vaihda käyttäjä" on a machine console (spec 19.6): the next user picks
|
||||
* their name and types their own PIN code. The console has its own session
|
||||
* (UseConsoleSession), so this changes only the console's user. Users
|
||||
* without a PIN code sign in with their email and password on the
|
||||
* console's sign-in page, back to the console.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use SignsInWithPin;
|
||||
|
||||
/**
|
||||
* The console to return to, given by the console page.
|
||||
*/
|
||||
#[Locked]
|
||||
public string $returnTo = '';
|
||||
|
||||
public function mount(string $returnTo): void
|
||||
{
|
||||
abort_unless(UseConsoleSession::isConsoleUrl($returnTo) && ! str_contains($returnTo, '?'), 404);
|
||||
|
||||
$this->returnTo = $returnTo;
|
||||
}
|
||||
|
||||
public function switchUser(LoginPins $pins): void
|
||||
{
|
||||
if ($this->signInWithPin($pins)) {
|
||||
$this->redirect($this->returnTo);
|
||||
}
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view();
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
@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';
|
||||
@endphp
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
id="pin-switch-open"
|
||||
x-on:click="document.getElementById('pin-switch-dialog').showModal()"
|
||||
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>
|
||||
|
||||
<x-confirm-dialog id="pin-switch-dialog" :title="__('users.pin_switch.title')" class="text-base">
|
||||
@if ($this->pinUsers === [])
|
||||
<p>{{ __('users.pin_switch.no_users') }}</p>
|
||||
@else
|
||||
<form id="pin-switch-form" wire:submit="switchUser" class="space-y-4" novalidate>
|
||||
<x-users.pin-fields :users="$this->pinUsers" />
|
||||
</form>
|
||||
@endif
|
||||
|
||||
<form method="POST" action="{{ route('console.logout') }}" class="mt-4 border-t border-zinc-300 pt-3 dark:border-zinc-600">
|
||||
@csrf
|
||||
<input type="hidden" name="return_to" value="{{ $returnTo }}">
|
||||
<button type="submit" class="text-sm font-medium text-primary-700 underline hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-primary-300">{{ __('users.pin_switch.with_password') }}</button>
|
||||
</form>
|
||||
|
||||
<x-slot:actions>
|
||||
@if ($this->pinUsers !== [])
|
||||
<x-button wire:click="switchUser" icon="arrow-right-end-on-rectangle" :text="__('users.pin_switch.submit')" />
|
||||
@endif
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
</div>
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\UseCases\LoginPins;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
|
||||
use App\Modules\Users\Domain\Exceptions\WrongPassword;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* The user's own PIN code for switching user on a machine console (spec
|
||||
* 19.6). Setting or removing it asks for the user's password, which may
|
||||
* be wrong 5 times a minute, as on the login page.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
public string $currentPassword = '';
|
||||
|
||||
public string $pin = '';
|
||||
|
||||
public string $pinConfirmation = '';
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
}
|
||||
|
||||
public function save(LoginPins $pins): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
$this->resetErrorBag();
|
||||
|
||||
if (trim($this->pin) !== trim($this->pinConfirmation)) {
|
||||
$this->addError('pinConfirmation', __('users.pin.errors.confirmation'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->passwordThrottled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$pins->set((int) auth()->id(), $this->currentPassword, $this->pin);
|
||||
} catch (InvalidLoginPin) {
|
||||
$this->addError('pin', __('users.pin.errors.pin'));
|
||||
|
||||
return;
|
||||
} catch (WrongPassword) {
|
||||
$this->wrongPassword();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
RateLimiter::clear($this->throttleKey());
|
||||
|
||||
$this->reset('currentPassword', 'pin', 'pinConfirmation');
|
||||
$this->message = __('users.pin.saved');
|
||||
}
|
||||
|
||||
public function remove(LoginPins $pins): void
|
||||
{
|
||||
$this->authorize('machines.use');
|
||||
$this->resetErrorBag();
|
||||
|
||||
if ($this->passwordThrottled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$pins->remove((int) auth()->id(), $this->currentPassword);
|
||||
} catch (WrongPassword) {
|
||||
$this->wrongPassword();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
RateLimiter::clear($this->throttleKey());
|
||||
|
||||
$this->reset('currentPassword', 'pin', 'pinConfirmation');
|
||||
$this->message = __('users.pin.removed');
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('users.pin.title'));
|
||||
}
|
||||
|
||||
private function throttleKey(): string
|
||||
{
|
||||
return 'pin-password|'.auth()->id();
|
||||
}
|
||||
|
||||
private function passwordThrottled(): bool
|
||||
{
|
||||
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->addError('currentPassword', __('auth.throttle', ['seconds' => RateLimiter::availableIn($this->throttleKey())]));
|
||||
$this->reset('currentPassword');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function wrongPassword(): void
|
||||
{
|
||||
RateLimiter::hit($this->throttleKey());
|
||||
$this->addError('currentPassword', __('users.pin.errors.password'));
|
||||
$this->reset('currentPassword');
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6">
|
||||
<h1 class="text-2xl font-semibold">{{ __('users.pin.title') }}</h1>
|
||||
|
||||
<p class="text-sm">{{ __('users.pin.intro') }}</p>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm font-medium">
|
||||
{{ $message !== '' ? $message : (app(LoginPins::class)->has((int) auth()->id()) ? __('users.pin.is_set') : __('users.pin.not_set')) }}
|
||||
</p>
|
||||
|
||||
<form wire:submit="save" class="space-y-4" novalidate>
|
||||
<x-password-field id="current-password" wire:model="currentPassword" :label="__('users.pin.current_password')" autocomplete="current-password" />
|
||||
<x-input id="pin" wire:model="pin" type="password" inputmode="numeric" maxlength="6" :label="__('users.pin.pin')" :hint="__('users.pin.pin_hint')" autocomplete="off" />
|
||||
<x-input id="pin-confirmation" wire:model="pinConfirmation" type="password" inputmode="numeric" maxlength="6" :label="__('users.pin.pin_confirmation')" autocomplete="off" />
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<x-button submit :text="__('users.pin.save')" />
|
||||
@if (app(LoginPins::class)->has((int) auth()->id()))
|
||||
<x-button wire:click="remove" subtle color="black" :text="__('users.pin.remove')" />
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Presentation\Http\Controllers\ConsoleHandoff;
|
||||
use App\Modules\Users\Presentation\Http\Controllers\ConsoleLogoutController;
|
||||
use App\Modules\Users\Presentation\Http\Controllers\LogoutController;
|
||||
use App\Modules\Users\Presentation\Http\Controllers\SwitchLocaleController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
@@ -12,8 +14,17 @@ Route::middleware(['web', 'guest'])->group(function () {
|
||||
Route::livewire('/reset-password/{token}', 'users::reset-password')->name('password.reset');
|
||||
});
|
||||
|
||||
// The machine console's own session (UseConsoleSession: paths under console/).
|
||||
Route::middleware('web')->prefix('console')->name('console.')->group(function () {
|
||||
Route::livewire('/login', 'users::console-login')->middleware('guest')->name('login');
|
||||
Route::get('/handoff/{token}', [ConsoleHandoff::class, 'accept'])->middleware('throttle:30,1')->name('handoff.accept');
|
||||
Route::post('/logout', ConsoleLogoutController::class)->middleware('auth')->name('logout');
|
||||
});
|
||||
|
||||
Route::middleware(['web', 'auth'])->group(function () {
|
||||
Route::post('/logout', LogoutController::class)->name('logout');
|
||||
Route::livewire('/profile/pin', 'users::pin')->middleware('can:machines.use')->name('profile.pin');
|
||||
Route::get('/console-handoff', [ConsoleHandoff::class, 'start'])->middleware('throttle:30,1')->name('console.handoff');
|
||||
|
||||
Route::middleware('can:users.manage')
|
||||
->prefix('users')
|
||||
|
||||
+4
-2
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
@@ -12,8 +13,9 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->redirectGuestsTo(fn () => route('login'));
|
||||
$middleware->redirectUsersTo(fn () => route('home'));
|
||||
// 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.console-picker') : route('home'));
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
|
||||
@@ -42,6 +42,13 @@ return [
|
||||
'driver' => 'session',
|
||||
'provider' => 'users',
|
||||
],
|
||||
|
||||
// The machine console's own session (spec 19.6): signing in or out
|
||||
// there leaves the normal user interface's session alone.
|
||||
'console' => [
|
||||
'driver' => 'session',
|
||||
'provider' => 'users',
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* The hash of the user's own PIN code for switching user on a machine
|
||||
* console. Null when the user has not set one.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->string('pin_hash')->nullable()->after('password');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->dropColumn('pin_hash');
|
||||
});
|
||||
}
|
||||
};
|
||||
+8
-6
@@ -599,18 +599,20 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v
|
||||
|
||||
### 19.5 Huoltokohteet ja huoltohistoria *(valmis)*
|
||||
|
||||
- Koneella on **laskureita**, joilla huollon tarve mitataan, esim. tulosteet (kpl), arkit, tulostettu pinta-ala (m²), musteen kulutus (ml), leikattu matka (m) tai käyttötunnit. Konetyypin mukaan uudelle koneelle ehdotetaan tavalliset laskurit: painokoneelle tulosteet ja m², tarraleikkurille leikattu matka. Laskurin lukema kirjataan käsin konekäyttöliittymästä tai koneen sivulta (esim. koneen oma kokonaislaskuri); laskuri ei kasva kirjatuista töistä.
|
||||
- Koneella on **laskureita**, joilla huollon tarve mitataan, esim. tulosteet (kpl), arkit, tulostettu pinta-ala (m²), musteen kulutus (ml), leikattu matka (m) tai käyttötunnit. Konetyypin mukaan uudelle koneelle ehdotetaan tavalliset laskurit: painokoneelle tulosteet ja m², tarraleikkurille leikattu matka. Laskurit ovat kumulatiivisia: käyttäjä kirjaa konekäyttöliittymästä tai koneen sivulta arvion siitä, paljonko yksi työ kulutti (esim. 350 tulostetta), ja kulutus lisätään laskurin lukemaan, joka näytetään vihjeenä. Laskuri ei kasva kirjatuista töistä itsestään; tuntiperusteiselle laskurille (yksikkö h) konekäyttöliittymä kuitenkin ehdottaa kulutukseksi juuri kirjatut tunnit, ja ehdotus tallentuu vasta käyttäjän vahvistuksella.
|
||||
- **Huoltokohde**: kone, nimi (painokoneella esim. jätemustesäiliön tai värijauhetankin tyhjennys, tulostuspään puhdistus, pyyhkimen vaihto; tarraleikkurilla esim. terän vaihto, leikkuualustan tai -nauhan vaihto, puhdistus), huoltoväli: **laskuriväli** (laskuri ja määrä, esim. 20 000 tulostetta), **aikaväli** (päivähuolto, viikkohuolto, kuukausihuolto tai vuosihuolto, joka N. jakso, esim. joka 2. viikko) tai molemmat, jolloin huolto erääntyy kumman tahansa täyttyessä ensin; aikavälin käyttö ei ole pakollista, ja koneella voi olla useita eri välein huollettavia kohteita yhtä aikaa (esim. päivittäinen puhdistus, viikoittainen tarkistus ja vuosihuolto), ennakkovaroitus (päivähuollolla ei ennakkovaroitusta) (esim. 90 % välistä) ja vapaaehtoinen ohje. Huoltokohteelle voi liittää varastonimikkeen (esim. vaihtorumpu), joka kirjataan käytetyksi huollon yhteydessä.
|
||||
- Erääntynyt huolto on **huoltopyyntö**: se näkyy tilassa *Huolto myöhässä* ja ilmoitetaan, ja se kuittautuu huoltokirjauksella. Aikaväli lasketaan kalenterijaksoina viimeisen huollon päivästä (kuukauden loppu rajataan, esim. 31.1. → 28.2.).
|
||||
- Erääntynyt huolto on **huoltopyyntö**: se näkyy tilassa *Huolto myöhässä* ja ilmoitetaan, ja se kuittautuu huoltokirjauksella. Aikaväli lasketaan kalenterijaksoina viimeisen huollon päivästä (kuukauden loppu rajataan, esim. 31.1. → 28.2.). Laskuriväli lasketaan huoltohetken lukemasta: jäljellä oleva määrä laskee huoltovälistä nollaan, ja huolto aloittaa koko huoltovälin alusta (väli 20 000, huolto lukemassa 19 500 → jäljellä taas 20 000).
|
||||
- Huoltokohteen tila lasketaan viimeisestä huollosta kertyneestä määrästä: *Kunnossa*, *Huolto lähestyy* tai *Huolto myöhässä*; tila näytetään aina tekstinä ja kuvakkeena sekä jäljellä olevana määränä (esim. "jäljellä 1 200 tulostetta").
|
||||
- Huollon tekee ja kuittaa koneen käyttäjä (kuka tahansa konekäyttöliittymää käyttävä, 19.9); erillistä huolto-oikeutta ei ole.
|
||||
- **Huoltokirjaus**: huoltokohde, aika, tekijä, laskurin lukema huoltohetkellä, vapaaehtoinen huomautus ja käytetyt varaosat/materiaalit varastosta. Kirjaus nollaa kohteen kertymän. Kirjauksia ei poisteta; virheellisen kirjauksen johto merkitsee perutuksi.
|
||||
- Koneen sivulla on huoltokohteet tiloineen ja huoltohistoria (suodatus huoltokohteella ja aikavälillä).
|
||||
- **Huoltokirjaus**: huoltokohde, aika, tekijä, laskurin lukema huoltohetkellä (viimeisin lukema), vapaaehtoinen huomautus ja käytetyt varaosat/materiaalit varastosta. Kirjaus nollaa kohteen: jäljellä on taas koko laskuriväli, ja aikaväli alkaa huoltopäivästä. Kirjauksia ei poisteta; virheellisen kirjauksen johto merkitsee perutuksi.
|
||||
- Koneen sivulla on huoltokohteet tiloineen ja huoltohistoria (suodatus huoltokohteella ja aikavälillä). Jos koneella ei ole laskureita eikä huoltokohteita, osiot jätetään pois (johto näkee silti Uusi huoltokohde -painikkeen).
|
||||
- Lähestyvät ja myöhässä olevat huollot näytetään konekäyttöliittymässä, johdon etusivun *Vaatii toimia* -osassa ja ilmoituksina (luku 13) koneen vastuuhenkilölle; samasta huoltotarpeesta ei ilmoiteta kahdesti.
|
||||
|
||||
### 19.6 Konekäyttöliittymä (kosketusnäyttö) *(valmis)*
|
||||
|
||||
- Jokaisella koneella on oma koko näytön näkymä (`/machines/{kone}/console`) koneen vieressä olevalle tabletille tai kosketusnäytölle. Näkymässä ei ole päävalikkoa, vain koneen nimi, käyttäjä, **Päivitä**, Vaihda käyttäjä ja paluu tavalliseen käyttöliittymään.
|
||||
- Jokaisella koneella on oma koko näytön näkymä (`/console/machines/{kone}`) koneen vieressä olevalle tabletille tai kosketusnäytölle. Näkymässä ei ole päävalikkoa, vain koneen nimi, käyttäjä, **Päivitä**, Vaihda käyttäjä ja paluu tavalliseen käyttöliittymään.
|
||||
- Konekäyttöliittymällä on **oma istuntonsa**, erillään tavallisesta käyttöliittymästä samassa selaimessa. Koneen sivulta (ja konelistasta ja tilauksista) se avautuu uuteen ikkunaan kirjautuneena samalle käyttäjälle kertakäyttöisellä, minuutin voimassa olevalla avaimella. Sen jälkeen istunnot elävät erillään: tavallisen käyttöliittymän sulkeminen tai uloskirjautuminen ei vaikuta konekäyttöliittymään, eikä konekäyttöliittymän käyttäjänvaihto tavalliseen. Kirjautumissivu `/login` kirjaa aina tavalliseen käyttöliittymään. Suoraan avattu konekäyttöliittymä (esim. erillinen tabletti) kysyy kirjautumisen omalla sivullaan (`/console/login`) PIN-koodilla tai sähköpostilla ja salasanalla.
|
||||
- **Vaihda käyttäjä** avaa valintaikkunan, jossa seuraava käyttäjä valitsee nimensä ja näppäilee oman 4–6-numeroisen **PIN-koodinsa** numeronäppäimillä. PIN-koodin asettaa käyttäjä itse profiilivalikon sivulla *Konsolin PIN-koodi* salasanallaan; siitä tallennetaan vain tiiviste. Vaihto koskee vain konekäyttöliittymän omaa istuntoa. Viisi väärää PIN-koodia lukitsee käyttäjän PIN-kirjautumisen 15 minuutiksi. Käyttäjä, jolla ei ole PIN-koodia, kirjautuu konekäyttöliittymän kirjautumissivulla sähköpostilla ja salasanalla takaisin konekäyttöliittymään.
|
||||
- **Päivitä**-painike (iso, aina näkyvissä yläreunassa) lataa työlistan, tilausten tilat, saldot ja huoltojen tilat uudelleen palvelimelta. Näkymä päivittyy myös itsestään, mutta painikkeella saa heti ajantasaisen tilanteen, kun samaa asiaa on käsitelty toisella laitteella: esim. pikamyyntitilaus aloitetaan puhelimella, valmistetaan tabletilla konekäyttöliittymässä ja maksetaan lopuksi kassakoneella, josta kuitti tulostetaan. Päivityksen jälkeen ilmoitus (`role="status"`) kertoo päivitysajan ja uusien rivien määrän, ja fokus pysyy painikkeessa.
|
||||
- Kosketusnäytölle mitoitettu: painikkeet ja kosketusalueet vähintään 44 × 44 px, isot fontit, vähän tekstinsyöttöä, ei hover-toimintoja; toimii pysty- ja vaaka-asennossa tabletin kokoisilla näytöillä ja myös puhelimella. Saavutettavuusvaatimukset (WCAG 2.2 AA) koskevat myös tätä näkymää.
|
||||
- **Työlista**: kuluvan päivän tehtävät ja pikamyyntitilaukset (sekä myöhässä olevat aiemmilta päiviltä) järjestyksessä; tulevien päivien listat voi katsoa Seuraava päivä -painikkeella, mutta valmiiksi kuitataan vain tämän päivän ja myöhässä olevat rivit, seuraava korostettuna (tekstillä). Pikamyyntitilauksen rivillä on iso noutonumero ja Valmis-painike (19.7); uusi tilaus ilmoitetaan `aria-live`-alueella. Tehtävän valinta näyttää ohjeistuksen ja kuvauksen, ja tilan voi vaihtaa isoilla painikkeilla (Aloita = työn alla, Valmis, Tarkastettavaksi).
|
||||
@@ -619,7 +621,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v
|
||||
- ensin tämän koneen yleisimmin ja viimeksi käyttämät nimikkeet, sitten ryhmäpainikkeet (esim. Paperit, Mediat), joilla lista rajataan;
|
||||
- hakukenttä, joka suodattaa kirjoittaessa nimen ja koodin osista (isot ja pienet kirjaimet ja ääkköset samoin), sekä viivakoodinlukija, joka kirjoittaa koodin kenttään;
|
||||
- määrä +/- painikkeilla tai numeronäppäimistöllä, yksikkö näkyvissä; kirjaus vahvistetaan yhdellä painalluksella, ja ilmoitus (`role="status"`) kertoo kirjatun määrän ja uuden saldon. Viimeisimmän kirjauksen voi perua heti.
|
||||
- **Laskurit ja huollot**: laskurin lukeman kirjaus numeronäppäimistöllä; huoltokohteet tiloineen ja huoltokirjaus (Huolto tehty, lukema esitäytettynä, käytetyt osat). Myöhässä olevat huollot näkyvät näkymän yläosassa tekstinä ja kuvakkeena.
|
||||
- **Laskurit ja huollot**: työn kulutuksen kirjaus laskuriin numeronäppäimistöllä (laskurin lukema vihjeenä); huoltokohteet tiloineen ja huoltokirjaus (Huolto tehty, käytetyt osat). Osio näytetään vain, jos koneella on laskureita tai huoltokohteita. Myöhässä olevat huollot näkyvät näkymän yläosassa tekstinä ja kuvakkeena.
|
||||
- Tehtävän tunnit kirjataan tavalliseen tapaan (luku 9); konekäyttöliittymässä on pikakirjaus valitun tehtävän tämän päivän tunneille.
|
||||
|
||||
### 19.7 Pikamyyntituotteiden valmistus *(valmis)*
|
||||
|
||||
@@ -148,6 +148,13 @@ return [
|
||||
'not_author' => 'You can edit and remove only your own comments.',
|
||||
],
|
||||
],
|
||||
'tabs' => [
|
||||
'label' => 'Sections of task :title',
|
||||
'notes' => 'Checklist and comments',
|
||||
'images' => 'Images',
|
||||
'materials' => 'Materials and machines',
|
||||
'no_materials' => 'This task has no materials or machines.',
|
||||
],
|
||||
'images' => [
|
||||
'title' => 'Images',
|
||||
'list_of' => 'Images: :title',
|
||||
|
||||
@@ -56,4 +56,5 @@ return [
|
||||
'theme_system' => 'System default',
|
||||
'selected' => '(selected)',
|
||||
],
|
||||
'opens_in_new_window' => 'opens in a new window',
|
||||
];
|
||||
|
||||
+15
-9
@@ -162,11 +162,11 @@ return [
|
||||
'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.',
|
||||
'latest_reading' => 'Counter now :reading :unit (updated :at).',
|
||||
'usage' => 'Used by the job (:unit)',
|
||||
'save_usage' => 'Record usage',
|
||||
'save_usage_named' => 'Record usage: :counter',
|
||||
'usage_saved' => ':usage :unit added to :counter, counter now :reading :unit.',
|
||||
'items' => 'Maintenance',
|
||||
'add' => 'New maintenance item',
|
||||
'none' => 'The machine has no maintenance items.',
|
||||
@@ -193,7 +193,6 @@ return [
|
||||
'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.',
|
||||
@@ -209,7 +208,7 @@ return [
|
||||
'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.',
|
||||
'cancel_text' => 'The record stays in the history marked as cancelled, and it no longer resets the interval. The stock it used is returned with a reversal.',
|
||||
'cancelled' => 'Maintenance :name marked as cancelled.',
|
||||
'errors' => [
|
||||
'needs_interval' => 'Give a counter-based interval, a time-based interval or both.',
|
||||
@@ -218,9 +217,14 @@ return [
|
||||
'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.',
|
||||
'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',
|
||||
@@ -274,7 +278,9 @@ return [
|
||||
'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',
|
||||
'latest' => 'Counter now :reading',
|
||||
'usage' => ':counter: used by the job (:unit)',
|
||||
'hour_suggestion' => 'Suggestion: record :hours h on the counter :counter. Confirm with Record usage.',
|
||||
],
|
||||
'process' => [
|
||||
'title' => 'Production process',
|
||||
|
||||
@@ -186,6 +186,14 @@ return [
|
||||
'paid' => 'Order :number paid: :total, :method.',
|
||||
'cancel' => 'Cancel order',
|
||||
'cancel_named' => 'Cancel order :number',
|
||||
'change' => 'Change',
|
||||
'change_named' => 'Change order :number',
|
||||
'editing' => 'You are changing order :number. Its products and customer are in the cart.',
|
||||
'editing_notice' => 'You are changing order :number. The pickup number stays the same.',
|
||||
'stop_editing' => 'Discard change',
|
||||
'editing_stopped' => 'Order change discarded; the cart is empty.',
|
||||
'save_change' => 'Save order change',
|
||||
'changed' => 'Order :number changed, total :total.',
|
||||
'cancel_title' => 'Cancel the order?',
|
||||
'cancel_text' => 'The order leaves the machines\' work lists and no sale is made. Material and hours already recorded stay.',
|
||||
'cancelled' => 'Order :number cancelled.',
|
||||
@@ -197,6 +205,8 @@ return [
|
||||
'errors' => [
|
||||
'step' => 'The step could not be completed: the order has changed. Refresh the list.',
|
||||
'closed' => 'The order is already paid or cancelled.',
|
||||
'started' => 'The order can no longer be changed: making has started or it is paid or cancelled.',
|
||||
'no_production' => 'An order needs at least one product that is made. Sell the other products as an ordinary sale.',
|
||||
],
|
||||
],
|
||||
'errors' => [
|
||||
|
||||
@@ -86,6 +86,47 @@ return [
|
||||
'supervisor_has_interns' => 'The user is the supervisor of active interns. First choose a new supervisor for the interns.',
|
||||
],
|
||||
|
||||
'pin' => [
|
||||
'title' => 'Console PIN code',
|
||||
'intro' => 'On a machine console you can switch to your user with your own PIN code, without your email and password. A session opened with the PIN code works only on the machine console.',
|
||||
'is_set' => 'You have a PIN code.',
|
||||
'not_set' => 'You do not have a PIN code yet.',
|
||||
'current_password' => 'Current password',
|
||||
'pin' => 'New PIN code',
|
||||
'pin_hint' => '4–6 digits.',
|
||||
'pin_confirmation' => 'PIN code again',
|
||||
'save' => 'Save PIN code',
|
||||
'remove' => 'Remove PIN code',
|
||||
'saved' => 'PIN code saved.',
|
||||
'removed' => 'PIN code removed.',
|
||||
'errors' => [
|
||||
'pin' => 'Enter 4–6 digits as the PIN code.',
|
||||
'confirmation' => 'The PIN codes do not match.',
|
||||
'password' => 'The password is not correct.',
|
||||
],
|
||||
],
|
||||
'console_login' => [
|
||||
'title' => 'Sign in to the machine console',
|
||||
'intro' => 'The machine console has a sign-in of its own. The normal user interface in the same browser does not change.',
|
||||
'with_pin' => 'With a PIN code',
|
||||
'with_password' => 'With email and password',
|
||||
],
|
||||
'pin_switch' => [
|
||||
'title' => 'Change user',
|
||||
'user' => 'Who are you?',
|
||||
'pin' => 'PIN code',
|
||||
'keypad' => 'Number keys',
|
||||
'clear' => 'Clear',
|
||||
'backspace' => 'Remove the last digit',
|
||||
'submit' => 'Sign in',
|
||||
'no_users' => 'Nobody has a PIN code yet. A PIN code is set from the profile menu.',
|
||||
'with_password' => 'Sign in with email and password',
|
||||
'errors' => [
|
||||
'user' => 'Choose your name.',
|
||||
'pin' => 'The PIN code is not correct.',
|
||||
'locked' => 'Too many wrong attempts. Try again in :minutes min or sign in with your password.',
|
||||
],
|
||||
],
|
||||
'password_mail' => [
|
||||
'subject' => 'Set your password',
|
||||
'greeting' => 'Hello!',
|
||||
|
||||
@@ -148,6 +148,13 @@ return [
|
||||
'not_author' => 'Voit muokata ja poistaa vain omia kommenttejasi.',
|
||||
],
|
||||
],
|
||||
'tabs' => [
|
||||
'label' => 'Tehtävän :title osiot',
|
||||
'notes' => 'Tarkistuslista ja kommentit',
|
||||
'images' => 'Kuvat',
|
||||
'materials' => 'Materiaali ja koneet',
|
||||
'no_materials' => 'Tällä tehtävällä ei ole materiaaleja eikä koneita.',
|
||||
],
|
||||
'images' => [
|
||||
'title' => 'Kuvat',
|
||||
'list_of' => 'Kuvat: :title',
|
||||
|
||||
@@ -56,4 +56,5 @@ return [
|
||||
'theme_system' => 'Järjestelmän mukainen',
|
||||
'selected' => '(valittu)',
|
||||
],
|
||||
'opens_in_new_window' => 'avautuu uuteen ikkunaan',
|
||||
];
|
||||
|
||||
+15
-9
@@ -162,11 +162,11 @@ return [
|
||||
'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.',
|
||||
'latest_reading' => 'Laskuri nyt :reading :unit (päivitetty :at).',
|
||||
'usage' => 'Työn kulutus (:unit)',
|
||||
'save_usage' => 'Kirjaa kulutus',
|
||||
'save_usage_named' => 'Kirjaa kulutus: :counter',
|
||||
'usage_saved' => 'Laskuriin :counter lisätty :usage :unit, laskuri nyt :reading :unit.',
|
||||
'items' => 'Huollot',
|
||||
'add' => 'Uusi huoltokohde',
|
||||
'none' => 'Koneelle ei ole huoltokohteita.',
|
||||
@@ -193,7 +193,6 @@ return [
|
||||
'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.',
|
||||
@@ -209,7 +208,7 @@ return [
|
||||
'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ää.',
|
||||
'cancel_text' => 'Huoltokirjaus jää historiaan perutuksi merkittynä, eikä se enää nollaa huoltoväliä. Sen käyttämä varasto palautetaan vastakirjauksella.',
|
||||
'cancelled' => 'Huolto :name merkitty perutuksi.',
|
||||
'errors' => [
|
||||
'needs_interval' => 'Anna laskuriin perustuva huoltoväli, aikaan perustuva huoltoväli tai molemmat.',
|
||||
@@ -218,9 +217,14 @@ return [
|
||||
'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.',
|
||||
'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',
|
||||
@@ -274,7 +278,9 @@ return [
|
||||
'undo' => 'Peru viimeisin kirjaus',
|
||||
'reason_required' => 'Anna syy, kun tehtävää ei ole valittu.',
|
||||
'counters_and_maintenance' => 'Laskurit ja huollot',
|
||||
'latest' => 'Viimeisin lukema :reading',
|
||||
'latest' => 'Laskuri nyt :reading',
|
||||
'usage' => ':counter: työn kulutus (:unit)',
|
||||
'hour_suggestion' => 'Ehdotus: kirjaa :hours h laskuriin :counter. Vahvista painamalla Kirjaa kulutus.',
|
||||
],
|
||||
'process' => [
|
||||
'title' => 'Valmistusprosessi',
|
||||
|
||||
@@ -186,6 +186,14 @@ return [
|
||||
'paid' => 'Tilaus :number maksettu: :total, :method.',
|
||||
'cancel' => 'Peru tilaus',
|
||||
'cancel_named' => 'Peru tilaus :number',
|
||||
'change' => 'Muuta',
|
||||
'change_named' => 'Muuta tilausta :number',
|
||||
'editing' => 'Muutat tilausta :number. Tuotteet ja asiakas on tuotu ostoskoriin.',
|
||||
'editing_notice' => 'Muutat tilausta :number. Noutonumero pysyy samana.',
|
||||
'stop_editing' => 'Peru muutos',
|
||||
'editing_stopped' => 'Tilauksen muutos peruttu; ostoskori tyhjennetty.',
|
||||
'save_change' => 'Tallenna tilauksen muutos',
|
||||
'changed' => 'Tilaus :number muutettu, yhteensä :total.',
|
||||
'cancel_title' => 'Perutaanko tilaus?',
|
||||
'cancel_text' => 'Tilaus poistuu koneiden työlistoilta, eikä myyntiä synny. Jo kirjattu materiaali ja tunnit jäävät.',
|
||||
'cancelled' => 'Tilaus :number peruttu.',
|
||||
@@ -197,6 +205,8 @@ return [
|
||||
'errors' => [
|
||||
'step' => 'Vaihetta ei voitu kuitata: tilauksen tila on muuttunut. Päivitä lista.',
|
||||
'closed' => 'Tilaus on jo maksettu tai peruttu.',
|
||||
'started' => 'Tilausta ei voi enää muuttaa: valmistus on alkanut tai tilaus on maksettu tai peruttu.',
|
||||
'no_production' => 'Tilauksessa pitää olla vähintään yksi valmistettava tuote. Myy muut tuotteet tavallisena myyntinä.',
|
||||
],
|
||||
],
|
||||
'errors' => [
|
||||
|
||||
@@ -86,6 +86,47 @@ return [
|
||||
'supervisor_has_interns' => 'Käyttäjä on aktiivisten harjoittelijoiden vastuuhenkilö. Vaihda harjoittelijoille ensin uusi vastuuhenkilö.',
|
||||
],
|
||||
|
||||
'pin' => [
|
||||
'title' => 'Konsolin PIN-koodi',
|
||||
'intro' => 'Koneen konekäyttöliittymässä voit vaihtaa käyttäjäksi omalla PIN-koodillasi ilman sähköpostia ja salasanaa. PIN-koodilla avattu istunto toimii vain konekäyttöliittymässä.',
|
||||
'is_set' => 'Sinulla on PIN-koodi.',
|
||||
'not_set' => 'Sinulla ei ole vielä PIN-koodia.',
|
||||
'current_password' => 'Nykyinen salasana',
|
||||
'pin' => 'Uusi PIN-koodi',
|
||||
'pin_hint' => '4–6 numeroa.',
|
||||
'pin_confirmation' => 'PIN-koodi uudelleen',
|
||||
'save' => 'Tallenna PIN-koodi',
|
||||
'remove' => 'Poista PIN-koodi',
|
||||
'saved' => 'PIN-koodi tallennettu.',
|
||||
'removed' => 'PIN-koodi poistettu.',
|
||||
'errors' => [
|
||||
'pin' => 'Anna PIN-koodiksi 4–6 numeroa.',
|
||||
'confirmation' => 'PIN-koodit eivät ole samat.',
|
||||
'password' => 'Salasana ei ole oikein.',
|
||||
],
|
||||
],
|
||||
'console_login' => [
|
||||
'title' => 'Kirjaudu konekäyttöliittymään',
|
||||
'intro' => 'Konekäyttöliittymällä on oma kirjautumisensa. Tavallinen käyttöliittymä samassa selaimessa ei muutu.',
|
||||
'with_pin' => 'PIN-koodilla',
|
||||
'with_password' => 'Sähköpostilla ja salasanalla',
|
||||
],
|
||||
'pin_switch' => [
|
||||
'title' => 'Vaihda käyttäjä',
|
||||
'user' => 'Kuka olet?',
|
||||
'pin' => 'PIN-koodi',
|
||||
'keypad' => 'Numeronäppäimet',
|
||||
'clear' => 'Tyhjennä',
|
||||
'backspace' => 'Poista viimeinen numero',
|
||||
'submit' => 'Kirjaudu',
|
||||
'no_users' => 'Kenelläkään ei ole vielä PIN-koodia. PIN-koodin voi asettaa profiilivalikosta.',
|
||||
'with_password' => 'Kirjaudu sähköpostilla ja salasanalla',
|
||||
'errors' => [
|
||||
'user' => 'Valitse nimesi.',
|
||||
'pin' => 'PIN-koodi ei ole oikein.',
|
||||
'locked' => 'Liian monta väärää yritystä. Yritä uudelleen :minutes min kuluttua tai kirjaudu salasanalla.',
|
||||
],
|
||||
],
|
||||
'password_mail' => [
|
||||
'subject' => 'Aseta salasana',
|
||||
'greeting' => 'Hei!',
|
||||
|
||||
@@ -92,6 +92,15 @@
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
@can('machines.use')
|
||||
<p>
|
||||
<a href="{{ route('profile.pin') }}" wire:navigate class="flex min-h-6 items-center gap-2 rounded-md px-2 py-1 text-zinc-100 underline hover:bg-zinc-700 hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-400">
|
||||
<x-icon name="key" class="size-4" aria-hidden="true" />
|
||||
{{ __('users.pin.title') }}
|
||||
</a>
|
||||
</p>
|
||||
@endcan
|
||||
|
||||
<form method="POST" action="{{ route('logout') }}" class="border-t border-zinc-600 pt-3">
|
||||
@csrf
|
||||
<x-button submit subtle color="black" sm icon="arrow-right-start-on-rectangle" :text="__('layout.logout')" />
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
{{--
|
||||
Tabs after the WAI-ARIA tabs pattern, because TallStackUI's <x-tab> ties its
|
||||
panels to ids that do not exist and has no arrow keys. Only the selected tab
|
||||
is in the tab order; arrow keys, Home and End move between the tabs and
|
||||
select them. Panels are <x-tabs.panel> children with the same id.
|
||||
|
||||
$tabs: ['key' => 'title', ...] in display order.
|
||||
--}}
|
||||
@props([
|
||||
'id',
|
||||
'label',
|
||||
'tabs',
|
||||
'selected' => null,
|
||||
])
|
||||
|
||||
@php
|
||||
$selected ??= array_key_first($tabs);
|
||||
@endphp
|
||||
|
||||
<div
|
||||
{{ $attributes->class('space-y-3') }}
|
||||
x-data="{
|
||||
selected: @js($selected),
|
||||
select(key) {
|
||||
this.selected = key;
|
||||
this.$nextTick(() => document.getElementById(@js($id) + '-tab-' + key)?.focus());
|
||||
},
|
||||
move(event) {
|
||||
const keys = @js(array_keys($tabs));
|
||||
const index = keys.indexOf(this.selected);
|
||||
const next = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: keys.length - 1 }[event.key];
|
||||
if (next === undefined) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
this.select(keys[(next + keys.length) % keys.length]);
|
||||
},
|
||||
}"
|
||||
>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="{{ $label }}"
|
||||
x-on:keydown="move($event)"
|
||||
class="flex flex-wrap gap-x-4 gap-y-1 border-b border-zinc-200 dark:border-zinc-700"
|
||||
>
|
||||
@foreach ($tabs as $key => $title)
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
id="{{ $id }}-tab-{{ $key }}"
|
||||
aria-controls="{{ $id }}-panel-{{ $key }}"
|
||||
aria-selected="{{ $key === $selected ? 'true' : 'false' }}"
|
||||
tabindex="{{ $key === $selected ? '0' : '-1' }}"
|
||||
x-bind:aria-selected="(selected === @js($key)).toString()"
|
||||
x-bind:tabindex="selected === @js($key) ? 0 : -1"
|
||||
x-on:click="select(@js($key))"
|
||||
x-bind:class="selected === @js($key)
|
||||
? 'border-primary-700 font-semibold text-zinc-900 dark:border-primary-400 dark:text-white'
|
||||
: 'border-transparent text-zinc-700 hover:border-zinc-400 dark:text-zinc-300'"
|
||||
class="-mb-px min-h-6 rounded-t-md border-b-2 px-1 py-2 text-left text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400"
|
||||
>{{ $title }}</button>
|
||||
@endforeach
|
||||
</div>
|
||||
|
||||
{{ $slot }}
|
||||
</div>
|
||||
@@ -0,0 +1,21 @@
|
||||
{{--
|
||||
One panel of <x-tabs>: $tabsId is the id given to <x-tabs>, $name the key of
|
||||
its tab. The panel is always rendered and only hidden, so Livewire components
|
||||
in it keep their state.
|
||||
--}}
|
||||
@props([
|
||||
'tabsId',
|
||||
'name',
|
||||
])
|
||||
|
||||
<div
|
||||
{{ $attributes->class('rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400') }}
|
||||
role="tabpanel"
|
||||
id="{{ $tabsId }}-panel-{{ $name }}"
|
||||
aria-labelledby="{{ $tabsId }}-tab-{{ $name }}"
|
||||
tabindex="0"
|
||||
x-show="selected === @js($name)"
|
||||
x-cloak
|
||||
>
|
||||
{{ $slot }}
|
||||
</div>
|
||||
@@ -0,0 +1,40 @@
|
||||
{{--
|
||||
The fields of signing in with a console PIN code (spec 19.6), inside a
|
||||
Livewire component that uses SignsInWithPin: the user's name as large
|
||||
radio buttons, the PIN code and a number keypad for touch screens.
|
||||
--}}
|
||||
@props([
|
||||
'users',
|
||||
])
|
||||
|
||||
@php
|
||||
$key = 'inline-flex min-h-14 items-center justify-center rounded-lg border border-zinc-500 bg-white text-2xl font-semibold text-zinc-900 hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100 dark:hover:bg-zinc-700 dark:focus-visible:outline-blue-400';
|
||||
@endphp
|
||||
|
||||
<fieldset>
|
||||
<legend class="mb-2 font-semibold">{{ __('users.pin_switch.user') }}</legend>
|
||||
<div class="grid max-h-64 gap-2 overflow-y-auto sm:grid-cols-2">
|
||||
@foreach ($users as $option)
|
||||
<label wire:key="pin-user-{{ $option->id }}" class="flex min-h-11 cursor-pointer items-center gap-3 rounded-lg border border-zinc-300 px-3 py-2 has-checked:border-primary-600 has-checked:font-semibold dark:border-zinc-600 dark:has-checked:border-primary-400">
|
||||
<input type="radio" name="pin-user" value="{{ $option->id }}" wire:model="userId" class="size-5 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
|
||||
{{ $option->name }}
|
||||
</label>
|
||||
@endforeach
|
||||
</div>
|
||||
@error('userId')
|
||||
<p role="alert" class="mt-1 text-sm font-medium text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
</fieldset>
|
||||
|
||||
<x-input id="pin-sign-in-pin" wire:model="pin" type="password" inputmode="numeric" maxlength="6" :label="__('users.pin_switch.pin')" autocomplete="off" />
|
||||
|
||||
<div class="grid grid-cols-3 gap-2" role="group" aria-label="{{ __('users.pin_switch.keypad') }}">
|
||||
@foreach (['1', '2', '3', '4', '5', '6', '7', '8', '9'] as $digit)
|
||||
<button type="button" class="{{ $key }}" x-on:click="if (($wire.pin ?? '').length < 6) $wire.pin = ($wire.pin ?? '') + '{{ $digit }}'">{{ $digit }}</button>
|
||||
@endforeach
|
||||
<button type="button" class="{{ $key }} text-base" x-on:click="$wire.pin = ''">{{ __('users.pin_switch.clear') }}</button>
|
||||
<button type="button" class="{{ $key }}" x-on:click="if (($wire.pin ?? '').length < 6) $wire.pin = ($wire.pin ?? '') + '0'">0</button>
|
||||
<button type="button" class="{{ $key }}" x-on:click="$wire.pin = ($wire.pin ?? '').slice(0, -1)" aria-label="{{ __('users.pin_switch.backspace') }}">
|
||||
<x-icon name="backspace" class="size-7" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -82,7 +82,8 @@ it('records material on a task card with the keyboard and without accessibility
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->assertSee(__('inventory.task.title'))
|
||||
$visit->click('#task-'.$task->id.'-tabs-tab-materials')
|
||||
->assertSee(__('inventory.task.title'))
|
||||
->fill('#task-'.$task->id.'-material-search', 'valoku')
|
||||
->assertSee('1 osuma')
|
||||
->click('[wire\:click="selectItem('.$this->item->id.')"]')
|
||||
|
||||
@@ -216,6 +216,42 @@ it('changes a task status and removes a task with the keyboard', function () {
|
||||
->assertScript('document.activeElement.id', 'tasks-heading');
|
||||
});
|
||||
|
||||
it('puts the task actions above the tabs and moves between the tabs with the arrow keys', function (string $device, string $colorScheme) {
|
||||
$this->job->update(['status' => 'order']);
|
||||
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
|
||||
$task = TaskModel::factory()
|
||||
->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä']);
|
||||
$tabs = 'task-'.$task->id.'-tabs';
|
||||
|
||||
$visit = visit(route('jobs.show', $this->job->id));
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->click('#task-toggle-'.$task->id)
|
||||
->assertScript("!! (document.getElementById('task-status-{$task->id}').compareDocumentPosition(document.getElementById('{$tabs}-tab-notes')) & Node.DOCUMENT_POSITION_FOLLOWING)", true)
|
||||
->assertAttribute('#'.$tabs.'-tab-notes', 'aria-selected', 'true')
|
||||
->assertVisible('#checklist-new-'.$task->id)
|
||||
->assertMissing('#'.$tabs.'-panel-images')
|
||||
->keys('#'.$tabs.'-tab-notes', 'ArrowRight')
|
||||
->assertScript('document.activeElement.id', $tabs.'-tab-images')
|
||||
->assertAttribute('#'.$tabs.'-tab-images', 'aria-selected', 'true')
|
||||
->assertAttribute('#'.$tabs.'-tab-notes', 'tabindex', '-1')
|
||||
->assertVisible('#'.$tabs.'-panel-images')
|
||||
->assertMissing('#'.$tabs.'-panel-notes')
|
||||
->keys('#'.$tabs.'-tab-images', 'End')
|
||||
->assertScript('document.activeElement.id', $tabs.'-tab-materials')
|
||||
->assertSee('Tällä tehtävällä ei ole materiaaleja eikä koneita.')
|
||||
->keys('#'.$tabs.'-tab-materials', 'ArrowRight')
|
||||
->assertScript('document.activeElement.id', $tabs.'-tab-notes')
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
it('shows task cards collapsed, opens several at once and expands or collapses them all', function () {
|
||||
$this->job->update(['status' => 'order']);
|
||||
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
|
||||
@@ -348,6 +384,7 @@ it('recaptions and removes a task image with the keyboard', function () {
|
||||
|
||||
$page = visit(route('jobs.show', $this->job->id))
|
||||
->click('#task-toggle-'.$task->id)
|
||||
->click('#task-'.$task->id.'-tabs-tab-images')
|
||||
->assertVisible('img[alt="Valot paikallaan"]')
|
||||
->assertScript("document.querySelector('img[alt=\"Valot paikallaan\"]').naturalWidth > 0", true)
|
||||
->assertSeeIn('#task-'.$task->id.'-title + dl', 'Kuvat:');
|
||||
|
||||
@@ -10,13 +10,17 @@ 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\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->management()->create(['name' => 'Johtaja']);
|
||||
$this->actingAs($this->user);
|
||||
// The machine console has its own session and guard.
|
||||
$this->actingAs($this->user, 'console');
|
||||
|
||||
$print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole();
|
||||
$print->update(['uses_stock' => true]);
|
||||
@@ -47,16 +51,21 @@ 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);
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
if ($page === 'job') {
|
||||
$visit->click('#task-'.$this->task->id.'-tabs-tab-materials');
|
||||
}
|
||||
|
||||
$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'],
|
||||
@@ -111,3 +120,68 @@ it('refreshes the console on a tablet and keeps focus on the button', function (
|
||||
->assertSee(__('machines.console.selected', ['title' => 'Banderolli']))
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
});
|
||||
|
||||
it('changes user with a PIN code in a dialog on the console', function (string $device, string $colorScheme) {
|
||||
User::factory()->employee()->create(['name' => 'Olli Operaattori', 'pin_hash' => Hash::make('2468')]);
|
||||
|
||||
$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->click('#pin-switch-open')
|
||||
->assertScript("document.getElementById('pin-switch-dialog').open", true)
|
||||
->assertScript("document.getElementById('pin-switch-dialog').contains(document.activeElement)", true)
|
||||
->assertSee('Olli Operaattori')
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
it('signs in with a PIN code typed on the keypad and stays on the console', function () {
|
||||
User::factory()->employee()->create(['name' => 'Olli Operaattori', 'pin_hash' => Hash::make('2468')]);
|
||||
|
||||
visit(route('machines.console', $this->machine->id))
|
||||
->click('#pin-switch-open')
|
||||
->click('Olli Operaattori')
|
||||
->click('2')->click('4')->click('6')->click('8')
|
||||
->click(__('users.pin_switch.submit'))
|
||||
->assertSee(__('machines.console.user', ['name' => 'Olli Operaattori']))
|
||||
->assertNoJavaScriptErrors();
|
||||
});
|
||||
|
||||
it('has no accessibility issues on the console\'s sign-in page', function (string $device, string $colorScheme) {
|
||||
User::factory()->employee()->create(['name' => 'Olli Operaattori', 'pin_hash' => Hash::make('2468')]);
|
||||
Auth::guard('console')->logout();
|
||||
|
||||
$visit = visit(route('console.login'));
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->assertSee(__('users.console_login.title'))
|
||||
->assertSee('Olli Operaattori')
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
it('has no accessibility issues on the PIN code page', function (string $device, string $colorScheme) {
|
||||
$visit = visit(route('profile.pin'));
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->assertSee(__('users.pin.title'))
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
@@ -17,6 +17,8 @@ uses(RefreshDatabase::class);
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->management()->create(['name' => 'Johtaja']);
|
||||
$this->actingAs($this->user);
|
||||
// The machine console has its own session and guard.
|
||||
$this->actingAs($this->user, 'console');
|
||||
|
||||
$print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole();
|
||||
$print->update(['uses_stock' => true]);
|
||||
@@ -72,3 +74,45 @@ it('completes an order on the console and pays it on the quick sale page with th
|
||||
->assertSee('Tilaus 1 maksettu')
|
||||
->assertSee('Avaa kuitti');
|
||||
});
|
||||
|
||||
it('changes an order with the keyboard, moving focus to the cart', function () {
|
||||
visit(route('sales.sell'))
|
||||
->keys('[aria-label="'.__('sales.orders.change_named', ['number' => 1]).'"]', 'Enter')
|
||||
->assertSee(__('sales.orders.editing_notice', ['number' => 1]))
|
||||
->assertScript('document.activeElement.id', 'cart-heading')
|
||||
->assertSee(__('sales.orders.save_change'))
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->keys('#stop-editing', 'Enter')
|
||||
->assertScript('document.activeElement.id', 'cart-heading')
|
||||
->assertDontSee(__('sales.orders.editing_notice', ['number' => 1]))
|
||||
->keys('[aria-label="'.__('sales.orders.change_named', ['number' => 1]).'"]', 'Enter')
|
||||
->keys('#order-customer-name', 'Control+a')
|
||||
->type('#order-customer-name', 'Liisa')
|
||||
->keys('#order-customer-name', 'Enter')
|
||||
->assertSee('Tilaus 1 muutettu')
|
||||
->assertSee('Liisa');
|
||||
});
|
||||
|
||||
it('cancels an order in a dialog that takes and returns focus', function () {
|
||||
$cancel = '[aria-label="'.__('sales.orders.cancel_named', ['number' => 1]).'"]';
|
||||
|
||||
visit(route('sales.sell'))
|
||||
->keys($cancel, 'Enter')
|
||||
->assertScript('document.getElementById("cancel-order-dialog").open', true)
|
||||
->assertScript('document.getElementById("cancel-order-dialog").contains(document.activeElement)', true)
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->keys('#cancel-order-dialog', 'Escape')
|
||||
->assertScript('document.getElementById("cancel-order-dialog").open', false)
|
||||
->assertScript('document.activeElement.getAttribute("aria-label")', __('sales.orders.cancel_named', ['number' => 1]))
|
||||
->keys($cancel, 'Enter')
|
||||
->click('#cancel-order-dialog button[wire\:click="cancel"]')
|
||||
->assertSee('Tilaus 1 peruttu.')
|
||||
->assertScript('document.activeElement.id', 'orders-status');
|
||||
});
|
||||
|
||||
it('moves a production step with the keyboard, keeping focus', function () {
|
||||
visit(route('catalog.products.edit', $this->sticker->id))
|
||||
->keys('[aria-label="'.__('catalog.workflows.move_up_named', ['number' => 2]).'"]', 'Enter')
|
||||
->assertScript('document.activeElement.getAttribute("aria-label")', __('catalog.workflows.move_up_named', ['number' => 1]))
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
});
|
||||
|
||||
@@ -32,6 +32,11 @@ class FakeUserAccountQueries implements UserAccountQueries
|
||||
throw new LogicException('Not needed in unit tests.');
|
||||
}
|
||||
|
||||
public function pinLoginOptions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function supervisorOptions(?int $exceptUserId = null): array
|
||||
{
|
||||
return [];
|
||||
|
||||
@@ -9,11 +9,14 @@ 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\MachineCounterModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
|
||||
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 Illuminate\Support\Facades\Hash;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
@@ -46,6 +49,8 @@ function console(object $test): mixed
|
||||
}
|
||||
|
||||
it('opens without the main menu and shows today\'s work list', function () {
|
||||
$this->actingAs($this->employee, 'console');
|
||||
|
||||
$this->get(route('machines.console', $this->machine->id))
|
||||
->assertOk()
|
||||
->assertSee('Suurkuvatulostin')
|
||||
@@ -53,7 +58,7 @@ it('opens without the main menu and shows today\'s work list', function () {
|
||||
->assertSee(__('machines.console.refresh'))
|
||||
->assertDontSee(__('layout.main_menu'));
|
||||
|
||||
$this->actingAs(User::factory()->subcontractor()->create());
|
||||
$this->actingAs(User::factory()->subcontractor()->create(), 'console');
|
||||
$this->get(route('machines.console', $this->machine->id))->assertForbidden();
|
||||
});
|
||||
|
||||
@@ -122,11 +127,92 @@ it('announces new rows when refreshed', function () {
|
||||
->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'));
|
||||
it('returns to the console after signing out of the console to sign in with a password', function () {
|
||||
$this->actingAs($this->employee, 'console');
|
||||
$this->post(route('console.logout'), ['return_to' => route('machines.console', $this->machine->id)])->assertRedirect(route('console.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']);
|
||||
$this->actingAs($this->employee, 'console');
|
||||
$this->post(route('console.logout'), ['return_to' => 'https://example.com/phish']);
|
||||
expect(session('url.intended'))->toBeNull();
|
||||
});
|
||||
|
||||
it('suggests the hours booked as the usage of the machine\'s hour counter and leaves out counters and maintenance when there are none', function () {
|
||||
console($this)->assertDontSee(__('machines.console.counters_and_maintenance'));
|
||||
|
||||
$hours = MachineCounterModel::query()->create(['machine_id' => $this->machine->id, 'name' => 'Käyttötunnit', 'unit' => 'hour', 'sort_order' => 1]);
|
||||
|
||||
console($this)
|
||||
->assertSee(__('machines.console.counters_and_maintenance'))
|
||||
->call('selectRow', MachineQueueEntryModel::query()->sole()->id)
|
||||
->set('hours', '1,5')
|
||||
->call('saveHours')
|
||||
->assertSet('usage.'.$hours->id, '1,5')
|
||||
->assertSet('message', fn (string $message) => str_contains($message, 'Ehdotus: kirjaa 1,5 h laskuriin Käyttötunnit.'))
|
||||
->call('saveUsage', $hours->id)
|
||||
->assertHasNoErrors();
|
||||
|
||||
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')]);
|
||||
User::factory()->employee()->create(['name' => 'Ei PINiä']);
|
||||
|
||||
Livewire::test('users::pin-switch', ['returnTo' => $console])
|
||||
->assertSee('Olli Operaattori')
|
||||
->assertDontSee('Ei PINiä')
|
||||
->set('userId', (string) $other->id)
|
||||
->set('pin', '1111')
|
||||
->call('switchUser')
|
||||
->assertHasErrors('pin')
|
||||
->set('pin', '2468')
|
||||
->call('switchUser')
|
||||
->assertRedirect($console);
|
||||
|
||||
expect(auth()->id())->toBe($other->id);
|
||||
});
|
||||
|
||||
it('locks a user\'s PIN code after five wrong attempts', function () {
|
||||
$other = User::factory()->employee()->create(['pin_hash' => Hash::make('2468')]);
|
||||
$component = Livewire::test('users::pin-switch', ['returnTo' => route('machines.console', $this->machine->id)])->set('userId', (string) $other->id);
|
||||
|
||||
foreach (range(1, 5) as $attempt) {
|
||||
$component->set('pin', '0000')->call('switchUser');
|
||||
}
|
||||
|
||||
$component->set('pin', '2468')->call('switchUser')
|
||||
->assertHasErrors('pin')
|
||||
->assertSee('Liian monta väärää yritystä');
|
||||
|
||||
expect(auth()->id())->toBe($this->employee->id);
|
||||
});
|
||||
|
||||
it('does not let a deactivated user in with a PIN code or return to another site', function () {
|
||||
$other = User::factory()->employee()->inactive()->create(['pin_hash' => Hash::make('2468')]);
|
||||
|
||||
Livewire::test('users::pin-switch', ['returnTo' => route('machines.console', $this->machine->id)])
|
||||
->assertDontSee($other->name)
|
||||
->set('userId', (string) $other->id)
|
||||
->set('pin', '2468')
|
||||
->call('switchUser')
|
||||
->assertHasErrors('userId');
|
||||
|
||||
Livewire::test('users::pin-switch', ['returnTo' => 'https://example.com/phish'])->assertNotFound();
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceRecordModel;
|
||||
@@ -54,7 +55,41 @@ it('adds maintenance items with a counter interval, time intervals or both, and
|
||||
$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 () {
|
||||
it('adds the usage of a job to the cumulative counter and refuses an empty or zero usage', function () {
|
||||
$this->actingAs($this->employee);
|
||||
|
||||
Livewire::test('machines::maintenance', ['machineId' => $this->machine->id])
|
||||
->set('usage.'.$this->prints->id, '350')
|
||||
->call('saveUsage', $this->prints->id)
|
||||
->assertHasNoErrors()
|
||||
->set('usage.'.$this->prints->id, '1 000')
|
||||
->call('saveUsage', $this->prints->id)
|
||||
->assertSet('message', "Laskuriin Tulosteet lisätty 1\u{00A0}000 kpl, laskuri nyt 1\u{00A0}350 kpl.")
|
||||
->set('usage.'.$this->prints->id, '0')
|
||||
->call('saveUsage', $this->prints->id)
|
||||
->assertHasErrors('usage.'.$this->prints->id)
|
||||
->set('usage.'.$this->prints->id, '')
|
||||
->call('saveUsage', $this->prints->id)
|
||||
->assertHasErrors('usage.'.$this->prints->id);
|
||||
|
||||
expect(MachineCounterReadingModel::query()->orderBy('id')->pluck('reading_milli')->all())->toBe([350_000, 1_350_000]);
|
||||
});
|
||||
|
||||
it('hides the maintenance sections of a machine without counters and maintenance items from users', function () {
|
||||
$this->prints->delete();
|
||||
$this->actingAs($this->employee);
|
||||
|
||||
Livewire::test('machines::maintenance', ['machineId' => $this->machine->id])
|
||||
->assertDontSee(__('machines.maintenance.items'))
|
||||
->assertDontSee(__('machines.maintenance.history'));
|
||||
|
||||
$this->actingAs($this->manager);
|
||||
Livewire::test('machines::maintenance', ['machineId' => $this->machine->id])
|
||||
->assertSee(__('machines.maintenance.add'))
|
||||
->assertDontSee(__('machines.maintenance.history'));
|
||||
});
|
||||
|
||||
it('shows a maintenance request when due and resets the interval 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,
|
||||
@@ -64,8 +99,8 @@ it('shows a maintenance request when due and starts the interval again with a ma
|
||||
|
||||
Livewire::test('machines::maintenance', ['machineId' => $this->machine->id])
|
||||
->assertSee('Kunnossa')
|
||||
->set('readings.'.$this->prints->id, '19 000')
|
||||
->call('saveReading', $this->prints->id)
|
||||
->set('usage.'.$this->prints->id, '19 000')
|
||||
->call('saveUsage', $this->prints->id)
|
||||
->assertSee('Huolto lähestyy')
|
||||
->assertSee("jäljellä 1\u{00A0}000 kpl", false);
|
||||
|
||||
@@ -74,18 +109,17 @@ it('shows a maintenance request when due and starts the interval again with a ma
|
||||
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("jäljellä 20\u{00A0}000 kpl", false)
|
||||
->assertSee('Rumpu vaihdettu');
|
||||
|
||||
$record = MaintenanceRecordModel::query()->sole();
|
||||
$use = StockMovementModel::query()->sole();
|
||||
|
||||
expect($record->counter_reading_milli)->toBe(19_500_000)
|
||||
expect($record->counter_reading_milli)->toBe(19_000_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]);
|
||||
|
||||
@@ -97,6 +131,12 @@ it('shows a maintenance request when due and starts the interval again with a ma
|
||||
->call('cancelRecord')
|
||||
->assertSee('Peruttu')
|
||||
->assertSee('Huolto myöhässä');
|
||||
|
||||
$reversal = StockMovementModel::query()->where('reverses_movement_id', $use->id)->sole();
|
||||
|
||||
expect($reversal->quantity_milli)->toBe(1_000)
|
||||
->and($reversal->user_id)->toBe($this->manager->id)
|
||||
->and((int) StockMovementModel::query()->where('stock_item_id', $this->drum->id)->sum('quantity_milli'))->toBe(0);
|
||||
});
|
||||
|
||||
it('notifies the responsible person of a maintenance request once', function () {
|
||||
|
||||
@@ -165,3 +165,57 @@ it('sells products without a process at once as before', function () {
|
||||
expect(QuickSaleModel::query()->count())->toBe(1)
|
||||
->and(QuickSaleOrderModel::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('changes an order before making starts and keeps its pickup number', function () {
|
||||
sendOrder($this);
|
||||
$order = QuickSaleOrderModel::query()->sole();
|
||||
$oldLineIds = QuickSaleOrderLineModel::query()->pluck('id')->all();
|
||||
|
||||
Livewire::test('sales::orders')
|
||||
->assertSee(__('sales.orders.change_named', ['number' => 1]))
|
||||
->call('edit', $order->id)
|
||||
->assertDispatched('edit-quick-sale-order', orderId: $order->id);
|
||||
|
||||
Livewire::test('sales::sell')
|
||||
->call('editOrder', $order->id)
|
||||
->assertSet('editingPickupNumber', 1)
|
||||
->assertSet('quantities', [$this->sticker->id => 2, $this->copy->id => 1])
|
||||
->assertSet('orderCustomerName', 'Matti')
|
||||
->assertSee(__('sales.orders.save_change'))
|
||||
->call('addProduct', $this->sticker->id)
|
||||
->set('orderCustomerName', 'Liisa')
|
||||
->call('save')
|
||||
->assertHasNoErrors()
|
||||
->assertSet('editingOrderId', null)
|
||||
->assertSet('savedMessage', fn (string $message) => str_starts_with($message, 'Tilaus 1 muutettu, yhteensä 31,00'));
|
||||
|
||||
$sticker = QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole();
|
||||
|
||||
expect(QuickSaleOrderModel::query()->sole()->only(['id', 'pickup_number', 'customer_name']))
|
||||
->toBe(['id' => $order->id, 'pickup_number' => 1, 'customer_name' => 'Liisa'])
|
||||
->and($sticker->quantity)->toBe(3)
|
||||
->and($sticker->id)->not->toBeIn($oldLineIds)
|
||||
->and(QuickSaleOrderLineModel::query()->count())->toBe(2)
|
||||
->and(MachineQueueEntryModel::query()->sole()->quick_sale_order_line_id)->toBe($sticker->id);
|
||||
});
|
||||
|
||||
it('refuses to change an order once a step is completed', function () {
|
||||
sendOrder($this);
|
||||
$order = QuickSaleOrderModel::query()->sole();
|
||||
|
||||
$sell = Livewire::test('sales::sell')->call('editOrder', $order->id)->assertSet('editingOrderId', $order->id);
|
||||
|
||||
Livewire::test('machines::console', ['machine' => $this->printer->id])
|
||||
->call('startOrderComplete', MachineQueueEntryModel::query()->sole()->id)
|
||||
->call('completeOrder');
|
||||
|
||||
$sell->call('addProduct', $this->sticker->id)
|
||||
->call('save')
|
||||
->assertHasErrors('sale')
|
||||
->assertSet('editingOrderId', null);
|
||||
|
||||
expect(QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole()->quantity)->toBe(2);
|
||||
|
||||
Livewire::test('sales::orders')->assertDontSee(__('sales.orders.change_named', ['number' => 1]));
|
||||
Livewire::test('sales::sell')->call('editOrder', $order->id)->assertHasErrors('sale')->assertSet('editingOrderId', null);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->employee()->create(['name' => 'Eero Työntekijä', 'password' => 'Salasana-123!']);
|
||||
$this->machine = MachineModel::factory()->create(['name' => 'Suurkuvatulostin']);
|
||||
$this->console = route('machines.console', $this->machine->id);
|
||||
});
|
||||
|
||||
it('opens the console signed in as the same user with a one-time key', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$accept = $this->get(route('console.handoff', ['to' => $this->console]))->assertRedirect()->headers->get('Location');
|
||||
|
||||
expect($accept)->toStartWith(url('console/handoff/'));
|
||||
|
||||
$this->get($accept)->assertRedirect($this->console);
|
||||
expect(Auth::guard('console')->id())->toBe($this->user->id);
|
||||
|
||||
Auth::guard('console')->logout();
|
||||
$this->get($accept)->assertRedirect(route('console.login'));
|
||||
expect(Auth::guard('console')->check())->toBeFalse();
|
||||
});
|
||||
|
||||
it('lets a console key expire after a minute and refuses other addresses', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$accept = $this->get(route('console.handoff', ['to' => $this->console]))->headers->get('Location');
|
||||
$this->travel(61)->seconds();
|
||||
$this->get($accept)->assertRedirect(route('console.login'));
|
||||
|
||||
$this->get(route('console.handoff', ['to' => 'https://example.com/console/x']))->assertNotFound();
|
||||
$this->get(route('console.handoff', ['to' => route('customers.index')]))->assertNotFound();
|
||||
});
|
||||
|
||||
it('asks a signed-out console to sign in on the console\'s own page and keeps /login for the normal user interface', function () {
|
||||
$this->get($this->console)->assertRedirect(route('console.login'));
|
||||
expect(session('url.intended'))->toBe($this->console);
|
||||
|
||||
$this->actingAs($this->user, 'console');
|
||||
$this->get(route('login'))->assertOk();
|
||||
$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 () {
|
||||
$this->actingAs($this->user);
|
||||
$this->actingAs($this->user, 'console');
|
||||
|
||||
$this->post(route('console.logout'))->assertRedirect(route('console.login'));
|
||||
|
||||
expect(Auth::guard('console')->check())->toBeFalse()
|
||||
->and(Auth::guard('web')->id())->toBe($this->user->id);
|
||||
});
|
||||
|
||||
it('signs in to the console with a PIN code or a password', function () {
|
||||
$this->user->forceFill(['pin_hash' => Hash::make('2468')])->save();
|
||||
session()->put('url.intended', $this->console);
|
||||
|
||||
Livewire::test('users::console-login')
|
||||
->assertSee('Eero Työntekijä')
|
||||
->set('userId', (string) $this->user->id)
|
||||
->set('pin', '2468')
|
||||
->call('loginWithPin')
|
||||
->assertRedirect($this->console);
|
||||
|
||||
Auth::logout();
|
||||
session()->put('url.intended', $this->console);
|
||||
|
||||
Livewire::test('users::console-login')
|
||||
->set('email', $this->user->email)
|
||||
->set('password', 'Salasana-123!')
|
||||
->call('loginWithPassword')
|
||||
->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]])]]]),
|
||||
fn (Request $request) => $request->headers->set('X-Livewire', '1'),
|
||||
);
|
||||
|
||||
expect(UseConsoleSession::isConsole(Request::create('/console/machines/1')))->toBeTrue()
|
||||
->and(UseConsoleSession::isConsole(Request::create('/console-handoff')))->toBeFalse()
|
||||
->and(UseConsoleSession::isConsole(Request::create('/machines/1')))->toBeFalse()
|
||||
->and(UseConsoleSession::isConsole($livewire('console/machines/1')))->toBeTrue()
|
||||
->and(UseConsoleSession::isConsole($livewire('machines/1')))->toBeFalse();
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->employee()->create(['password' => 'Salasana-123!']);
|
||||
$this->actingAs($this->user);
|
||||
});
|
||||
|
||||
it('sets the console PIN code with the user\'s password and stores only its hash', function () {
|
||||
$this->get(route('profile.pin'))->assertOk()->assertSee(__('users.pin.not_set'));
|
||||
|
||||
Livewire::test('users::pin')
|
||||
->set('currentPassword', 'väärä')
|
||||
->set('pin', '2468')
|
||||
->set('pinConfirmation', '2468')
|
||||
->call('save')
|
||||
->assertHasErrors('currentPassword')
|
||||
->set('currentPassword', 'Salasana-123!')
|
||||
->set('pin', '24a8')
|
||||
->set('pinConfirmation', '24a8')
|
||||
->call('save')
|
||||
->assertHasErrors('pin')
|
||||
->set('pin', '2468')
|
||||
->set('pinConfirmation', '2469')
|
||||
->call('save')
|
||||
->assertHasErrors('pinConfirmation')
|
||||
->set('pinConfirmation', '2468')
|
||||
->call('save')
|
||||
->assertHasNoErrors()
|
||||
->assertSet('message', __('users.pin.saved'));
|
||||
|
||||
$hash = $this->user->fresh()->pin_hash;
|
||||
|
||||
expect($hash)->not->toBe('2468')
|
||||
->and(Hash::check('2468', $hash))->toBeTrue()
|
||||
->and($this->user->fresh()->toArray())->not->toHaveKey('pin_hash');
|
||||
});
|
||||
|
||||
it('removes the PIN code with the user\'s password', function () {
|
||||
$this->user->forceFill(['pin_hash' => Hash::make('2468')])->save();
|
||||
|
||||
Livewire::test('users::pin')
|
||||
->set('currentPassword', 'Salasana-123!')
|
||||
->call('remove')
|
||||
->assertSet('message', __('users.pin.removed'));
|
||||
|
||||
expect($this->user->fresh()->pin_hash)->toBeNull();
|
||||
});
|
||||
|
||||
it('stops checking the password after 5 wrong ones a minute', function () {
|
||||
$component = Livewire::test('users::pin');
|
||||
|
||||
foreach (range(1, 5) as $attempt) {
|
||||
$component->set('currentPassword', 'väärä')->call('remove')->assertHasErrors(['currentPassword' => __('users.pin.errors.password')]);
|
||||
}
|
||||
|
||||
$this->user->forceFill(['pin_hash' => Hash::make('2468')])->save();
|
||||
|
||||
$component->set('currentPassword', 'Salasana-123!')
|
||||
->call('remove')
|
||||
->assertHasErrors('currentPassword')
|
||||
->assertSet('message', '');
|
||||
|
||||
expect($this->user->fresh()->pin_hash)->not->toBeNull();
|
||||
|
||||
$this->travel(61)->seconds();
|
||||
|
||||
$component->set('currentPassword', 'Salasana-123!')
|
||||
->call('remove')
|
||||
->assertSet('message', __('users.pin.removed'));
|
||||
});
|
||||
|
||||
it('is not offered to subcontractors', function () {
|
||||
$this->actingAs(User::factory()->subcontractor()->create());
|
||||
|
||||
$this->get(route('profile.pin'))->assertForbidden();
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Application\Contracts\SecretHasher;
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use App\Modules\Users\Application\UseCases\LoginPins;
|
||||
use App\Modules\Users\Domain\Contracts\LoginSecrets;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\WrongPassword;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
use Tests\Fakes\FakeClock;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\InMemoryUserAccountRepository;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->users = new InMemoryUserAccountRepository;
|
||||
$this->userId = $this->users->save(UserAccount::register(new PersonName('Olli'), new EmailAddress('[email protected]'), Role::Employee))->id();
|
||||
|
||||
$this->secrets = new class implements LoginSecrets
|
||||
{
|
||||
/** @var array<int, string> */
|
||||
public array $passwords = [];
|
||||
|
||||
/** @var array<int, string> */
|
||||
public array $pins = [];
|
||||
|
||||
public function passwordHashOf(int $userId): ?string
|
||||
{
|
||||
return $this->passwords[$userId] ?? null;
|
||||
}
|
||||
|
||||
public function pinHashOf(int $userId): ?string
|
||||
{
|
||||
return $this->pins[$userId] ?? null;
|
||||
}
|
||||
|
||||
public function storePinHash(int $userId, ?string $hash): void
|
||||
{
|
||||
if ($hash === null) {
|
||||
unset($this->pins[$userId]);
|
||||
} else {
|
||||
$this->pins[$userId] = $hash;
|
||||
}
|
||||
}
|
||||
};
|
||||
$this->secrets->passwords[$this->userId] = 'hashed:Salasana-123!';
|
||||
|
||||
$hasher = new class implements SecretHasher
|
||||
{
|
||||
public function hash(string $secret): string
|
||||
{
|
||||
return 'hashed:'.$secret;
|
||||
}
|
||||
|
||||
public function check(string $secret, string $hash): bool
|
||||
{
|
||||
return $hash === 'hashed:'.$secret;
|
||||
}
|
||||
};
|
||||
|
||||
$this->clock = new FakeClock(new DateTimeImmutable('2027-05-31'));
|
||||
$this->pins = new LoginPins($this->secrets, $hasher, new CheckLoginAllowed($this->users, $this->clock), new FakeTransactionManager);
|
||||
});
|
||||
|
||||
it('sets a PIN code only with the right password and verifies it', function () {
|
||||
expect(fn () => $this->pins->set($this->userId, 'väärä', '2468'))->toThrow(WrongPassword::class);
|
||||
|
||||
$this->pins->set($this->userId, 'Salasana-123!', '2468');
|
||||
|
||||
expect($this->secrets->pins[$this->userId])->toBe('hashed:2468')
|
||||
->and($this->pins->verify($this->userId, '2468'))->toBeTrue()
|
||||
->and($this->pins->verify($this->userId, '1111'))->toBeFalse()
|
||||
->and($this->pins->verify(999, '2468'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('refuses a right PIN code of an intern whose last day has passed', function () {
|
||||
$internId = $this->users->save(UserAccount::register(new PersonName('Ida'), new EmailAddress('[email protected]'), Role::Intern, new DateTimeImmutable('2027-05-31'), $this->userId))->id();
|
||||
$this->secrets->passwords[$internId] = 'hashed:Salasana-123!';
|
||||
$this->pins->set($internId, 'Salasana-123!', '1357');
|
||||
|
||||
expect($this->pins->verify($internId, '1357'))->toBeTrue();
|
||||
|
||||
$this->clock->today = new DateTimeImmutable('2027-06-01');
|
||||
|
||||
expect($this->pins->verify($internId, '1357'))->toBeFalse();
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
|
||||
use App\Modules\Users\Domain\ValueObjects\LoginPin;
|
||||
|
||||
it('accepts 4–6 digits as a PIN code', function (string $pin) {
|
||||
expect((new LoginPin($pin))->value)->toBe(trim($pin));
|
||||
})->with(['1234', '123456', ' 0042 ']);
|
||||
|
||||
it('refuses other PIN codes', function (string $pin) {
|
||||
new LoginPin($pin);
|
||||
})->with(['123', '1234567', '12a4', ''])->throws(InvalidLoginPin::class);
|
||||
Reference in New Issue
Block a user