Files
Toiminnanohjaus/app/Modules/Inventory/Presentation/Livewire/⚡item.blade.php
T
2026-11-26 16:18:59 +02:00

523 lines
23 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\PurchaseData;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockPurchase;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\RecordStockWriteOff;
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
use App\Modules\Inventory\Application\UseCases\SetStockItemActive;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
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\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
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;
/**
* A stock item's page (spec 19.1–19.2): its details and balance, the
* movement history with the balance after each, and the forms to record a
* purchase or a write-off (management) and use without a target (everyone
* using stock). Movements are corrected with reversals.
*/
new class extends Component
{
use FormatsStock;
public const int HISTORY_LIMIT = 200;
#[Locked]
public int $itemId;
#[Locked]
public string $message = '';
#[Locked]
public ?int $reverseMovementId = null;
public string $purchaseDay = '';
public string $purchaseQuantity = '';
public string $purchaseTotal = '';
public string $purchaseUnitPrice = '';
public string $purchaseSupplier = '';
public string $purchaseDocument = '';
public string $writeOffQuantity = '';
public string $writeOffReason = '';
public string $useQuantity = '';
public string $useReason = '';
public function mount(StockQueries $stock, Clock $clock, int $item): void
{
$this->authorize('inventory.view');
$summary = $stock->findItem($item) ?? abort(404);
$this->itemId = $summary->id;
$this->purchaseDay = $clock->today()->format('Y-m-d');
$this->purchaseSupplier = (string) $summary->supplier;
$this->message = (string) session('status', '');
}
#[Computed]
public function item(): StockItemSummary
{
return app(StockQueries::class)->findItem($this->itemId) ?? abort(404);
}
/**
* @return list<StockMovementSummary>
*/
#[Computed]
public function movements(): array
{
return app(StockQueries::class)->movementsOf($this->itemId, self::HISTORY_LIMIT);
}
public function recordPurchase(RecordStockPurchase $recordPurchase): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
if (trim($this->purchaseTotal) === '' && trim($this->purchaseUnitPrice) === '') {
$this->addError('purchaseTotal', __('inventory.errors.price_required'));
return;
}
try {
$recordPurchase->execute(new PurchaseData(
$this->itemId,
$this->purchaseDay,
$this->purchaseQuantity,
$this->purchaseTotal,
$this->purchaseUnitPrice,
$this->purchaseSupplier,
$this->purchaseDocument,
), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('purchaseQuantity', __('inventory.errors.quantity'));
return;
} catch (InvalidStockCost) {
$this->addError(trim($this->purchaseTotal) !== '' ? 'purchaseTotal' : 'purchaseUnitPrice', __('inventory.errors.cost'));
return;
} catch (InvalidStockDay) {
$this->addError('purchaseDay', __('inventory.errors.day'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.purchase.saved', [
'quantity' => $this->quantity((int) round((float) str_replace(',', '.', $this->purchaseQuantity) * 1000), $this->item->unit),
'balance' => $this->quantity($this->item->balanceMilli, $this->item->unit),
'cost' => $this->unitCost($this->item->averageCostHundredths),
]);
$this->reset('purchaseQuantity', 'purchaseTotal', 'purchaseUnitPrice', 'purchaseDocument');
$this->js("document.getElementById('item-status')?.focus()");
}
public function recordWriteOff(RecordStockWriteOff $recordWriteOff): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
try {
$result = $recordWriteOff->execute(new StockUseData($this->itemId, $this->writeOffQuantity, reason: $this->writeOffReason), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('writeOffQuantity', __('inventory.errors.quantity'));
return;
} catch (StockReasonRequired) {
$this->addError('writeOffReason', __('inventory.errors.reason'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.write_off.saved', [
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
]);
$this->reset('writeOffQuantity', 'writeOffReason');
$this->js("document.getElementById('item-status')?.focus()");
}
public function recordUse(RecordStockUse $recordUse): void
{
$this->authorize('inventory.record-use');
$this->resetErrorBag();
try {
$result = $recordUse->execute(new StockUseData($this->itemId, $this->useQuantity, reason: $this->useReason), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('useQuantity', __('inventory.errors.quantity'));
return;
} catch (StockReasonRequired) {
$this->addError('useReason', __('inventory.errors.reason'));
return;
} catch (StockItemInactive) {
$this->addError('useQuantity', __('inventory.errors.inactive'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.use.saved', [
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
]);
$this->reset('useQuantity', 'useReason');
$this->js("document.getElementById('item-status')?.focus()");
}
public function confirmReverse(int $movementId): void
{
$movement = $this->movement($movementId);
abort_unless($this->mayReverse($movement), 403);
$this->reverseMovementId = $movementId;
$this->js("document.getElementById('reverse-dialog').showModal()");
}
public function reverse(ReverseStockMovement $reverseMovement): void
{
$movement = $this->movement((int) $this->reverseMovementId);
abort_unless($this->mayReverse($movement), 403);
try {
$reverseMovement->execute($movement->id, (int) auth()->id(), Gate::allows('inventory.reverse-any'));
$this->refreshItem();
$this->message = __('inventory.item.reversed', ['balance' => $this->quantity($this->item->balanceMilli, $this->item->unit)]);
} catch (StockMovementNotFound) {
$this->message = __('inventory.errors.not_found');
} catch (StockMovementAlreadyReversed) {
$this->message = __('inventory.errors.already_reversed');
} catch (StockMovementNotReversible) {
$this->message = __('inventory.errors.not_reversible');
} catch (StockReversalNotAllowed) {
$this->message = __('inventory.errors.reversal_not_allowed');
}
$this->reverseMovementId = null;
$this->refreshItem();
$this->js("document.getElementById('reverse-dialog').close(); document.getElementById('item-status').focus()");
}
public function toggleActive(SetStockItemActive $setActive): void
{
$this->authorize('inventory.manage');
$active = ! $this->item->isActive;
$setActive->execute($this->itemId, $active);
$this->refreshItem();
$this->message = __($active ? 'inventory.item.activated' : 'inventory.item.deactivated');
}
public function mayReverse(StockMovementSummary $movement): bool
{
if (! $movement->canBeReversed()) {
return false;
}
if (Gate::allows('inventory.reverse-any')) {
return true;
}
return Gate::allows('inventory.record-use')
&& $movement->kind->value === 'consumption'
&& $movement->userId === (int) auth()->id()
&& $movement->occurredOn === app(Clock::class)->today()->format('Y-m-d');
}
public function targetText(StockMovementSummary $movement): string
{
$parts = [];
if ($movement->taskId !== null) {
$parts[] = __('inventory.item.target_task', ['id' => $movement->taskId]);
}
if ($movement->machineId !== null) {
$parts[] = __('inventory.item.target_machine', ['id' => $movement->machineId]);
}
if ($movement->orderLineId !== null) {
$parts[] = __('inventory.item.target_order');
}
if ($movement->maintenanceRecordId !== null) {
$parts[] = __('inventory.item.target_maintenance');
}
if ($movement->inventoryCountId !== null) {
$parts[] = __('inventory.item.target_count', ['id' => $movement->inventoryCountId]);
}
if ($movement->supplier !== null) {
$parts[] = $movement->supplier;
}
if ($movement->documentNumber !== null) {
$parts[] = __('inventory.item.document', ['number' => $movement->documentNumber]);
}
if ($movement->reason !== null) {
$parts[] = $movement->reason;
}
if ($movement->reversesMovementId !== null) {
$parts[] = __('inventory.item.reverses', ['number' => $movement->reversesMovementId]);
}
return $parts === [] ? '–' : implode(', ', $parts);
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
$headers = [
['index' => 'time', 'label' => __('inventory.columns.time'), 'sortable' => false],
['index' => 'kind', 'label' => __('inventory.columns.kind'), 'sortable' => false],
['index' => 'quantity', 'label' => __('inventory.columns.quantity'), 'sortable' => false, 'align' => 'right'],
['index' => 'balance', 'label' => __('inventory.columns.balance_after'), 'sortable' => false, 'align' => 'right'],
['index' => 'user', 'label' => __('inventory.columns.user'), 'sortable' => false],
['index' => 'target', 'label' => __('inventory.columns.target'), 'sortable' => false],
];
if (Gate::allows('inventory.see-value')) {
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
}
$headers[] = ['index' => 'actions', 'label' => __('inventory.columns.actions'), 'sortable' => false];
return $headers;
}
public function render(): mixed
{
return $this->view()->title($this->item->name);
}
private function movement(int $movementId): StockMovementSummary
{
$movement = app(StockQueries::class)->findMovement($movementId);
abort_if($movement === null || $movement->itemId !== $this->itemId, 404);
return $movement;
}
private function refreshItem(): void
{
unset($this->item, $this->movements);
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
@php($item = $this->item)
<div class="flex flex-wrap items-start gap-4">
@if ($item->hasImage)
<img src="{{ route('inventory.items.image', [$item->id, 'thumbnail']) }}" alt="{{ __('inventory.item.image_alt', ['name' => $item->name]) }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
@endif
<div class="min-w-0 flex-1 space-y-2">
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
<h1 class="text-2xl font-semibold break-words">{{ $item->name }}</h1>
<x-inventory.stock-status :item="$item" />
@can('inventory.manage')
<div class="flex flex-wrap gap-2">
<x-button :href="route('inventory.items.edit', $item->id)" wire:navigate sm icon="pencil" :text="__('inventory.item.edit')" />
<x-button wire:click="toggleActive" subtle color="black" sm :icon="$item->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'" :text="$item->isActive ? __('inventory.item.deactivate') : __('inventory.item.activate')" />
</div>
@endcan
</div>
</div>
<p id="item-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
<section aria-labelledby="details-heading" class="space-y-3">
<h2 id="details-heading" class="text-lg font-semibold">{{ __('inventory.item.details') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
<div>
<dt class="font-medium">{{ __('inventory.item.balance') }}</dt>
<dd class="text-lg font-semibold">{{ $this->quantity($item->balanceMilli, $item->unit) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.group') }}</dt>
<dd>{{ $item->groupName }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.reorder_level') }}</dt>
<dd>{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.form.code') }}</dt>
<dd>{{ $item->code ?? '–' }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.form.supplier') }}</dt>
<dd>{{ $item->supplier ?? '–' }}</dd>
</div>
@can('inventory.see-value')
<div>
<dt class="font-medium">{{ __('inventory.columns.average_cost') }}</dt>
<dd>{{ $this->unitCost($item->averageCostHundredths) }} / {{ __('inventory.units.'.$item->unit->value) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.value') }}</dt>
<dd>{{ $this->money($item->valueCents) }}</dd>
</div>
@endcan
</dl>
@if ($item->isNegative())
<p class="flex items-start gap-2 text-sm font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('inventory.use.negative_warning') }}
</p>
@endif
</section>
@php($unitLabel = __('inventory.units.'.$item->unit->value))
<div class="grid gap-6 lg:grid-cols-2">
@can('inventory.manage')
<section aria-labelledby="purchase-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="purchase-heading" class="text-lg font-semibold">{{ __('inventory.purchase.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.purchase.intro') }}</p>
<form wire:submit="recordPurchase" class="space-y-4" novalidate>
<x-input id="purchase-day" wire:model="purchaseDay" type="date" :label="__('inventory.purchase.day')" required />
<x-input id="purchase-quantity" wire:model="purchaseQuantity" inputmode="decimal" :label="__('inventory.purchase.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="purchase-total" wire:model="purchaseTotal" inputmode="decimal" :label="__('inventory.purchase.total_price')" autocomplete="off" />
<x-input id="purchase-unit-price" wire:model="purchaseUnitPrice" inputmode="decimal" :label="__('inventory.purchase.unit_price', ['unit' => $unitLabel])" :hint="__('inventory.purchase.unit_price_hint')" autocomplete="off" />
<x-input id="purchase-supplier" wire:model="purchaseSupplier" :label="__('inventory.purchase.supplier')" autocomplete="off" maxlength="255" />
<x-input id="purchase-document" wire:model="purchaseDocument" :label="__('inventory.purchase.document_number')" autocomplete="off" maxlength="255" />
<x-button submit icon="truck" :text="__('inventory.purchase.save')" />
</form>
</section>
<section aria-labelledby="write-off-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="write-off-heading" class="text-lg font-semibold">{{ __('inventory.write_off.title') }}</h2>
<form wire:submit="recordWriteOff" class="space-y-4" novalidate>
<x-input id="write-off-quantity" wire:model="writeOffQuantity" inputmode="decimal" :label="__('inventory.write_off.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="write-off-reason" wire:model="writeOffReason" :label="__('inventory.write_off.reason')" :hint="__('inventory.write_off.reason_hint')" autocomplete="off" maxlength="255" />
<x-button submit icon="trash" :text="__('inventory.write_off.save')" />
</form>
</section>
@endcan
@if ($item->isActive)
@can('inventory.record-use')
<section aria-labelledby="use-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="use-heading" class="text-lg font-semibold">{{ __('inventory.use.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.use.intro') }}</p>
<form wire:submit="recordUse" class="space-y-4" novalidate>
<x-input id="use-quantity" wire:model="useQuantity" inputmode="decimal" :label="__('inventory.use.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="use-reason" wire:model="useReason" :label="__('inventory.use.reason')" autocomplete="off" maxlength="255" />
<x-button submit icon="minus-circle" :text="__('inventory.use.save')" />
</form>
</section>
@endcan
@else
<p class="text-sm">{{ __('inventory.item.inactive_note') }}</p>
@endif
</div>
<section aria-labelledby="history-heading" class="space-y-3">
<h2 id="history-heading" class="text-lg font-semibold">{{ __('inventory.item.history') }}</h2>
@if ($this->movements === [])
<p class="text-sm">{{ __('inventory.item.history_none') }}</p>
@else
@if (count($this->movements) >= $this::HISTORY_LIMIT)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}</p>
@endif
<x-table :headers="$this->headers()" :rows="$this->movements">
@interact('column_time', $movement)
<span class="whitespace-nowrap">{{ $this->dateLabel($movement->recordedAt) }}</span>
@if ($movement->occurredOn !== substr($movement->recordedAt, 0, 10))
<span class="block text-xs">{{ $this->dateLabel($movement->occurredOn) }}</span>
@endif
@endinteract
@interact('column_kind', $movement)
{{ __('inventory.kinds.'.$movement->kind->value) }}
@if ($movement->reversedByMovementId !== null)
<span class="block text-xs">{{ __('inventory.item.reversed_by', ['number' => $movement->reversedByMovementId]) }}</span>
@endif
@endinteract
@interact('column_quantity', $movement)
<span class="whitespace-nowrap">{{ ($movement->quantityMilli > 0 ? '+' : '').$this->quantity($movement->quantityMilli) }}</span>
@endinteract
@interact('column_balance', $movement)
<span class="whitespace-nowrap">{{ $this->quantity($movement->balanceAfterMilli) }}</span>
@endinteract
@interact('column_user', $movement)
{{ $movement->userName }}
@endinteract
@interact('column_target', $movement)
<span class="whitespace-normal">{{ $this->targetText($movement) }}</span>
@endinteract
@interact('column_value', $movement)
<span class="whitespace-nowrap">{{ $this->money($movement->valueCents) }}</span>
@endinteract
@interact('column_actions', $movement)
@if ($this->mayReverse($movement))
<x-button
wire:click="confirmReverse({{ $movement->id }})"
subtle
color="black"
sm
icon="arrow-uturn-left"
:text="__('inventory.item.reverse')"
:aria-label="__('inventory.item.reverse_named', ['kind' => __('inventory.kinds.'.$movement->kind->value), 'quantity' => $this->quantity($movement->quantityMilli), 'time' => $this->dateLabel($movement->recordedAt)])"
/>
@endif
@endinteract
</x-table>
@endif
</section>
<x-confirm-dialog id="reverse-dialog" :title="__('inventory.item.reverse_title')">
@php($reverseMovement = $reverseMovementId === null ? null : collect($this->movements)->firstWhere('id', $reverseMovementId))
@if ($reverseMovement !== null)
<p>{{ __('inventory.item.reverse_text', ['kind' => __('inventory.kinds.'.$reverseMovement->kind->value), 'quantity' => $this->quantity($reverseMovement->quantityMilli, $item->unit)]) }}</p>
@endif
<x-slot:actions>
<x-button wire:click="reverse" color="red" :text="__('inventory.item.reverse_confirm')" />
</x-slot:actions>
</x-confirm-dialog>
</div>