Files
Toiminnanohjaus/app/Modules/Inventory/Presentation/Livewire/⚡task-materials.blade.php
T

392 lines
17 KiB
PHP

<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\Contracts\StockTasks;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Application\DTOs\StockTaskContext;
use App\Modules\Inventory\Application\DTOs\TaskMaterialSuggestion;
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
use App\Modules\Inventory\Application\UseCases\TaskMaterials;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Inventory\Domain\Exceptions\StockTaskNotAvailable;
use App\Modules\Inventory\Domain\Exceptions\StockTaskSuggestionNotFound;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Used material of a job's task (Käytetty materiaali, spec 19.4), shown in
* the task's card on the job page and made for phones too, as installation
* is often done at the customer's. Material is searched by name or code
* and recorded as used on the task; a workflow step's default materials
* wait as suggestions until confirmed. Users undo their own use of today.
* Shown only when the task's service unit uses stock; earlier use stays
* visible read-only.
*/
new class extends Component
{
use FormatsStock;
public const int RESULT_LIMIT = 8;
#[Locked]
public int $jobId;
#[Locked]
public int $taskId;
#[Locked]
public string $taskTitle = '';
public string $search = '';
#[Locked]
public ?int $selectedItemId = null;
public string $quantity = '1';
/**
* Quantities of the suggestions as edited, by suggestion id.
*
* @var array<int, string>
*/
public array $suggestionQuantities = [];
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('jobs.view-job', $this->jobId);
$context = $this->context;
abort_if($context !== null && $context->jobId !== $this->jobId, 404);
foreach ($this->suggestions as $suggestion) {
$this->suggestionQuantities[$suggestion->id] = StockQuantity::inputValue($suggestion->quantityMilli);
}
}
#[Computed]
public function context(): ?StockTaskContext
{
return app(StockTasks::class)->context($this->taskId);
}
/**
* @return list<StockMovementSummary>
*/
#[Computed]
public function movements(): array
{
return app(StockQueries::class)->taskMovements($this->taskId);
}
/**
* @return list<TaskMaterialSuggestion>
*/
#[Computed]
public function suggestions(): array
{
return app(StockQueries::class)->taskSuggestions($this->taskId);
}
/**
* @return list<StockItemSummary>
*/
#[Computed]
public function results(): array
{
$term = trim($this->search);
return mb_strlen($term) < 2 ? [] : array_slice(app(StockQueries::class)->items($term), 0, self::RESULT_LIMIT);
}
#[Computed]
public function selectedItem(): ?StockItemSummary
{
return $this->selectedItemId === null ? null : app(StockQueries::class)->findItem($this->selectedItemId);
}
public function canRecord(): bool
{
$context = $this->context;
return $context !== null && $context->usesStock && ! $context->isLocked && Gate::allows('inventory.record-use');
}
public function selectItem(int $itemId): void
{
$this->authorizeRecording();
$this->selectedItemId = $itemId;
$this->quantity = '1';
$this->search = '';
$this->resetErrorBag();
$this->js("document.getElementById('task-{$this->taskId}-material-quantity')?.focus()");
}
public function clearItem(): void
{
$this->selectedItemId = null;
$this->js("document.getElementById('task-{$this->taskId}-material-search')?.focus()");
}
public function record(TaskMaterials $materials): void
{
$this->authorizeRecording();
$this->resetErrorBag();
if ($this->selectedItemId === null) {
return;
}
try {
$result = $materials->record($this->taskId, $this->selectedItemId, $this->quantity, (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('quantity', __('inventory.errors.quantity'));
return;
} catch (StockItemInactive) {
$this->addError('quantity', __('inventory.errors.inactive'));
return;
} catch (StockItemNotFound|StockTaskNotAvailable) {
$this->message = __('inventory.errors.not_found');
return;
}
$unit = $this->selectedItem?->unit;
$this->message = __('inventory.task.recorded', [
'item' => $result->itemName,
'quantity' => $this->quantity($result->quantityMilli, $unit),
'balance' => $this->quantity($result->balanceMilli, $unit),
]);
$this->selectedItemId = null;
$this->quantity = '1';
unset($this->movements);
$this->js("document.getElementById('task-{$this->taskId}-material-search')?.focus()");
}
public function confirmSuggestion(int $suggestionId, TaskMaterials $materials): void
{
$this->authorizeRecording();
$this->resetErrorBag();
$suggestion = collect($this->suggestions)->firstWhere('id', $suggestionId);
try {
$result = $materials->confirm($this->taskId, $suggestionId, $this->suggestionQuantities[$suggestionId] ?? '', (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('suggestionQuantities.'.$suggestionId, __('inventory.errors.quantity'));
return;
} catch (StockItemInactive) {
$this->addError('suggestionQuantities.'.$suggestionId, __('inventory.errors.inactive'));
return;
} catch (StockItemNotFound|StockTaskNotAvailable|StockTaskSuggestionNotFound) {
$this->message = __('inventory.errors.not_found');
unset($this->suggestions);
return;
}
$this->message = __('inventory.task.recorded', [
'item' => $result->itemName,
'quantity' => $this->quantity($result->quantityMilli, $suggestion?->unit),
'balance' => $this->quantity($result->balanceMilli, $suggestion?->unit),
]);
unset($this->suggestions, $this->movements, $this->suggestionQuantities[$suggestionId]);
$this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()");
}
public function dismissSuggestion(int $suggestionId, TaskMaterials $materials): void
{
$this->authorizeRecording();
$suggestion = collect($this->suggestions)->firstWhere('id', $suggestionId);
try {
$materials->dismiss($this->taskId, $suggestionId);
} catch (StockTaskSuggestionNotFound) {
// Already handled elsewhere: the list is refreshed below.
}
$this->message = __('inventory.task.dismissed', ['item' => $suggestion?->itemName ?? '']);
unset($this->suggestions, $this->suggestionQuantities[$suggestionId]);
$this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()");
}
public function undo(int $movementId, ReverseStockMovement $reverse): void
{
$this->authorize('inventory.record-use');
$movement = collect($this->movements)->firstWhere('id', $movementId);
abort_if($movement === null || ! $this->mayUndo($movement), 403);
try {
$reverse->execute($movementId, (int) auth()->id(), Gate::allows('inventory.reverse-any'));
$this->message = __('inventory.task.undone', ['item' => $movement->itemName, 'quantity' => $this->quantity(-$movement->quantityMilli, $movement->unit)]);
} catch (StockMovementNotFound|StockMovementAlreadyReversed) {
$this->message = __('inventory.errors.already_reversed');
} catch (StockReversalNotAllowed) {
$this->message = __('inventory.errors.reversal_not_allowed');
}
unset($this->movements);
$this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()");
}
/**
* Users undo their own use on the day it was recorded; management any use.
*/
public function mayUndo(StockMovementSummary $movement): bool
{
if (! $movement->canBeReversed() || $movement->kind->value !== 'consumption' || ! $this->canRecord()) {
return false;
}
return Gate::allows('inventory.reverse-any')
|| ($movement->userId === (int) auth()->id() && $movement->occurredOn === app(Clock::class)->today()->format('Y-m-d'));
}
private function authorizeRecording(): void
{
$this->authorize('jobs.view-job', $this->jobId);
abort_unless($this->canRecord(), 403);
}
};
?>
<div>
@if (($this->context?->usesStock ?? false) || $this->movements !== [])
<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>
@if ($this->canRecord())
@if ($this->suggestions !== [])
<div class="space-y-2 rounded-md border border-zinc-300 p-3 dark:border-zinc-600">
<p class="text-sm font-medium">{{ __('inventory.task.suggestions') }}</p>
<ul class="space-y-2">
@foreach ($this->suggestions as $suggestion)
<li wire:key="suggestion-{{ $suggestion->id }}" class="flex flex-wrap items-end gap-2">
<div class="w-28">
<x-input
id="suggestion-{{ $suggestion->id }}-quantity"
wire:model="suggestionQuantities.{{ $suggestion->id }}"
inputmode="decimal"
:label="__('inventory.task.quantity_of', ['item' => $suggestion->itemName, 'unit' => __('inventory.units.'.$suggestion->unit->value)])"
autocomplete="off"
/>
</div>
<x-button wire:click="confirmSuggestion({{ $suggestion->id }})" sm icon="check" :text="__('inventory.task.confirm')" :aria-label="__('inventory.task.confirm_named', ['item' => $suggestion->itemName])" />
<x-button wire:click="dismissSuggestion({{ $suggestion->id }})" subtle color="black" sm icon="x-mark" :text="__('inventory.task.dismiss')" :aria-label="__('inventory.task.dismiss_named', ['item' => $suggestion->itemName])" />
</li>
@endforeach
</ul>
</div>
@endif
@if ($this->selectedItem !== null)
<form wire:submit="record" class="flex flex-wrap items-end gap-2" novalidate>
<p class="w-full text-sm">
<span class="font-medium">{{ $this->selectedItem->name }}</span>
({{ __('inventory.task.balance', ['balance' => $this->quantity($this->selectedItem->balanceMilli, $this->selectedItem->unit)]) }})
</p>
<div class="w-32">
<x-input
id="task-{{ $taskId }}-material-quantity"
wire:model="quantity"
inputmode="decimal"
:label="__('inventory.task.quantity', ['unit' => __('inventory.units.'.$this->selectedItem->unit->value)])"
autocomplete="off"
/>
</div>
<x-button submit icon="check" :text="__('inventory.task.record')" />
<x-button wire:click="clearItem" subtle color="black" :text="__('inventory.task.change_item')" />
</form>
@else
<div class="space-y-2">
<x-input
id="task-{{ $taskId }}-material-search"
wire:model.live.debounce.300ms="search"
type="search"
icon="magnifying-glass"
:label="__('inventory.task.search')"
:hint="__('inventory.task.search_hint')"
autocomplete="off"
/>
@if (mb_strlen(trim($search)) >= 2)
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('inventory.task.results', count($this->results), ['count' => count($this->results)]) }}
</p>
<ul class="space-y-1">
@foreach ($this->results as $result)
<li wire:key="material-result-{{ $taskId }}-{{ $result->id }}">
<button
type="button"
wire:click="selectItem({{ $result->id }})"
class="flex min-h-11 w-full flex-wrap items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
aria-label="{{ __('inventory.task.choose', ['item' => $result->name, 'balance' => $this->quantity($result->balanceMilli, $result->unit)]) }}"
>
<span class="font-medium">{{ $result->name }}</span>
<span class="text-zinc-700 dark:text-zinc-300">{{ $this->quantity($result->balanceMilli, $result->unit) }}</span>
</button>
</li>
@endforeach
</ul>
@endif
</div>
@endif
@endif
@if ($this->movements === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.task.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 text-sm dark:divide-zinc-700">
@foreach ($this->movements as $movement)
<li wire:key="task-material-{{ $movement->id }}" class="flex flex-wrap items-center justify-between gap-2 py-2">
<span>
<span class="font-medium">{{ $movement->itemName }}</span>
{{ $this->quantity(-$movement->quantityMilli, $movement->unit) }}
<span class="text-zinc-600 dark:text-zinc-300">
· {{ __('inventory.kinds.'.$movement->kind->value) }} · {{ $movement->userName }}, {{ $this->dateLabel($movement->recordedAt) }}
@if ($movement->reversedByMovementId !== null)
· {{ __('inventory.task.undone_mark') }}
@endif
</span>
</span>
@if ($this->mayUndo($movement))
<x-button
wire:click="undo({{ $movement->id }})"
subtle
color="black"
sm
icon="arrow-uturn-left"
:text="__('inventory.task.undo')"
:aria-label="__('inventory.task.undo_named', ['item' => $movement->itemName, 'quantity' => $this->quantity(-$movement->quantityMilli, $movement->unit)])"
/>
@endif
</li>
@endforeach
</ul>
@endif
</section>
@endif
</div>