Add stock items, groups and movements at a moving average cost

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:18:59 +02:00
co-authored by Claude Sonnet 5.5
parent 361a2974cf
commit 30132deb0e
81 changed files with 4968 additions and 115 deletions
@@ -0,0 +1,27 @@
<?php
namespace App\Modules\Inventory\Presentation\Http\Controllers;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
/**
* A stock item's image or its thumbnail from the private disk, to those who
* see the stock.
*/
class ShowStockItemImage
{
public function __invoke(int $item, string $size, StockQueries $stock): Response
{
Gate::authorize('inventory.view');
$path = $stock->imagePathOf($item, $size === 'thumbnail') ?? abort(404);
$disk = Storage::disk('local');
abort_unless($disk->exists($path), 404);
return $disk->response($path, basename($path), ['Content-Type' => 'image/jpeg', 'Cache-Control' => 'private, max-age=86400']);
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Inventory\Presentation\Livewire\Concerns;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Carbon\CarbonImmutable;
/**
* Formatting shared by the stock pages and the components that show stock
* elsewhere (task material, machine console). Values may be negative.
*/
trait FormatsStock
{
public function quantity(int $milli, StockUnit|string|null $unit = null): string
{
$unitKey = $unit instanceof StockUnit ? $unit->value : $unit;
return StockQuantity::format($milli).($unitKey === null ? '' : "\u{00A0}".__('inventory.units.'.$unitKey));
}
public function money(int $cents): string
{
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
}
/**
* A unit cost in hundredths of a cent, e.g. "0,0123 €" or "12,50 €".
*/
public function unitCost(int $hundredths): string
{
$euros = number_format($hundredths / 10_000, 4, ',', "\u{00A0}");
$euros = preg_replace('/(,\d\d)00$/', '$1', $euros) ?? $euros;
$euros = preg_replace('/(,\d\d\d)0$/', '$1', $euros) ?? $euros;
return $euros."\u{00A0}€";
}
/**
* "24.11.2026" for "2026-11-24"; "24.11.2026 klo 14.05" for "2026-11-24 14:05".
*/
public function dateLabel(string $value): string
{
return strlen($value) > 10
? CarbonImmutable::createFromFormat('Y-m-d H:i', $value)->format('j.n.Y \k\l\o H.i')
: CarbonImmutable::createFromFormat('!Y-m-d', $value)->format('j.n.Y');
}
}
@@ -0,0 +1,212 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\UseCases\AddStockItemGroup;
use App\Modules\Inventory\Application\UseCases\ChangeStockItemGroup;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Stock item groups (nimikeryhmät, spec 19.1): adding, renaming, ordering
* with Move up / Move down and taking out of use. Management only.
*/
new class extends Component
{
public string $newName = '';
#[Locked]
public ?int $editingId = null;
public string $editingName = '';
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('inventory.manage');
}
/**
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return app(StockQueries::class)->groups();
}
public function add(AddStockItemGroup $addGroup): void
{
$this->authorize('inventory.manage');
try {
$addGroup->execute($this->newName);
} catch (InvalidStockName) {
$this->addError('newName', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('newName', __('inventory.errors.name_taken'));
return;
}
$this->message = __('inventory.groups.added', ['name' => trim($this->newName)]);
$this->newName = '';
unset($this->groups);
$this->js("document.getElementById('new-group-name')?.focus()");
}
public function startRename(int $groupId): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
$this->editingId = $group->id;
$this->editingName = $group->name;
$this->resetErrorBag();
$this->js("setTimeout(() => document.getElementById('rename-group')?.focus())");
}
public function cancelRename(): void
{
$id = $this->editingId;
$this->editingId = null;
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
}
public function rename(ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
try {
$change->rename((int) $this->editingId, $this->editingName);
} catch (InvalidStockName) {
$this->addError('editingName', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('editingName', __('inventory.errors.name_taken'));
return;
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
}
$id = $this->editingId;
$this->message = __('inventory.groups.renamed', ['name' => trim($this->editingName)]);
$this->editingId = null;
unset($this->groups);
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
}
public function move(int $groupId, string $direction, ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
$up = $direction === 'up';
try {
$moved = $change->move($groupId, $up);
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
return;
}
$this->message = __('inventory.groups.'.($moved ? ($up ? 'moved_up' : 'moved_down') : ($up ? 'first' : 'last')), ['name' => $group->name]);
unset($this->groups);
}
public function toggleActive(int $groupId, ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
try {
$change->setActive($groupId, ! $group->isActive);
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
return;
}
$this->message = __($group->isActive ? 'inventory.groups.deactivated' : 'inventory.groups.activated', ['name' => $group->name]);
unset($this->groups);
}
public function render(): mixed
{
return $this->view()->title(__('inventory.groups.title'));
}
};
?>
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.groups.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.groups.intro') }}</p>
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
</div>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
<form wire:submit="add" class="flex flex-wrap items-end gap-3" novalidate>
<div class="min-w-0 flex-1">
<x-input id="new-group-name" wire:model="newName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
</div>
<x-button submit icon="plus" :text="__('inventory.groups.add')" />
</form>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.groups.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
@foreach ($this->groups as $group)
<li wire:key="group-{{ $group->id }}" class="flex flex-wrap items-center gap-3 p-3">
@if ($editingId === $group->id)
<form wire:submit="rename" class="flex w-full flex-wrap items-end gap-2" novalidate>
<div class="min-w-0 flex-1">
<x-input id="rename-group" wire:model="editingName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
</div>
<x-button submit :text="__('inventory.groups.save')" />
<x-button wire:click="cancelRename" subtle color="black" :text="__('inventory.groups.cancel')" />
</form>
@else
<div class="min-w-0 flex-1">
<p class="font-medium break-words">{{ $group->name }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('inventory.groups.items', $group->itemCount, ['count' => $group->itemCount]) }}
@unless ($group->isActive)
· {{ __('inventory.status.inactive') }}
@endunless
</p>
</div>
<div class="flex flex-wrap gap-1">
<x-button wire:click="move({{ $group->id }}, 'up')" subtle color="black" sm icon="arrow-up" :aria-label="__('inventory.groups.up_named', ['name' => $group->name])" />
<x-button wire:click="move({{ $group->id }}, 'down')" subtle color="black" sm icon="arrow-down" :aria-label="__('inventory.groups.down_named', ['name' => $group->name])" />
<x-button id="rename-group-{{ $group->id }}" wire:click="startRename({{ $group->id }})" subtle color="black" sm icon="pencil" :text="__('inventory.groups.rename')" :aria-label="__('inventory.groups.rename_named', ['name' => $group->name])" />
<x-button
wire:click="toggleActive({{ $group->id }})"
subtle
color="black"
sm
:icon="$group->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'"
:text="$group->isActive ? __('inventory.groups.deactivate') : __('inventory.groups.activate')"
:aria-label="__($group->isActive ? 'inventory.groups.deactivate_named' : 'inventory.groups.activate_named', ['name' => $group->name])"
/>
</div>
@endif
</li>
@endforeach
</ul>
@endif
</div>
@@ -0,0 +1,169 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The stock list (spec 19.1): items with their balances, searched by name
* or code and filtered by group and "only items to order". Management also
* sees the average costs and the stock value.
*/
new class extends Component
{
use FormatsStock;
#[Url(as: 'haku', except: '')]
public string $search = '';
#[Url(as: 'ryhma', except: '')]
public string $group = '';
#[Url(as: 'tilattavat', except: false)]
public bool $onlyReorder = false;
public bool $includeInactive = false;
public function mount(): void
{
$this->authorize('inventory.view');
}
/**
* @return list<StockItemSummary>
*/
#[Computed]
public function items(): array
{
return app(StockQueries::class)->items(
$this->search,
$this->group === '' ? null : (int) $this->group,
$this->onlyReorder,
$this->includeInactive && Gate::allows('inventory.manage'),
);
}
/**
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return app(StockQueries::class)->groups(includeInactive: false);
}
public function updated(): void
{
$this->authorize('inventory.view');
unset($this->items);
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
$headers = [
['index' => 'name', 'label' => __('inventory.columns.name'), 'sortable' => false],
['index' => 'group', 'label' => __('inventory.columns.group'), 'sortable' => false],
['index' => 'balance', 'label' => __('inventory.columns.balance'), 'sortable' => false, 'align' => 'right'],
['index' => 'reorder', 'label' => __('inventory.columns.reorder_level'), 'sortable' => false, 'align' => 'right'],
['index' => 'status', 'label' => __('inventory.columns.status'), 'sortable' => false],
];
if (Gate::allows('inventory.see-value')) {
$headers[] = ['index' => 'cost', 'label' => __('inventory.columns.average_cost'), 'sortable' => false, 'align' => 'right'];
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
}
return $headers;
}
public function render(): mixed
{
return $this->view()->title(__('inventory.index.title'));
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.index.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.index.intro') }}</p>
@can('inventory.manage')
<div class="flex flex-wrap gap-3">
<x-button :href="route('inventory.items.create')" wire:navigate icon="plus" :text="__('inventory.index.new_item')" />
<x-button :href="route('inventory.groups')" wire:navigate subtle color="black" icon="folder" :text="__('inventory.index.groups')" />
</div>
@endcan
</div>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<x-input id="stock-search" wire:model.live.debounce.300ms="search" type="search" icon="magnifying-glass" :label="__('inventory.index.search')" autocomplete="off" />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="stock-group" wire:model.live="group" :label="__('inventory.index.group')" :aria-label="__('inventory.index.group')">
<option value="">{{ __('inventory.index.all_groups') }}</option>
@foreach ($this->groups as $option)
<option value="{{ $option->id }}">{{ $option->name }}</option>
@endforeach
</x-select.native>
<div class="flex flex-col justify-end gap-2">
<x-checkbox id="only-reorder" wire:model.live="onlyReorder" :label="__('inventory.index.only_reorder')" />
@can('inventory.manage')
<x-checkbox id="include-inactive" wire:model.live="includeInactive" :label="__('inventory.index.include_inactive')" />
@endcan
</div>
</div>
<p role="status" aria-live="polite" class="text-sm font-medium">
{{ trans_choice('inventory.index.count', count($this->items), ['count' => count($this->items)]) }}
</p>
@if ($this->items === [])
<p class="text-sm">{{ __('inventory.index.none') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->items">
@interact('column_name', $item)
<x-link :href="route('inventory.items.show', $item->id)" navigate class="whitespace-normal">{{ $item->name }}</x-link>
@if ($item->code !== null)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $item->code }}</span>
@endif
@endinteract
@interact('column_group', $item)
<span class="whitespace-normal">{{ $item->groupName }}</span>
@endinteract
@interact('column_balance', $item)
<span class="whitespace-nowrap">{{ $this->quantity($item->balanceMilli, $item->unit) }}</span>
@endinteract
@interact('column_reorder', $item)
<span class="whitespace-nowrap">{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</span>
@endinteract
@interact('column_status', $item)
<x-inventory.stock-status :item="$item" />
@endinteract
@interact('column_cost', $item)
<span class="whitespace-nowrap">{{ $this->unitCost($item->averageCostHundredths) }}</span>
@endinteract
@interact('column_value', $item)
<span class="whitespace-nowrap">{{ $this->money($item->valueCents) }}</span>
@endinteract
</x-table>
@can('inventory.see-value')
<p class="text-right font-semibold">{{ __('inventory.index.total_value', ['value' => $this->money(array_sum(array_map(fn ($item) => $item->valueCents, $this->items)))]) }}</p>
@endcan
@endif
</div>
@@ -0,0 +1,227 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Application\UseCases\AddStockItem;
use App\Modules\Inventory\Application\UseCases\ChangeStockItemImage;
use App\Modules\Inventory\Application\UseCases\UpdateStockItem;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
/**
* Add page (no {item}) and edit page (with {item}) of a stock item: group,
* name, unit, code, supplier, reorder level and an optional image.
* Management only.
*/
new class extends Component
{
use WithFileUploads;
public const int MAX_KILOBYTES = 12288;
#[Locked]
public ?int $itemId = null;
#[Locked]
public bool $hasImage = false;
public string $groupId = '';
public string $name = '';
public string $unit = 'piece';
public string $code = '';
public string $supplier = '';
public string $reorderLevel = '';
/**
* @var TemporaryUploadedFile|null
*/
public $image = null;
public bool $removeImage = false;
public function mount(StockQueries $stock, ?int $item = null): void
{
$this->authorize('inventory.manage');
if ($item === null) {
$this->groupId = (string) ($this->groups[0]->id ?? '');
return;
}
$summary = $stock->findItem($item) ?? abort(404);
$this->itemId = $summary->id;
$this->groupId = (string) $summary->groupId;
$this->name = $summary->name;
$this->unit = $summary->unit->value;
$this->code = (string) $summary->code;
$this->supplier = (string) $summary->supplier;
$this->reorderLevel = $summary->reorderLevelMilli === null ? '' : StockQuantity::inputValue($summary->reorderLevelMilli);
$this->hasImage = $summary->hasImage;
}
/**
* Groups in use, and the item's own group even when out of use.
*
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return array_values(array_filter(
app(StockQueries::class)->groups(),
fn (StockGroupSummary $group): bool => $group->isActive || (string) $group->id === $this->groupId,
));
}
public function save(AddStockItem $addItem, UpdateStockItem $updateItem, ChangeStockItemImage $changeImage): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
$this->validate(
[
'groupId' => ['required', 'integer'],
'unit' => ['required', 'in:'.implode(',', array_column(StockUnit::cases(), 'value'))],
'image' => ['nullable', 'file', 'image', 'mimes:jpg,jpeg,png,webp,gif', 'max:'.self::MAX_KILOBYTES],
],
[
'groupId.required' => __('inventory.errors.group'),
'groupId.integer' => __('inventory.errors.group'),
'image.file' => __('inventory.errors.image'),
'image.image' => __('inventory.errors.image'),
'image.mimes' => __('inventory.errors.image'),
'image.max' => __('inventory.errors.image_too_large', ['size' => self::MAX_KILOBYTES / 1024]),
],
);
$data = new StockItemData((int) $this->groupId, $this->name, $this->unit, $this->code, $this->supplier, $this->reorderLevel);
try {
if ($this->itemId === null) {
$this->itemId = $addItem->execute($data);
$status = __('inventory.form.created', ['name' => trim($this->name)]);
} else {
$updateItem->execute($this->itemId, $data);
$status = __('inventory.form.updated', ['name' => trim($this->name)]);
}
if ($this->image instanceof TemporaryUploadedFile) {
$changeImage->execute($this->itemId, (string) $this->image->getRealPath());
} elseif ($this->removeImage) {
$changeImage->execute($this->itemId, null);
}
} catch (InvalidStockName) {
$this->addError('name', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('name', __('inventory.errors.name_taken'));
return;
} catch (InvalidStockQuantity) {
$this->addError('reorderLevel', __('inventory.errors.reorder_level'));
return;
} catch (StockItemGroupNotFound) {
$this->addError('groupId', __('inventory.errors.group'));
return;
} catch (InvalidStockImage) {
$this->addError('image', __('inventory.errors.image'));
return;
} catch (StockItemNotFound) {
abort(404);
}
session()->flash('status', $status);
$this->redirectRoute('inventory.items.show', $this->itemId, navigate: true);
}
public function heading(): string
{
return __($this->itemId === null ? 'inventory.form.create_title' : 'inventory.form.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading());
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.form.no_groups') }} <x-link :href="route('inventory.groups')" navigate>{{ __('inventory.index.groups') }}</x-link></p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="item-group" wire:model="groupId" :label="__('inventory.form.group')" :aria-label="__('inventory.form.group')">
@foreach ($this->groups as $group)
<option value="{{ $group->id }}">{{ $group->name }}</option>
@endforeach
</x-select.native>
<x-input id="item-name" wire:model="name" :label="__('inventory.form.name')" autocomplete="off" maxlength="150" required />
<x-select.native id="item-unit" wire:model="unit" :label="__('inventory.form.unit')" :aria-label="__('inventory.form.unit')">
@foreach (StockUnit::cases() as $option)
<option value="{{ $option->value }}">{{ __('inventory.units.'.$option->value) }}</option>
@endforeach
</x-select.native>
<x-input id="item-code" wire:model="code" :label="__('inventory.form.code')" :hint="__('inventory.form.code_hint')" autocomplete="off" maxlength="150" />
<x-input id="item-supplier" wire:model="supplier" :label="__('inventory.form.supplier')" autocomplete="off" maxlength="150" />
<x-input id="item-reorder" wire:model="reorderLevel" inputmode="decimal" :label="__('inventory.form.reorder_level')" :hint="__('inventory.form.reorder_level_hint')" autocomplete="off" />
<div class="space-y-2">
<label for="item-image" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('inventory.form.image') }}</label>
<p id="item-image-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
@if ($hasImage && $itemId !== null)
<img src="{{ route('inventory.items.image', [$itemId, 'thumbnail']) }}" alt="{{ __('inventory.form.current_image') }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
<x-checkbox id="remove-image" wire:model="removeImage" :label="__('inventory.form.remove_image')" />
@endif
<input
type="file"
id="item-image"
wire:model="image"
accept="image/jpeg,image/png,image/webp,image/gif"
aria-describedby="item-image-hint @error('image') item-image-error @enderror"
@error('image') aria-invalid="true" @enderror
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
/>
@error('image')
<p id="item-image-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</div>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('inventory.form.save')" />
<x-button :href="$itemId === null ? route('inventory.index') : route('inventory.items.show', $itemId)" wire:navigate subtle color="black" :text="__('inventory.form.cancel')" />
</div>
</form>
@endif
</div>
@@ -0,0 +1,522 @@
<?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>
@@ -0,0 +1,23 @@
<?php
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:inventory.view'])
->prefix('inventory')
->name('inventory.')
->group(function () {
Route::livewire('/', 'inventory::index')->name('index');
Route::get('/items/{item}/image/{size}', ShowStockItemImage::class)
->whereNumber('item')
->whereIn('size', ['full', 'thumbnail'])
->name('items.image');
Route::middleware('can:inventory.manage')->group(function () {
Route::livewire('/groups', 'inventory::groups')->name('groups');
Route::livewire('/items/create', 'inventory::item-form')->name('items.create');
Route::livewire('/items/{item}/edit', 'inventory::item-form')->whereNumber('item')->name('items.edit');
});
Route::livewire('/items/{item}', 'inventory::item')->whereNumber('item')->name('items.show');
});