From 30132deb0eb9fc23b296002c581d6130314c5801 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Thu, 26 Nov 2026 16:18:59 +0200 Subject: [PATCH] Add stock items, groups and movements at a moving average cost Co-Authored-By: Claude Sonnet 5.5 --- .../Application/Contracts/StockItemImages.php | 26 + .../Application/Contracts/StockQueries.php | 51 ++ .../Application/DTOs/PurchaseData.php | 22 + .../Application/DTOs/StockGroupSummary.php | 15 + .../Application/DTOs/StockItemData.php | 21 + .../Application/DTOs/StockItemSummary.php | 44 ++ .../Application/DTOs/StockMovementSummary.php | 46 ++ .../Application/DTOs/StockUseData.php | 23 + .../Application/DTOs/StockUseResult.php | 19 + .../Application/UseCases/AddStockItem.php | 45 ++ .../UseCases/AddStockItemGroup.php | 40 ++ .../UseCases/ChangeStockItemGroup.php | 80 +++ .../UseCases/ChangeStockItemImage.php | 53 ++ .../UseCases/RecordStockPurchase.php | 115 ++++ .../Application/UseCases/RecordStockUse.php | 57 ++ .../UseCases/RecordStockWriteOff.php | 59 ++ .../UseCases/ReverseStockMovement.php | 70 +++ .../UseCases/SetStockItemActive.php | 33 ++ .../Application/UseCases/StockItemFields.php | 62 +++ .../Application/UseCases/UpdateStockItem.php | 46 ++ .../Contracts/StockItemGroupRepository.php | 23 + .../Domain/Contracts/StockItemRepository.php | 22 + .../Contracts/StockMovementRepository.php | 21 + .../Inventory/Domain/Entities/StockItem.php | 169 ++++++ .../Domain/Entities/StockItemGroup.php | 71 +++ .../Domain/Entities/StockMovement.php | 225 ++++++++ .../Domain/Enums/StockMovementKind.php | 19 + .../Inventory/Domain/Enums/StockUnit.php | 20 + .../Domain/Exceptions/InvalidStockCost.php | 15 + .../Domain/Exceptions/InvalidStockDay.php | 15 + .../Domain/Exceptions/InvalidStockImage.php | 15 + .../Domain/Exceptions/InvalidStockName.php | 15 + .../Exceptions/InvalidStockQuantity.php | 15 + .../Exceptions/StockItemGroupNotFound.php | 15 + .../Domain/Exceptions/StockItemInactive.php | 15 + .../Domain/Exceptions/StockItemNotFound.php | 15 + .../StockMovementAlreadyReversed.php | 15 + .../Exceptions/StockMovementNotFound.php | 15 + .../Exceptions/StockMovementNotReversible.php | 15 + .../Domain/Exceptions/StockNameTaken.php | 15 + .../Domain/Exceptions/StockReasonRequired.php | 15 + .../Exceptions/StockReversalNotAllowed.php | 15 + .../Inventory/Domain/Services/StockSearch.php | 33 ++ .../Domain/Services/StockValuation.php | 57 ++ .../Domain/ValueObjects/StockName.php | 31 ++ .../Domain/ValueObjects/StockQuantity.php | 92 +++ .../Domain/ValueObjects/StockUseTarget.php | 44 ++ .../Files/StockItemImageFiles.php | 42 ++ .../Eloquent/StockItemGroupModel.php | 47 ++ .../Persistence/Eloquent/StockItemModel.php | 60 ++ .../Eloquent/StockMovementModel.php | 74 +++ .../EloquentStockItemGroupRepository.php | 59 ++ .../EloquentStockItemRepository.php | 70 +++ .../EloquentStockMovementRepository.php | 81 +++ .../Repositories/EloquentStockQueries.php | 185 +++++++ .../Providers/InventoryServiceProvider.php | 64 +++ .../Http/Controllers/ShowStockItemImage.php | 27 + .../Livewire/Concerns/FormatsStock.php | 49 ++ .../Presentation/Livewire/⚡groups.blade.php | 212 +++++++ .../Presentation/Livewire/⚡index.blade.php | 169 ++++++ .../Livewire/⚡item-form.blade.php | 227 ++++++++ .../Presentation/Livewire/⚡item.blade.php | 522 ++++++++++++++++++ .../Inventory/Presentation/Routes/web.php | 23 + .../Infrastructure/Files/GdTaskImageFiles.php | 125 +---- .../Application/Contracts/ImageResizer.php | 21 + .../Infrastructure/Images/GdImageResizer.php | 141 +++++ .../Providers/SharedServiceProvider.php | 3 + app/View/MainMenu.php | 1 + bootstrap/providers.php | 2 + database/factories/StockItemFactory.php | 38 ++ database/factories/StockItemGroupFactory.php | 26 + .../2026_11_26_140647_create_stock_tables.php | 78 +++ lang/en/inventory.php | 189 +++++++ lang/en/layout.php | 3 + lang/fi/inventory.php | 189 +++++++ lang/fi/layout.php | 3 + .../inventory/stock-status.blade.php | 31 ++ tests/Browser/InventoryAccessibilityTest.php | 63 +++ tests/Feature/Modules/Inventory/StockTest.php | 216 ++++++++ tests/Feature/Modules/Jobs/TaskImagesTest.php | 2 +- .../Modules/Inventory/StockValuationTest.php | 77 +++ 81 files changed, 4968 insertions(+), 115 deletions(-) create mode 100644 app/Modules/Inventory/Application/Contracts/StockItemImages.php create mode 100644 app/Modules/Inventory/Application/Contracts/StockQueries.php create mode 100644 app/Modules/Inventory/Application/DTOs/PurchaseData.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockGroupSummary.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockItemData.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockItemSummary.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockMovementSummary.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockUseData.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockUseResult.php create mode 100644 app/Modules/Inventory/Application/UseCases/AddStockItem.php create mode 100644 app/Modules/Inventory/Application/UseCases/AddStockItemGroup.php create mode 100644 app/Modules/Inventory/Application/UseCases/ChangeStockItemGroup.php create mode 100644 app/Modules/Inventory/Application/UseCases/ChangeStockItemImage.php create mode 100644 app/Modules/Inventory/Application/UseCases/RecordStockPurchase.php create mode 100644 app/Modules/Inventory/Application/UseCases/RecordStockUse.php create mode 100644 app/Modules/Inventory/Application/UseCases/RecordStockWriteOff.php create mode 100644 app/Modules/Inventory/Application/UseCases/ReverseStockMovement.php create mode 100644 app/Modules/Inventory/Application/UseCases/SetStockItemActive.php create mode 100644 app/Modules/Inventory/Application/UseCases/StockItemFields.php create mode 100644 app/Modules/Inventory/Application/UseCases/UpdateStockItem.php create mode 100644 app/Modules/Inventory/Domain/Contracts/StockItemGroupRepository.php create mode 100644 app/Modules/Inventory/Domain/Contracts/StockItemRepository.php create mode 100644 app/Modules/Inventory/Domain/Contracts/StockMovementRepository.php create mode 100644 app/Modules/Inventory/Domain/Entities/StockItem.php create mode 100644 app/Modules/Inventory/Domain/Entities/StockItemGroup.php create mode 100644 app/Modules/Inventory/Domain/Entities/StockMovement.php create mode 100644 app/Modules/Inventory/Domain/Enums/StockMovementKind.php create mode 100644 app/Modules/Inventory/Domain/Enums/StockUnit.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/InvalidStockCost.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/InvalidStockDay.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/InvalidStockImage.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/InvalidStockName.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/InvalidStockQuantity.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockItemGroupNotFound.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockItemInactive.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockItemNotFound.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockMovementAlreadyReversed.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockMovementNotFound.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockMovementNotReversible.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockNameTaken.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockReasonRequired.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockReversalNotAllowed.php create mode 100644 app/Modules/Inventory/Domain/Services/StockSearch.php create mode 100644 app/Modules/Inventory/Domain/Services/StockValuation.php create mode 100644 app/Modules/Inventory/Domain/ValueObjects/StockName.php create mode 100644 app/Modules/Inventory/Domain/ValueObjects/StockQuantity.php create mode 100644 app/Modules/Inventory/Domain/ValueObjects/StockUseTarget.php create mode 100644 app/Modules/Inventory/Infrastructure/Files/StockItemImageFiles.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemGroupModel.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemModel.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockMovementModel.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemGroupRepository.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php create mode 100644 app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php create mode 100644 app/Modules/Inventory/Presentation/Http/Controllers/ShowStockItemImage.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/Concerns/FormatsStock.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/⚡groups.blade.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/⚡index.blade.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/⚡item-form.blade.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/⚡item.blade.php create mode 100644 app/Modules/Inventory/Presentation/Routes/web.php create mode 100644 app/Modules/Shared/Application/Contracts/ImageResizer.php create mode 100644 app/Modules/Shared/Infrastructure/Images/GdImageResizer.php create mode 100644 database/factories/StockItemFactory.php create mode 100644 database/factories/StockItemGroupFactory.php create mode 100644 database/migrations/2026_11_26_140647_create_stock_tables.php create mode 100644 lang/en/inventory.php create mode 100644 lang/fi/inventory.php create mode 100644 resources/views/components/inventory/stock-status.blade.php create mode 100644 tests/Browser/InventoryAccessibilityTest.php create mode 100644 tests/Feature/Modules/Inventory/StockTest.php create mode 100644 tests/Unit/Modules/Inventory/StockValuationTest.php diff --git a/app/Modules/Inventory/Application/Contracts/StockItemImages.php b/app/Modules/Inventory/Application/Contracts/StockItemImages.php new file mode 100644 index 0000000..20723a0 --- /dev/null +++ b/app/Modules/Inventory/Application/Contracts/StockItemImages.php @@ -0,0 +1,26 @@ + $paths + */ + public function delete(array $paths): void; +} diff --git a/app/Modules/Inventory/Application/Contracts/StockQueries.php b/app/Modules/Inventory/Application/Contracts/StockQueries.php new file mode 100644 index 0000000..043e998 --- /dev/null +++ b/app/Modules/Inventory/Application/Contracts/StockQueries.php @@ -0,0 +1,51 @@ + In order. + */ + public function groups(bool $includeInactive = true): array; + + /** + * Items in group order and then by name. $search matches parts of the + * name or code regardless of case and Finnish letters. + * + * @return list + */ + public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array; + + public function findItem(int $id): ?StockItemSummary; + + /** + * @param list $ids + * @return array By id. + */ + public function itemsByIds(array $ids): array; + + /** + * The item's movements, newest first, with the balance after each. + * + * @return list + */ + public function movementsOf(int $itemId, int $limit = 200): array; + + public function findMovement(int $id): ?StockMovementSummary; + + /** + * The private-disk path of the item's image or its thumbnail. + */ + public function imagePathOf(int $itemId, bool $thumbnail): ?string; +} diff --git a/app/Modules/Inventory/Application/DTOs/PurchaseData.php b/app/Modules/Inventory/Application/DTOs/PurchaseData.php new file mode 100644 index 0000000..83b9ed5 --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/PurchaseData.php @@ -0,0 +1,22 @@ +reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli; + } + + public function isNegative(): bool + { + return $this->balanceMilli < 0; + } +} diff --git a/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php b/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php new file mode 100644 index 0000000..b7f8c4f --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php @@ -0,0 +1,46 @@ +reversedByMovementId === null + && $this->kind !== StockMovementKind::Reversal + && $this->kind !== StockMovementKind::Adjustment; + } +} diff --git a/app/Modules/Inventory/Application/DTOs/StockUseData.php b/app/Modules/Inventory/Application/DTOs/StockUseData.php new file mode 100644 index 0000000..2b15f53 --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/StockUseData.php @@ -0,0 +1,23 @@ +fields->parse($data); + + return $this->transactions->run(function () use ($data, $fields): int { + $this->fields->check($data, $fields['name']); + + $item = StockItem::create($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']); + + return (int) $this->items->save($item)->id(); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/AddStockItemGroup.php b/app/Modules/Inventory/Application/UseCases/AddStockItemGroup.php new file mode 100644 index 0000000..cbab349 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/AddStockItemGroup.php @@ -0,0 +1,40 @@ +transactions->run(function () use ($name): int { + if ($this->groups->isNameTaken($name->value)) { + throw new StockNameTaken; + } + + return (int) $this->groups->save(StockItemGroup::create($name, $this->groups->nextSortOrder()))->id(); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/ChangeStockItemGroup.php b/app/Modules/Inventory/Application/UseCases/ChangeStockItemGroup.php new file mode 100644 index 0000000..e4fd8b0 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/ChangeStockItemGroup.php @@ -0,0 +1,80 @@ +transactions->run(function () use ($groupId, $name): void { + $group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound; + + if ($this->groups->isNameTaken($name->value, $groupId)) { + throw new StockNameTaken; + } + + $group->rename($name); + $this->groups->save($group); + }); + } + + /** + * @return bool False when the group already was first (up) or last. + * + * @throws StockItemGroupNotFound + */ + public function move(int $groupId, bool $up): bool + { + return $this->transactions->run(function () use ($groupId, $up): bool { + $group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound; + $neighbour = $this->groups->neighbour($group, $up); + + if ($neighbour === null) { + return false; + } + + $group->swapOrderWith($neighbour); + $this->groups->save($group); + $this->groups->save($neighbour); + + return true; + }); + } + + /** + * @throws StockItemGroupNotFound + */ + public function setActive(int $groupId, bool $active): void + { + $this->transactions->run(function () use ($groupId, $active): void { + $group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound; + $active ? $group->activate() : $group->deactivate(); + $this->groups->save($group); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/ChangeStockItemImage.php b/app/Modules/Inventory/Application/UseCases/ChangeStockItemImage.php new file mode 100644 index 0000000..20cab85 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/ChangeStockItemImage.php @@ -0,0 +1,53 @@ +items->findById($itemId) ?? throw new StockItemNotFound; + $stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId); + + /** @var list $old */ + $old = $this->transactions->run(function () use ($itemId, $stored): array { + $item = $this->items->findById($itemId) ?? throw new StockItemNotFound; + $old = array_values(array_filter([$item->imagePath(), $item->thumbnailPath()])); + + if ($stored === null) { + $item->removeImage(); + } else { + $item->setImage($stored['path'], $stored['thumbnailPath']); + } + + $this->items->save($item); + + return $old; + }); + + $this->images->delete($old); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/RecordStockPurchase.php b/app/Modules/Inventory/Application/UseCases/RecordStockPurchase.php new file mode 100644 index 0000000..f66c0e0 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/RecordStockPurchase.php @@ -0,0 +1,115 @@ +quantity); + $valueCents = $this->valueCents($data, $quantity); + $occurredOn = $this->day($data->occurredOn); + + return $this->transactions->run(function () use ($data, $quantity, $valueCents, $occurredOn, $actorUserId): int { + $item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound; + $balance = $this->movements->balanceOf($data->itemId); + + $movement = StockMovement::purchase($item, $quantity, $valueCents, $occurredOn, $this->clock->now(), $actorUserId, $data->supplier ?? $item->supplier(), $data->documentNumber); + + $item->receive($balance, $quantity->milli, $valueCents); + $this->items->save($item); + + return (int) $this->movements->add($movement)->id(); + }); + } + + /** + * @throws InvalidStockCost + */ + private function valueCents(PurchaseData $data, StockQuantity $quantity): int + { + try { + $total = Money::parse($data->totalPrice); + } catch (InvalidMoneyAmount) { + throw new InvalidStockCost; + } + + if ($total !== null) { + return $total->cents; + } + + return StockValuation::valueCents($quantity->milli, $this->unitCostHundredths($data->unitPrice)); + } + + /** + * A unit price with up to four decimals ("0,0123") in hundredths of a cent. + * + * @throws InvalidStockCost + */ + private function unitCostHundredths(string $value): int + { + $value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? ''); + + if (preg_match('/^(\d{1,7})(?:\.(\d{1,4}))?$/', $value, $matches) !== 1) { + throw new InvalidStockCost; + } + + return (int) $matches[1] * 10_000 + (int) str_pad($matches[2] ?? '', 4, '0'); + } + + /** + * @throws InvalidStockDay + */ + private function day(string $value): DateTimeImmutable + { + if ($value === '') { + return $this->clock->today(); + } + + $day = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + if ($day === false || $day->format('Y-m-d') !== $value) { + throw new InvalidStockDay; + } + + return $day; + } +} diff --git a/app/Modules/Inventory/Application/UseCases/RecordStockUse.php b/app/Modules/Inventory/Application/UseCases/RecordStockUse.php new file mode 100644 index 0000000..abbe1d4 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/RecordStockUse.php @@ -0,0 +1,57 @@ +quantity); + $target = new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $data->reason); + + return $this->transactions->run(function () use ($data, $quantity, $target, $actorUserId): StockUseResult { + $item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound; + $item->ensureUsable(); + + $movement = $this->movements->add(StockMovement::consumption($item, $quantity, $target, $this->clock->today(), $this->clock->now(), $actorUserId)); + + return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId)); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/RecordStockWriteOff.php b/app/Modules/Inventory/Application/UseCases/RecordStockWriteOff.php new file mode 100644 index 0000000..7bbd826 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/RecordStockWriteOff.php @@ -0,0 +1,59 @@ +quantity); + $reason = trim((string) $data->reason); + + if ($reason === '') { + throw new StockReasonRequired; + } + + $target = $data->taskId === null && $data->machineId === null && $data->orderLineId === null && $data->maintenanceRecordId === null + ? null + : new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $reason); + + return $this->transactions->run(function () use ($data, $quantity, $reason, $target, $actorUserId): StockUseResult { + $item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound; + + $movement = $this->movements->add(StockMovement::writeOff($item, $quantity, $reason, $this->clock->today(), $this->clock->now(), $actorUserId, $target)); + + return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId)); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/ReverseStockMovement.php b/app/Modules/Inventory/Application/UseCases/ReverseStockMovement.php new file mode 100644 index 0000000..ac02e32 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/ReverseStockMovement.php @@ -0,0 +1,70 @@ +clock->today(); + + return $this->transactions->run(function () use ($movementId, $actorUserId, $mayReverseAny, $today): int { + $original = $this->movements->findById($movementId) ?? throw new StockMovementNotFound; + + if (! $mayReverseAny && ! $original->isOwnUseOf($actorUserId, $today)) { + throw new StockReversalNotAllowed; + } + + $item = $this->items->lockById($original->itemId()) ?? throw new StockItemNotFound; + + if ($this->movements->isReversed($movementId)) { + throw new StockMovementAlreadyReversed; + } + + $reversal = StockMovement::reversalOf($original, $today, $this->clock->now(), $actorUserId); + + if ($original->kind() === StockMovementKind::Purchase) { + $item->receive($this->movements->balanceOf($item->id() ?? 0), $reversal->quantityMilli(), $reversal->valueCents()); + $this->items->save($item); + } + + return (int) $this->movements->add($reversal)->id(); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/SetStockItemActive.php b/app/Modules/Inventory/Application/UseCases/SetStockItemActive.php new file mode 100644 index 0000000..623fc8c --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/SetStockItemActive.php @@ -0,0 +1,33 @@ +transactions->run(function () use ($itemId, $active): void { + $item = $this->items->findById($itemId) ?? throw new StockItemNotFound; + $active ? $item->activate() : $item->deactivate(); + $this->items->save($item); + }); + } +} diff --git a/app/Modules/Inventory/Application/UseCases/StockItemFields.php b/app/Modules/Inventory/Application/UseCases/StockItemFields.php new file mode 100644 index 0000000..11b88cd --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/StockItemFields.php @@ -0,0 +1,62 @@ + new StockName($data->name), + 'unit' => StockUnit::tryFrom($data->unit) ?? StockUnit::Piece, + 'reorderLevelMilli' => StockQuantity::parse($data->reorderLevel)?->milli, + ]; + } + + /** + * A new item needs a group in use; an existing item may stay in its + * group after the group is taken out of use. + * + * @throws StockItemGroupNotFound + * @throws StockNameTaken + */ + public function check(StockItemData $data, StockName $name, ?int $exceptItemId = null): void + { + $group = $this->groups->findById($data->groupId); + + if ($group === null || ($exceptItemId === null && ! $group->isActive())) { + throw new StockItemGroupNotFound; + } + + if ($this->items->isNameTaken($name->value, $exceptItemId)) { + throw new StockNameTaken; + } + } +} diff --git a/app/Modules/Inventory/Application/UseCases/UpdateStockItem.php b/app/Modules/Inventory/Application/UseCases/UpdateStockItem.php new file mode 100644 index 0000000..5705d4b --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/UpdateStockItem.php @@ -0,0 +1,46 @@ +fields->parse($data); + + $this->transactions->run(function () use ($itemId, $data, $fields): void { + $item = $this->items->findById($itemId) ?? throw new StockItemNotFound; + $this->fields->check($data, $fields['name'], $itemId); + + $item->change($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']); + $this->items->save($item); + }); + } +} diff --git a/app/Modules/Inventory/Domain/Contracts/StockItemGroupRepository.php b/app/Modules/Inventory/Domain/Contracts/StockItemGroupRepository.php new file mode 100644 index 0000000..e84d70b --- /dev/null +++ b/app/Modules/Inventory/Domain/Contracts/StockItemGroupRepository.php @@ -0,0 +1,23 @@ +groupId = $groupId; + $this->name = $name; + $this->unit = $unit; + $this->code = self::text($code); + $this->supplier = self::text($supplier); + $this->reorderLevelMilli = $reorderLevelMilli; + } + + /** + * Updates the moving average cost for a purchase (or, with a negative + * quantity and value, the reversal of one) received on top of the + * given balance. + */ + public function receive(int $balanceMilli, int $quantityMilli, int $valueCents): void + { + $this->averageCostHundredths = StockValuation::averageAfterPurchase($balanceMilli, $this->averageCostHundredths, $quantityMilli, $valueCents); + } + + /** + * @throws StockItemInactive + */ + public function ensureUsable(): void + { + if (! $this->active) { + throw new StockItemInactive; + } + } + + public function setImage(string $imagePath, string $thumbnailPath): void + { + $this->imagePath = $imagePath; + $this->thumbnailPath = $thumbnailPath; + } + + public function removeImage(): void + { + $this->imagePath = null; + $this->thumbnailPath = null; + } + + public function activate(): void + { + $this->active = true; + } + + public function deactivate(): void + { + $this->active = false; + } + + public function id(): ?int + { + return $this->id; + } + + public function groupId(): int + { + return $this->groupId; + } + + public function name(): StockName + { + return $this->name; + } + + public function unit(): StockUnit + { + return $this->unit; + } + + public function code(): ?string + { + return $this->code; + } + + public function supplier(): ?string + { + return $this->supplier; + } + + public function reorderLevelMilli(): ?int + { + return $this->reorderLevelMilli; + } + + public function averageCostHundredths(): int + { + return $this->averageCostHundredths; + } + + public function imagePath(): ?string + { + return $this->imagePath; + } + + public function thumbnailPath(): ?string + { + return $this->thumbnailPath; + } + + public function isActive(): bool + { + return $this->active; + } + + private static function text(?string $value): ?string + { + $value = $value === null ? '' : trim($value); + + return $value === '' ? null : mb_substr($value, 0, 150); + } +} diff --git a/app/Modules/Inventory/Domain/Entities/StockItemGroup.php b/app/Modules/Inventory/Domain/Entities/StockItemGroup.php new file mode 100644 index 0000000..6a2393a --- /dev/null +++ b/app/Modules/Inventory/Domain/Entities/StockItemGroup.php @@ -0,0 +1,71 @@ +name = $name; + } + + public function activate(): void + { + $this->active = true; + } + + public function deactivate(): void + { + $this->active = false; + } + + public function swapOrderWith(self $other): void + { + [$this->sortOrder, $other->sortOrder] = [$other->sortOrder, $this->sortOrder]; + } + + public function id(): ?int + { + return $this->id; + } + + public function name(): StockName + { + return $this->name; + } + + public function sortOrder(): int + { + return $this->sortOrder; + } + + public function isActive(): bool + { + return $this->active; + } +} diff --git a/app/Modules/Inventory/Domain/Entities/StockMovement.php b/app/Modules/Inventory/Domain/Entities/StockMovement.php new file mode 100644 index 0000000..8f5e531 --- /dev/null +++ b/app/Modules/Inventory/Domain/Entities/StockMovement.php @@ -0,0 +1,225 @@ +id(), StockMovementKind::Purchase, $quantity->milli, + StockValuation::unitCostOf($quantity->milli, $valueCents), $valueCents, + $occurredOn, $recordedAt, $userId, null, null, self::text($supplier), self::text($documentNumber), null, null, + ); + } + + public static function consumption(StockItem $item, StockQuantity $quantity, StockUseTarget $target, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self + { + return self::outgoing(StockMovementKind::Consumption, $item, $quantity, $target, $target->reason, $occurredOn, $recordedAt, $userId); + } + + /** + * @throws StockReasonRequired + */ + public static function writeOff(StockItem $item, StockQuantity $quantity, string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?StockUseTarget $target = null): self + { + $reason = self::text($reason) ?? throw new StockReasonRequired; + + return self::outgoing(StockMovementKind::WriteOff, $item, $quantity, $target, $reason, $occurredOn, $recordedAt, $userId); + } + + /** + * A stock count's correction: a signed difference at the average cost. + */ + public static function adjustment(StockItem $item, int $differenceMilli, int $inventoryCountId, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self + { + $cost = $item->averageCostHundredths(); + + return new self( + null, (int) $item->id(), StockMovementKind::Adjustment, $differenceMilli, $cost, + StockValuation::valueCents($differenceMilli, $cost), + $occurredOn, $recordedAt, $userId, null, null, null, null, $inventoryCountId, null, + ); + } + + /** + * @throws StockMovementNotReversible + */ + public static function reversalOf(self $original, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self + { + if (! $original->isReversible()) { + throw new StockMovementNotReversible; + } + + return new self( + null, $original->itemId, StockMovementKind::Reversal, -$original->quantityMilli, + $original->unitCostHundredths, -$original->valueCents, + $occurredOn, $recordedAt, $userId, $original->target, $original->reason, null, null, null, $original->id, + ); + } + + public static function reconstitute( + int $id, + int $itemId, + StockMovementKind $kind, + int $quantityMilli, + int $unitCostHundredths, + int $valueCents, + DateTimeImmutable $occurredOn, + DateTimeImmutable $recordedAt, + int $userId, + ?StockUseTarget $target, + ?string $reason, + ?string $supplier, + ?string $documentNumber, + ?int $inventoryCountId, + ?int $reversesMovementId, + ): self { + return new self($id, $itemId, $kind, $quantityMilli, $unitCostHundredths, $valueCents, $occurredOn, $recordedAt, $userId, $target, $reason, $supplier, $documentNumber, $inventoryCountId, $reversesMovementId); + } + + public function isReversible(): bool + { + return $this->kind !== StockMovementKind::Reversal && $this->kind !== StockMovementKind::Adjustment; + } + + /** + * Whether the user may reverse this movement without the right to + * correct anyone's: their own use, on the day it was recorded. + */ + public function isOwnUseOf(int $userId, DateTimeImmutable $today): bool + { + return $this->kind === StockMovementKind::Consumption + && $this->userId === $userId + && $this->occurredOn->format('Y-m-d') === $today->format('Y-m-d'); + } + + public function id(): ?int + { + return $this->id; + } + + public function itemId(): int + { + return $this->itemId; + } + + public function kind(): StockMovementKind + { + return $this->kind; + } + + public function quantityMilli(): int + { + return $this->quantityMilli; + } + + public function unitCostHundredths(): int + { + return $this->unitCostHundredths; + } + + public function valueCents(): int + { + return $this->valueCents; + } + + public function occurredOn(): DateTimeImmutable + { + return $this->occurredOn; + } + + public function recordedAt(): DateTimeImmutable + { + return $this->recordedAt; + } + + public function userId(): int + { + return $this->userId; + } + + public function target(): ?StockUseTarget + { + return $this->target; + } + + public function reason(): ?string + { + return $this->reason; + } + + public function supplier(): ?string + { + return $this->supplier; + } + + public function documentNumber(): ?string + { + return $this->documentNumber; + } + + public function inventoryCountId(): ?int + { + return $this->inventoryCountId; + } + + public function reversesMovementId(): ?int + { + return $this->reversesMovementId; + } + + private static function outgoing(StockMovementKind $kind, StockItem $item, StockQuantity $quantity, ?StockUseTarget $target, ?string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self + { + $cost = $item->averageCostHundredths(); + + return new self( + null, (int) $item->id(), $kind, -$quantity->milli, $cost, + StockValuation::valueCents(-$quantity->milli, $cost), + $occurredOn, $recordedAt, $userId, $target, $reason, null, null, null, null, + ); + } + + private static function text(?string $value): ?string + { + $value = $value === null ? '' : trim($value); + + return $value === '' ? null : mb_substr($value, 0, 255); + } +} diff --git a/app/Modules/Inventory/Domain/Enums/StockMovementKind.php b/app/Modules/Inventory/Domain/Enums/StockMovementKind.php new file mode 100644 index 0000000..86742e0 --- /dev/null +++ b/app/Modules/Inventory/Domain/Enums/StockMovementKind.php @@ -0,0 +1,19 @@ + 'a', 'ä' => 'a', 'ö' => 'o', 'é' => 'e', 'ü' => 'u']); + } +} diff --git a/app/Modules/Inventory/Domain/Services/StockValuation.php b/app/Modules/Inventory/Domain/Services/StockValuation.php new file mode 100644 index 0000000..dfbb302 --- /dev/null +++ b/app/Modules/Inventory/Domain/Services/StockValuation.php @@ -0,0 +1,57 @@ + self::MAX_LENGTH) { + throw new InvalidStockName; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Inventory/Domain/ValueObjects/StockQuantity.php b/app/Modules/Inventory/Domain/ValueObjects/StockQuantity.php new file mode 100644 index 0000000..79cf4d5 --- /dev/null +++ b/app/Modules/Inventory/Domain/ValueObjects/StockQuantity.php @@ -0,0 +1,92 @@ + self::MAX_MILLI) { + throw new InvalidStockQuantity; + } + + return new self($milli); + } + + /** + * A quantity greater than zero, as typed in. + * + * @throws InvalidStockQuantity + */ + public static function parsePositive(string $value): self + { + $quantity = self::parse($value); + + if ($quantity === null || $quantity->milli <= 0) { + throw new InvalidStockQuantity; + } + + return $quantity; + } + + /** + * A quantity of zero or more as typed in, or null for an empty value. + * + * @throws InvalidStockQuantity + */ + public static function parse(string $value): ?self + { + $value = preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? ''; + $value = str_replace(',', '.', $value); + + if ($value === '') { + return null; + } + + if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) { + throw new InvalidStockQuantity; + } + + return new self((int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0')); + } + + public function negated(): self + { + return new self(-$this->milli); + } + + /** + * Finnish format without trailing zeros: "2,5", "-1", "1 200". + */ + public static function format(int $milli): string + { + $whole = intdiv(abs($milli), 1000); + $fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0'); + + return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction); + } + + /** + * The value for an input field: "2,5" without thousands separators. + */ + public static function inputValue(int $milli): string + { + return str_replace("\u{00A0}", '', self::format($milli)); + } +} diff --git a/app/Modules/Inventory/Domain/ValueObjects/StockUseTarget.php b/app/Modules/Inventory/Domain/ValueObjects/StockUseTarget.php new file mode 100644 index 0000000..4aa4518 --- /dev/null +++ b/app/Modules/Inventory/Domain/ValueObjects/StockUseTarget.php @@ -0,0 +1,44 @@ +reason = $reason === '' || $reason === null ? null : mb_substr($reason, 0, 255); + + if ($this->reason === null && $taskId === null && $machineId === null && $orderLineId === null && $maintenanceRecordId === null) { + throw new StockReasonRequired; + } + } + + /** + * @throws StockReasonRequired + */ + public static function reason(?string $reason): self + { + return new self(reason: $reason); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Files/StockItemImageFiles.php b/app/Modules/Inventory/Infrastructure/Files/StockItemImageFiles.php new file mode 100644 index 0000000..a60c6d9 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Files/StockItemImageFiles.php @@ -0,0 +1,42 @@ +resizer->jpegVersions($uploadedFilePath, [self::MAX_SIZE, self::THUMBNAIL_SIZE]) ?? throw new InvalidStockImage; + $name = 'stock-items/'.$itemId.'/'.Str::uuid()->toString(); + + Storage::disk(self::DISK)->put($name.'.jpg', $versions[0]['bytes']); + Storage::disk(self::DISK)->put($name.'-thumb.jpg', $versions[1]['bytes']); + + return ['path' => $name.'.jpg', 'thumbnailPath' => $name.'-thumb.jpg']; + } + + public function delete(array $paths): void + { + if ($paths !== []) { + Storage::disk(self::DISK)->delete($paths); + } + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemGroupModel.php b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemGroupModel.php new file mode 100644 index 0000000..98474b4 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemGroupModel.php @@ -0,0 +1,47 @@ + */ + use HasFactory; + + /** + * @return HasMany + */ + public function items(): HasMany + { + return $this->hasMany(StockItemModel::class, 'stock_item_group_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'sort_order' => 'integer', + 'is_active' => 'boolean', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemModel.php b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemModel.php new file mode 100644 index 0000000..4e1e08a --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockItemModel.php @@ -0,0 +1,60 @@ + */ + use HasFactory; + + /** + * @return BelongsTo + */ + public function group(): BelongsTo + { + return $this->belongsTo(StockItemGroupModel::class, 'stock_item_group_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'stock_item_group_id' => 'integer', + 'unit' => StockUnit::class, + 'reorder_level_milli' => 'integer', + 'average_cost_hundredths' => 'integer', + 'is_active' => 'boolean', + 'balance_milli' => 'integer', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockMovementModel.php b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockMovementModel.php new file mode 100644 index 0000000..106bd7a --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/StockMovementModel.php @@ -0,0 +1,74 @@ + + */ + public function reversal(): HasOne + { + return $this->hasOne(StockMovementModel::class, 'reverses_movement_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'stock_item_id' => 'integer', + 'kind' => StockMovementKind::class, + 'quantity_milli' => 'integer', + 'unit_cost_hundredths' => 'integer', + 'value_cents' => 'integer', + 'occurred_on' => 'immutable_date', + 'recorded_at' => 'immutable_datetime', + 'user_id' => 'integer', + 'task_id' => 'integer', + 'customer_job_id' => 'integer', + 'machine_id' => 'integer', + 'quick_sale_order_line_id' => 'integer', + 'maintenance_record_id' => 'integer', + 'inventory_count_id' => 'integer', + 'reverses_movement_id' => 'integer', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemGroupRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemGroupRepository.php new file mode 100644 index 0000000..51dc1cc --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemGroupRepository.php @@ -0,0 +1,59 @@ +find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(StockItemGroup $group): StockItemGroup + { + $model = $group->id() === null ? new StockItemGroupModel : StockItemGroupModel::query()->findOrFail($group->id()); + + $model->fill([ + 'name' => $group->name()->value, + 'sort_order' => $group->sortOrder(), + 'is_active' => $group->isActive(), + ])->save(); + + return $this->toEntity($model); + } + + public function isNameTaken(string $name, ?int $exceptId = null): bool + { + return StockItemGroupModel::query() + ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)]) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + + public function nextSortOrder(): int + { + return (int) StockItemGroupModel::query()->max('sort_order') + 1; + } + + public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup + { + $model = StockItemGroupModel::query() + ->where('sort_order', $up ? '<' : '>', $group->sortOrder()) + ->orderBy('sort_order', $up ? 'desc' : 'asc') + ->first(); + + return $model === null ? null : $this->toEntity($model); + } + + private function toEntity(StockItemGroupModel $model): StockItemGroup + { + return StockItemGroup::reconstitute($model->id, new StockName($model->name), $model->sort_order, $model->is_active); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php new file mode 100644 index 0000000..c819657 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php @@ -0,0 +1,70 @@ +find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function lockById(int $id): ?StockItem + { + $model = StockItemModel::query()->lockForUpdate()->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(StockItem $item): StockItem + { + $model = $item->id() === null ? new StockItemModel : StockItemModel::query()->findOrFail($item->id()); + + $model->fill([ + 'stock_item_group_id' => $item->groupId(), + 'name' => $item->name()->value, + 'unit' => $item->unit(), + 'code' => $item->code(), + 'supplier' => $item->supplier(), + 'reorder_level_milli' => $item->reorderLevelMilli(), + 'average_cost_hundredths' => $item->averageCostHundredths(), + 'image_path' => $item->imagePath(), + 'thumbnail_path' => $item->thumbnailPath(), + 'is_active' => $item->isActive(), + ])->save(); + + return $this->toEntity($model); + } + + public function isNameTaken(string $name, ?int $exceptId = null): bool + { + return StockItemModel::query() + ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)]) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + + private function toEntity(StockItemModel $model): StockItem + { + return StockItem::reconstitute( + $model->id, + $model->stock_item_group_id, + new StockName($model->name), + $model->unit, + $model->code, + $model->supplier, + $model->reorder_level_milli, + $model->average_cost_hundredths, + $model->image_path, + $model->thumbnail_path, + $model->is_active, + ); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php new file mode 100644 index 0000000..de99e73 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php @@ -0,0 +1,81 @@ +target(); + + $model = StockMovementModel::query()->create([ + 'stock_item_id' => $movement->itemId(), + 'kind' => $movement->kind(), + 'quantity_milli' => $movement->quantityMilli(), + 'unit_cost_hundredths' => $movement->unitCostHundredths(), + 'value_cents' => $movement->valueCents(), + 'occurred_on' => $movement->occurredOn()->format('Y-m-d'), + 'recorded_at' => $movement->recordedAt()->format('Y-m-d H:i:s'), + 'user_id' => $movement->userId(), + 'task_id' => $target?->taskId, + 'customer_job_id' => $target?->jobId, + 'machine_id' => $target?->machineId, + 'quick_sale_order_line_id' => $target?->orderLineId, + 'maintenance_record_id' => $target?->maintenanceRecordId, + 'inventory_count_id' => $movement->inventoryCountId(), + 'reverses_movement_id' => $movement->reversesMovementId(), + 'reason' => $movement->reason(), + 'supplier' => $movement->supplier(), + 'document_number' => $movement->documentNumber(), + ]); + + return $this->toEntity($model); + } + + public function findById(int $id): ?StockMovement + { + $model = StockMovementModel::query()->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function isReversed(int $movementId): bool + { + return StockMovementModel::query()->where('reverses_movement_id', $movementId)->exists(); + } + + public function balanceOf(int $itemId): int + { + return (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli'); + } + + private function toEntity(StockMovementModel $model): StockMovement + { + $hasTarget = $model->task_id !== null || $model->machine_id !== null || $model->quick_sale_order_line_id !== null + || $model->maintenance_record_id !== null || ($model->reason !== null && $model->inventory_count_id === null); + + return StockMovement::reconstitute( + $model->id, + $model->stock_item_id, + $model->kind, + $model->quantity_milli, + $model->unit_cost_hundredths, + $model->value_cents, + DateTimeImmutable::createFromInterface($model->occurred_on), + DateTimeImmutable::createFromInterface($model->recorded_at), + $model->user_id, + $hasTarget ? new StockUseTarget($model->task_id, $model->customer_job_id, $model->machine_id, $model->quick_sale_order_line_id, $model->maintenance_record_id, $model->reason) : null, + $model->reason, + $model->supplier, + $model->document_number, + $model->inventory_count_id, + $model->reverses_movement_id, + ); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php new file mode 100644 index 0000000..7acbc26 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php @@ -0,0 +1,185 @@ +when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true)) + ->withCount('items') + ->orderBy('sort_order') + ->get() + ->map(fn (StockItemGroupModel $model): StockGroupSummary => new StockGroupSummary($model->id, $model->name, $model->is_active, (int) $model->getAttribute('items_count'))) + ->values() + ->all(); + } + + public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array + { + $search = trim((string) $search); + + return $this->itemQuery() + ->when($groupId !== null, fn (Builder $query) => $query->where('stock_items.stock_item_group_id', $groupId)) + ->when(! $includeInactive, fn (Builder $query) => $query->where('stock_items.is_active', true)) + ->get() + ->filter(fn (StockItemModel $model): bool => $search === '' || StockSearch::matches($search, $model->name, $model->code)) + ->map(fn (StockItemModel $model): StockItemSummary => $this->toSummary($model)) + ->filter(fn (StockItemSummary $item): bool => ! $onlyReorder || $item->needsReorder()) + ->values() + ->all(); + } + + public function findItem(int $id): ?StockItemSummary + { + $model = $this->itemQuery()->where('stock_items.id', $id)->first(); + + return $model === null ? null : $this->toSummary($model); + } + + public function itemsByIds(array $ids): array + { + if ($ids === []) { + return []; + } + + return $this->itemQuery() + ->whereIn('stock_items.id', $ids) + ->get() + ->mapWithKeys(fn (StockItemModel $model): array => [$model->id => $this->toSummary($model)]) + ->all(); + } + + public function movementsOf(int $itemId, int $limit = 200): array + { + $models = StockMovementModel::query() + ->with('reversal:id,reverses_movement_id') + ->where('stock_item_id', $itemId) + ->orderByDesc('id') + ->limit($limit) + ->get(); + + $balance = (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli'); + + return $this->summaries($models, $balance); + } + + public function findMovement(int $id): ?StockMovementSummary + { + $model = StockMovementModel::query()->with('reversal:id,reverses_movement_id')->find($id); + + if ($model === null) { + return null; + } + + $balance = (int) StockMovementModel::query() + ->where('stock_item_id', $model->stock_item_id) + ->where('id', '<=', $model->id) + ->sum('quantity_milli'); + + return $this->summaries(collect([$model]), $balance)[0]; + } + + public function imagePathOf(int $itemId, bool $thumbnail): ?string + { + $model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']); + + return $thumbnail ? $model?->thumbnail_path : $model?->image_path; + } + + /** + * @return Builder + */ + private function itemQuery(): Builder + { + return StockItemModel::query() + ->join('stock_item_groups', 'stock_item_groups.id', '=', 'stock_items.stock_item_group_id') + ->select('stock_items.*') + ->addSelect('stock_item_groups.name as group_name') + ->selectSub( + StockMovementModel::query()->selectRaw('COALESCE(SUM(quantity_milli), 0)')->whereColumn('stock_movements.stock_item_id', 'stock_items.id'), + 'balance_milli', + ) + ->orderBy('stock_item_groups.sort_order') + ->orderBy('stock_items.name'); + } + + private function toSummary(StockItemModel $model): StockItemSummary + { + $balance = (int) $model->getAttribute('balance_milli'); + + return new StockItemSummary( + id: $model->id, + groupId: $model->stock_item_group_id, + groupName: (string) $model->getAttribute('group_name'), + name: $model->name, + unit: $model->unit, + code: $model->code, + supplier: $model->supplier, + reorderLevelMilli: $model->reorder_level_milli, + balanceMilli: $balance, + averageCostHundredths: $model->average_cost_hundredths, + valueCents: StockValuation::valueCents($balance, $model->average_cost_hundredths), + hasImage: $model->thumbnail_path !== null, + isActive: $model->is_active, + ); + } + + /** + * @param Collection $models Newest first. + * @param int $balance The balance after the newest of them. + * @return list + */ + private function summaries(Collection $models, int $balance): array + { + $names = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); + $summaries = []; + + foreach ($models as $model) { + $summaries[] = new StockMovementSummary( + id: $model->id, + itemId: $model->stock_item_id, + kind: $model->kind, + quantityMilli: $model->quantity_milli, + balanceAfterMilli: $balance, + valueCents: $model->value_cents, + occurredOn: $model->occurred_on->format('Y-m-d'), + recordedAt: Carbon::instance($model->recorded_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'), + userId: $model->user_id, + userName: $names[$model->user_id] ?? '', + taskId: $model->task_id, + jobId: $model->customer_job_id, + machineId: $model->machine_id, + orderLineId: $model->quick_sale_order_line_id, + maintenanceRecordId: $model->maintenance_record_id, + inventoryCountId: $model->inventory_count_id, + reason: $model->reason, + supplier: $model->supplier, + documentNumber: $model->document_number, + reversesMovementId: $model->reverses_movement_id, + reversedByMovementId: $model->reversal?->id, + ); + + $balance -= $model->quantity_milli; + } + + return $summaries; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php new file mode 100644 index 0000000..93159b5 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php @@ -0,0 +1,64 @@ + + */ + public array $bindings = [ + StockItemGroupRepository::class => EloquentStockItemGroupRepository::class, + StockItemRepository::class => EloquentStockItemRepository::class, + StockMovementRepository::class => EloquentStockMovementRepository::class, + StockQueries::class => EloquentStockQueries::class, + StockItemImages::class => StockItemImageFiles::class, + ]; + + public function boot(): void + { + $presentationPath = dirname(__DIR__, 2).'/Presentation'; + + Livewire::addNamespace('inventory', viewPath: $presentationPath.'/Livewire'); + + if (! $this->app->routesAreCached()) { + $this->loadRoutesFrom($presentationPath.'/Routes/web.php'); + } + + $staff = fn (User $user): bool => $user->role !== Role::Subcontractor; + $managers = fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true); + + Gate::define('inventory.view', $staff); + Gate::define('inventory.record-use', $staff); + Gate::define('inventory.count', $staff); + Gate::define('inventory.manage', $managers); + Gate::define('inventory.manage-counts', $managers); + Gate::define('inventory.reverse-any', $managers); + Gate::define('inventory.see-value', $managers); + + // The menu shows stock pages only when a service unit uses stock (spec 19). + Gate::define('inventory.menu', fn (User $user): bool => $staff($user) && app(CatalogQueries::class)->stockServiceUnitIds() !== []); + } +} diff --git a/app/Modules/Inventory/Presentation/Http/Controllers/ShowStockItemImage.php b/app/Modules/Inventory/Presentation/Http/Controllers/ShowStockItemImage.php new file mode 100644 index 0000000..a53553c --- /dev/null +++ b/app/Modules/Inventory/Presentation/Http/Controllers/ShowStockItemImage.php @@ -0,0 +1,27 @@ +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']); + } +} diff --git a/app/Modules/Inventory/Presentation/Livewire/Concerns/FormatsStock.php b/app/Modules/Inventory/Presentation/Livewire/Concerns/FormatsStock.php new file mode 100644 index 0000000..7fb9e82 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/Concerns/FormatsStock.php @@ -0,0 +1,49 @@ +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'); + } +} diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡groups.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡groups.blade.php new file mode 100644 index 0000000..2cd4263 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡groups.blade.php @@ -0,0 +1,212 @@ +authorize('inventory.manage'); + } + + /** + * @return list + */ + #[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')); + } +}; +?> + +
+
+

{{ __('inventory.groups.title') }}

+

{{ __('inventory.groups.intro') }}

+

{{ __('inventory.groups.back') }}

+
+ +

{{ $message }}

+ +
+
+ +
+ + + + @if ($this->groups === []) +

{{ __('inventory.groups.none') }}

+ @else +
    + @foreach ($this->groups as $group) +
  • + @if ($editingId === $group->id) +
    +
    + +
    + + + + @else +
    +

    {{ $group->name }}

    +

    + {{ trans_choice('inventory.groups.items', $group->itemCount, ['count' => $group->itemCount]) }} + @unless ($group->isActive) + · {{ __('inventory.status.inactive') }} + @endunless +

    +
    +
    + + + + +
    + @endif +
  • + @endforeach +
+ @endif +
diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡index.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..64335bb --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,169 @@ +authorize('inventory.view'); + } + + /** + * @return list + */ + #[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 + */ + #[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 + */ + 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')); + } +}; +?> + +
+
+

{{ __('inventory.index.title') }}

+

{{ __('inventory.index.intro') }}

+ @can('inventory.manage') +
+ + +
+ @endcan +
+ +
+ + + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->groups as $option) + + @endforeach + + +
+ + @can('inventory.manage') + + @endcan +
+
+ +

+ {{ trans_choice('inventory.index.count', count($this->items), ['count' => count($this->items)]) }} +

+ + @if ($this->items === []) +

{{ __('inventory.index.none') }}

+ @else + + @interact('column_name', $item) + {{ $item->name }} + @if ($item->code !== null) + {{ $item->code }} + @endif + @endinteract + + @interact('column_group', $item) + {{ $item->groupName }} + @endinteract + + @interact('column_balance', $item) + {{ $this->quantity($item->balanceMilli, $item->unit) }} + @endinteract + + @interact('column_reorder', $item) + {{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }} + @endinteract + + @interact('column_status', $item) + + @endinteract + + @interact('column_cost', $item) + {{ $this->unitCost($item->averageCostHundredths) }} + @endinteract + + @interact('column_value', $item) + {{ $this->money($item->valueCents) }} + @endinteract + + + @can('inventory.see-value') +

{{ __('inventory.index.total_value', ['value' => $this->money(array_sum(array_map(fn ($item) => $item->valueCents, $this->items)))]) }}

+ @endcan + @endif +
diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡item-form.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡item-form.blade.php new file mode 100644 index 0000000..d7e903f --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡item-form.blade.php @@ -0,0 +1,227 @@ +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 + */ + #[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()); + } +}; +?> + +
+

{{ $this->heading() }}

+ + @if ($this->groups === []) +

{{ __('inventory.form.no_groups') }} {{ __('inventory.index.groups') }}

+ @else +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + @foreach ($this->groups as $group) + + @endforeach + + + + + + @foreach (StockUnit::cases() as $option) + + @endforeach + + + + + + + + +
+ +

{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}

+ @if ($hasImage && $itemId !== null) + {{ __('inventory.form.current_image') }} + + @endif + + @error('image') +

{{ $message }}

+ @enderror +
+ +
+ + +
+ + @endif +
diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡item.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡item.blade.php new file mode 100644 index 0000000..04abb78 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡item.blade.php @@ -0,0 +1,522 @@ +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 + */ + #[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 + */ + 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); + } +}; +?> + +
+ @php($item = $this->item) + +
+ @if ($item->hasImage) + {{ __('inventory.item.image_alt', ['name' => $item->name]) }} + @endif +
+

{{ __('inventory.groups.back') }}

+

{{ $item->name }}

+ + @can('inventory.manage') +
+ + +
+ @endcan +
+
+ +

{{ $message }}

+ +
+

{{ __('inventory.item.details') }}

+
+
+
{{ __('inventory.item.balance') }}
+
{{ $this->quantity($item->balanceMilli, $item->unit) }}
+
+
+
{{ __('inventory.columns.group') }}
+
{{ $item->groupName }}
+
+
+
{{ __('inventory.columns.reorder_level') }}
+
{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}
+
+
+
{{ __('inventory.form.code') }}
+
{{ $item->code ?? '–' }}
+
+
+
{{ __('inventory.form.supplier') }}
+
{{ $item->supplier ?? '–' }}
+
+ @can('inventory.see-value') +
+
{{ __('inventory.columns.average_cost') }}
+
{{ $this->unitCost($item->averageCostHundredths) }} / {{ __('inventory.units.'.$item->unit->value) }}
+
+
+
{{ __('inventory.columns.value') }}
+
{{ $this->money($item->valueCents) }}
+
+ @endcan +
+ @if ($item->isNegative()) +

+

+ @endif +
+ + @php($unitLabel = __('inventory.units.'.$item->unit->value)) + +
+ @can('inventory.manage') +
+

{{ __('inventory.purchase.title') }}

+

{{ __('inventory.purchase.intro') }}

+
+ + + + + + + + +
+ +
+

{{ __('inventory.write_off.title') }}

+
+ + + + +
+ @endcan + + @if ($item->isActive) + @can('inventory.record-use') +
+

{{ __('inventory.use.title') }}

+

{{ __('inventory.use.intro') }}

+
+ + + + +
+ @endcan + @else +

{{ __('inventory.item.inactive_note') }}

+ @endif +
+ +
+

{{ __('inventory.item.history') }}

+ + @if ($this->movements === []) +

{{ __('inventory.item.history_none') }}

+ @else + @if (count($this->movements) >= $this::HISTORY_LIMIT) +

{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}

+ @endif + + + @interact('column_time', $movement) + {{ $this->dateLabel($movement->recordedAt) }} + @if ($movement->occurredOn !== substr($movement->recordedAt, 0, 10)) + {{ $this->dateLabel($movement->occurredOn) }} + @endif + @endinteract + + @interact('column_kind', $movement) + {{ __('inventory.kinds.'.$movement->kind->value) }} + @if ($movement->reversedByMovementId !== null) + {{ __('inventory.item.reversed_by', ['number' => $movement->reversedByMovementId]) }} + @endif + @endinteract + + @interact('column_quantity', $movement) + {{ ($movement->quantityMilli > 0 ? '+' : '').$this->quantity($movement->quantityMilli) }} + @endinteract + + @interact('column_balance', $movement) + {{ $this->quantity($movement->balanceAfterMilli) }} + @endinteract + + @interact('column_user', $movement) + {{ $movement->userName }} + @endinteract + + @interact('column_target', $movement) + {{ $this->targetText($movement) }} + @endinteract + + @interact('column_value', $movement) + {{ $this->money($movement->valueCents) }} + @endinteract + + @interact('column_actions', $movement) + @if ($this->mayReverse($movement)) + + @endif + @endinteract + + @endif +
+ + + @php($reverseMovement = $reverseMovementId === null ? null : collect($this->movements)->firstWhere('id', $reverseMovementId)) + @if ($reverseMovement !== null) +

{{ __('inventory.item.reverse_text', ['kind' => __('inventory.kinds.'.$reverseMovement->kind->value), 'quantity' => $this->quantity($reverseMovement->quantityMilli, $item->unit)]) }}

+ @endif + + + + +
+
diff --git a/app/Modules/Inventory/Presentation/Routes/web.php b/app/Modules/Inventory/Presentation/Routes/web.php new file mode 100644 index 0000000..f3ab17b --- /dev/null +++ b/app/Modules/Inventory/Presentation/Routes/web.php @@ -0,0 +1,23 @@ +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'); + }); diff --git a/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php b/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php index 4121913..6805745 100644 --- a/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php +++ b/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php @@ -5,15 +5,13 @@ namespace App\Modules\Jobs\Infrastructure\Files; use App\Modules\Jobs\Application\Contracts\TaskImageFiles; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage; use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage; -use GdImage; +use App\Modules\Shared\Application\Contracts\ImageResizer; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; /** - * Task image files on the private local disk, made with GD: the image is - * turned upright by its EXIF orientation, scaled down and saved again as a - * JPEG, which leaves out all metadata (such as the location) and anything - * else embedded in the upload. + * Task image files on the private local disk: the image turned upright, + * scaled down and saved again as a JPEG without metadata, and a thumbnail. */ class GdTaskImageFiles implements TaskImageFiles { @@ -23,31 +21,20 @@ class GdTaskImageFiles implements TaskImageFiles public const int THUMBNAIL_SIZE = 400; - /** - * Larger images would not fit in memory when decoded. - */ - private const int MAX_PIXELS = 50_000_000; - - private const int QUALITY = 82; + public function __construct(private ImageResizer $resizer) {} public function store(string $uploadedFilePath, int $taskId): StoredTaskImage { - $image = $this->upright($this->read($uploadedFilePath), $uploadedFilePath); + $versions = $this->resizer->jpegVersions($uploadedFilePath, [self::MAX_SIZE, self::THUMBNAIL_SIZE]) ?? throw new InvalidTaskImage; + [$full, $thumbnail] = $versions; - try { - $full = $this->scaled($image, self::MAX_SIZE); - $thumbnail = $this->scaled($image, self::THUMBNAIL_SIZE); + $name = 'task-images/'.$taskId.'/'.Str::uuid()->toString(); + $stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', $full['width'], $full['height']); - $name = 'task-images/'.$taskId.'/'.Str::uuid()->toString(); - $stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', imagesx($full), imagesy($full)); + Storage::disk(self::DISK)->put($stored->path, $full['bytes']); + Storage::disk(self::DISK)->put($stored->thumbnailPath, $thumbnail['bytes']); - Storage::disk(self::DISK)->put($stored->path, $this->jpeg($full)); - Storage::disk(self::DISK)->put($stored->thumbnailPath, $this->jpeg($thumbnail)); - - return $stored; - } finally { - imagedestroy($image); - } + return $stored; } public function delete(array $paths): void @@ -56,94 +43,4 @@ class GdTaskImageFiles implements TaskImageFiles Storage::disk(self::DISK)->delete($paths); } } - - /** - * @throws InvalidTaskImage - */ - private function read(string $path): GdImage - { - $info = @getimagesize($path); - - if ($info === false || $info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) { - throw new InvalidTaskImage; - } - - $image = match ($info[2]) { - IMAGETYPE_JPEG => @imagecreatefromjpeg($path), - IMAGETYPE_PNG => @imagecreatefrompng($path), - IMAGETYPE_GIF => @imagecreatefromgif($path), - IMAGETYPE_WEBP => @imagecreatefromwebp($path), - default => false, - }; - - if ($image === false) { - throw new InvalidTaskImage; - } - - // Transparent parts become white, as JPEG has no transparency. - $flat = imagecreatetruecolor(imagesx($image), imagesy($image)); - imagefill($flat, 0, 0, (int) imagecolorallocate($flat, 255, 255, 255)); - imagecopy($flat, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); - imagedestroy($image); - - return $flat; - } - - /** - * Phone cameras save photos sideways and tell the right way up in EXIF. - */ - private function upright(GdImage $image, string $path): GdImage - { - $exif = function_exists('exif_read_data') ? @exif_read_data($path) : false; - $orientation = is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1; - - $rotated = match ($orientation) { - 3 => imagerotate($image, 180, 0), - 5, 6 => imagerotate($image, -90, 0), - 7, 8 => imagerotate($image, 90, 0), - default => $image, - }; - - if ($rotated === false) { - return $image; - } - - if (in_array($orientation, [2, 5, 7], true)) { - imageflip($rotated, IMG_FLIP_HORIZONTAL); - } elseif ($orientation === 4) { - imageflip($rotated, IMG_FLIP_VERTICAL); - } - - if ($rotated !== $image) { - imagedestroy($image); - } - - return $rotated; - } - - /** - * A copy whose longer side is at most the given size. - */ - private function scaled(GdImage $image, int $maxSize): GdImage - { - $width = imagesx($image); - $height = imagesy($image); - $ratio = min(1, $maxSize / max($width, $height)); - $newWidth = max(1, (int) round($width * $ratio)); - $newHeight = max(1, (int) round($height * $ratio)); - - $copy = imagecreatetruecolor($newWidth, $newHeight); - imagecopyresampled($copy, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); - - return $copy; - } - - private function jpeg(GdImage $image): string - { - ob_start(); - imagejpeg($image, null, self::QUALITY); - imagedestroy($image); - - return (string) ob_get_clean(); - } } diff --git a/app/Modules/Shared/Application/Contracts/ImageResizer.php b/app/Modules/Shared/Application/Contracts/ImageResizer.php new file mode 100644 index 0000000..bf11f03 --- /dev/null +++ b/app/Modules/Shared/Application/Contracts/ImageResizer.php @@ -0,0 +1,21 @@ + $maxSizes + * @return list|null + */ + public function jpegVersions(string $path, array $maxSizes): ?array; +} diff --git a/app/Modules/Shared/Infrastructure/Images/GdImageResizer.php b/app/Modules/Shared/Infrastructure/Images/GdImageResizer.php new file mode 100644 index 0000000..2abd80b --- /dev/null +++ b/app/Modules/Shared/Infrastructure/Images/GdImageResizer.php @@ -0,0 +1,141 @@ + $maxSizes + * @return list|null + */ + public function jpegVersions(string $path, array $maxSizes): ?array + { + $image = $this->read($path); + + if ($image === null) { + return null; + } + + $orientation = $this->orientation($path); + + try { + $versions = []; + + // Each version is scaled straight from the original and turned + // upright afterwards, so only one full-size image is in memory. + foreach ($maxSizes as $maxSize) { + $scaled = $this->upright($this->scaled($image, $maxSize), $orientation); + $versions[] = ['bytes' => $this->jpeg($scaled), 'width' => imagesx($scaled), 'height' => imagesy($scaled)]; + imagedestroy($scaled); + } + + return $versions; + } finally { + imagedestroy($image); + } + } + + private function orientation(string $path): int + { + $exif = function_exists('exif_read_data') ? @exif_read_data($path) : false; + + return is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1; + } + + private function read(string $path): ?GdImage + { + $info = @getimagesize($path); + + if ($info === false || $info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) { + return null; + } + + $image = match ($info[2]) { + IMAGETYPE_JPEG => @imagecreatefromjpeg($path), + IMAGETYPE_PNG => @imagecreatefrompng($path), + IMAGETYPE_GIF => @imagecreatefromgif($path), + IMAGETYPE_WEBP => @imagecreatefromwebp($path), + default => false, + }; + + if ($image === false) { + return null; + } + + return $image; + } + + /** + * Phone cameras save photos sideways and tell the right way up in EXIF. + */ + private function upright(GdImage $image, int $orientation): GdImage + { + $rotated = match ($orientation) { + 3 => imagerotate($image, 180, 0), + 5, 6 => imagerotate($image, -90, 0), + 7, 8 => imagerotate($image, 90, 0), + default => $image, + }; + + if ($rotated === false) { + return $image; + } + + if (in_array($orientation, [2, 5, 7], true)) { + imageflip($rotated, IMG_FLIP_HORIZONTAL); + } elseif ($orientation === 4) { + imageflip($rotated, IMG_FLIP_VERTICAL); + } + + if ($rotated !== $image) { + imagedestroy($image); + } + + return $rotated; + } + + /** + * A copy whose longer side is at most the given size, on white: JPEG has + * no transparency. + */ + private function scaled(GdImage $image, int $maxSize): GdImage + { + $width = imagesx($image); + $height = imagesy($image); + $ratio = min(1, $maxSize / max($width, $height)); + $newWidth = max(1, (int) round($width * $ratio)); + $newHeight = max(1, (int) round($height * $ratio)); + + $copy = imagecreatetruecolor($newWidth, $newHeight); + imagefill($copy, 0, 0, (int) imagecolorallocate($copy, 255, 255, 255)); + imagecopyresampled($copy, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + + return $copy; + } + + private function jpeg(GdImage $image): string + { + ob_start(); + imagejpeg($image, null, self::QUALITY); + + return (string) ob_get_clean(); + } +} diff --git a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php index d5b802c..2bd806b 100644 --- a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php +++ b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php @@ -5,9 +5,11 @@ namespace App\Modules\Shared\Infrastructure\Providers; use App\Models\User; use App\Modules\Shared\Application\Contracts\EventDispatcher; use App\Modules\Shared\Application\Contracts\HolidayOverrides; +use App\Modules\Shared\Application\Contracts\ImageResizer; use App\Modules\Shared\Application\Contracts\Settings; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher; +use App\Modules\Shared\Infrastructure\Images\GdImageResizer; use App\Modules\Shared\Infrastructure\Persistence\DatabaseHolidayOverrides; use App\Modules\Shared\Infrastructure\Persistence\DatabaseSettings; use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager; @@ -28,6 +30,7 @@ class SharedServiceProvider extends ServiceProvider EventDispatcher::class => LaravelEventDispatcher::class, Settings::class => DatabaseSettings::class, HolidayOverrides::class => DatabaseHolidayOverrides::class, + ImageResizer::class => GdImageResizer::class, ]; public function boot(): void diff --git a/app/View/MainMenu.php b/app/View/MainMenu.php index 17f480d..45e7ebe 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -102,6 +102,7 @@ final class MainMenu 'maintenance' => [ 'label' => 'layout.group_maintenance', 'items' => [ + ['route' => 'inventory.index', 'pattern' => ['inventory.index', 'inventory.items.*', 'inventory.groups'], 'label' => 'layout.inventory', 'ability' => 'inventory.menu'], ['route' => 'catalog.index', 'pattern' => ['catalog.index', 'catalog.service-units.*', 'catalog.services.*', 'catalog.work-types.*'], 'label' => 'layout.catalog', 'ability' => 'catalog.manage'], ['route' => 'catalog.workflow-templates', 'pattern' => ['catalog.workflow-templates*'], 'label' => 'layout.workflow_templates', 'ability' => 'catalog.manage'], ['route' => 'catalog.prices', 'pattern' => ['catalog.prices', 'catalog.products.*', 'catalog.vat-rates.*'], 'label' => 'layout.price_list_admin', 'ability' => 'catalog.manage'], diff --git a/bootstrap/providers.php b/bootstrap/providers.php index eca145e..418d5be 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -5,6 +5,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Dashboard\Infrastructure\Providers\DashboardServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; +use App\Modules\Inventory\Infrastructure\Providers\InventoryServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; use App\Modules\Notifications\Infrastructure\Providers\NotificationsServiceProvider; use App\Modules\Reports\Infrastructure\Providers\ReportsServiceProvider; @@ -26,6 +27,7 @@ return [ TimeTrackingServiceProvider::class, ExpensesServiceProvider::class, SalesServiceProvider::class, + InventoryServiceProvider::class, BillingServiceProvider::class, NotificationsServiceProvider::class, ReportsServiceProvider::class, diff --git a/database/factories/StockItemFactory.php b/database/factories/StockItemFactory.php new file mode 100644 index 0000000..18152f3 --- /dev/null +++ b/database/factories/StockItemFactory.php @@ -0,0 +1,38 @@ + + */ +class StockItemFactory extends Factory +{ + protected $model = StockItemModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'stock_item_group_id' => StockItemGroupModel::factory(), + 'name' => fake()->unique()->words(3, true), + 'unit' => StockUnit::Piece, + 'code' => null, + 'supplier' => null, + 'reorder_level_milli' => null, + 'average_cost_hundredths' => 0, + 'is_active' => true, + ]; + } + + public function inactive(): static + { + return $this->state(fn (): array => ['is_active' => false]); + } +} diff --git a/database/factories/StockItemGroupFactory.php b/database/factories/StockItemGroupFactory.php new file mode 100644 index 0000000..f0f5c24 --- /dev/null +++ b/database/factories/StockItemGroupFactory.php @@ -0,0 +1,26 @@ + + */ +class StockItemGroupFactory extends Factory +{ + protected $model = StockItemGroupModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->unique()->words(2, true), + 'sort_order' => fake()->unique()->numberBetween(1, 100000), + 'is_active' => true, + ]; + } +} diff --git a/database/migrations/2026_11_26_140647_create_stock_tables.php b/database/migrations/2026_11_26_140647_create_stock_tables.php new file mode 100644 index 0000000..96d2d26 --- /dev/null +++ b/database/migrations/2026_11_26_140647_create_stock_tables.php @@ -0,0 +1,78 @@ +id(); + $table->string('name', 150); + $table->unsignedInteger('sort_order'); + $table->boolean('is_active')->default(true); + $table->timestamps(); + }); + + Schema::create('stock_items', function (Blueprint $table) { + $table->id(); + $table->foreignId('stock_item_group_id')->constrained()->restrictOnDelete(); + $table->string('name', 150); + $table->string('unit', 20); + $table->string('code', 150)->nullable(); + $table->string('supplier', 150)->nullable(); + $table->bigInteger('reorder_level_milli')->nullable(); + $table->bigInteger('average_cost_hundredths')->default(0); + $table->string('image_path')->nullable(); + $table->string('thumbnail_path')->nullable(); + $table->boolean('is_active')->default(true); + $table->timestamps(); + + $table->index('code'); + }); + + Schema::create('stock_movements', function (Blueprint $table) { + $table->id(); + $table->foreignId('stock_item_id')->constrained()->restrictOnDelete(); + $table->string('kind', 20); + $table->bigInteger('quantity_milli'); + $table->bigInteger('unit_cost_hundredths'); + $table->bigInteger('value_cents'); + $table->date('occurred_on'); + $table->timestamp('recorded_at'); + $table->foreignId('user_id')->constrained()->restrictOnDelete(); + $table->foreignId('task_id')->nullable()->constrained()->restrictOnDelete(); + $table->foreignId('customer_job_id')->nullable()->constrained()->restrictOnDelete(); + $table->unsignedBigInteger('machine_id')->nullable(); + $table->unsignedBigInteger('quick_sale_order_line_id')->nullable(); + $table->unsignedBigInteger('maintenance_record_id')->nullable(); + $table->unsignedBigInteger('inventory_count_id')->nullable(); + $table->foreignId('reverses_movement_id')->nullable()->unique()->constrained('stock_movements')->restrictOnDelete(); + $table->string('reason')->nullable(); + $table->string('supplier')->nullable(); + $table->string('document_number')->nullable(); + $table->timestamps(); + + $table->index(['stock_item_id', 'id']); + $table->index(['occurred_on', 'kind']); + $table->index('machine_id'); + }); + } + + public function down(): void + { + Schema::dropIfExists('stock_movements'); + Schema::dropIfExists('stock_items'); + Schema::dropIfExists('stock_item_groups'); + } +}; diff --git a/lang/en/inventory.php b/lang/en/inventory.php new file mode 100644 index 0000000..04d37cd --- /dev/null +++ b/lang/en/inventory.php @@ -0,0 +1,189 @@ + [ + 'piece' => 'pcs', + 'sheet' => 'sheet', + 'roll' => 'roll', + 'metre' => 'm', + 'square_metre' => 'm²', + 'litre' => 'l', + 'package' => 'pack', + ], + 'kinds' => [ + 'purchase' => 'Purchase', + 'consumption' => 'Use', + 'write_off' => 'Write-off', + 'adjustment' => 'Stock count correction', + 'reversal' => 'Reversal', + ], + + 'index' => [ + 'title' => 'Stock', + 'intro' => 'Balances of stock items. Items to order (balance at or below the reorder level) and negative balances are marked.', + 'search' => 'Search by name or code', + 'group' => 'Item group', + 'all_groups' => 'All groups', + 'only_reorder' => 'Only items to order', + 'include_inactive' => 'Also show items out of use', + 'new_item' => 'New item', + 'groups' => 'Item groups', + 'none' => 'No items match.', + 'count' => '{0} No items|{1} 1 item|[2,*] :count items', + 'total_value' => 'Total stock value: :value', + ], + 'columns' => [ + 'name' => 'Item', + 'group' => 'Group', + 'balance' => 'Balance', + 'reorder_level' => 'Reorder level', + 'status' => 'Status', + 'average_cost' => 'Average cost', + 'value' => 'Value', + 'time' => 'Time', + 'kind' => 'Kind', + 'quantity' => 'Quantity', + 'balance_after' => 'Balance after', + 'user' => 'Recorded by', + 'target' => 'For', + 'actions' => 'Actions', + ], + 'status' => [ + 'ok' => 'Enough', + 'reorder' => 'To order', + 'negative' => 'Negative balance', + 'inactive' => 'Out of use', + ], + + 'groups' => [ + 'title' => 'Item groups', + 'intro' => 'Groups order the stock list and the material search of the machine console. Groups that have been used are not deleted but taken out of use.', + 'new' => 'New group', + 'name' => 'Group name', + 'add' => 'Add group', + 'items' => '{0} no items|{1} 1 item|[2,*] :count items', + 'rename' => 'Rename', + 'rename_named' => 'Rename: :name', + 'save' => 'Save name', + 'cancel' => 'Cancel', + 'up_named' => 'Move up: :name', + 'down_named' => 'Move down: :name', + 'deactivate_named' => 'Take out of use: :name', + 'activate_named' => 'Take into use: :name', + 'deactivate' => 'Take out of use', + 'activate' => 'Take into use', + 'none' => 'No groups yet. Add the first group, e.g. Papers and boards.', + 'added' => 'Group :name added.', + 'renamed' => 'Group renamed: :name.', + 'moved_up' => ':name moved up.', + 'moved_down' => ':name moved down.', + 'first' => ':name is already first.', + 'last' => ':name is already last.', + 'activated' => ':name taken into use.', + 'deactivated' => ':name taken out of use.', + 'back' => 'Back to stock', + ], + + 'form' => [ + 'create_title' => 'New item', + 'edit_title' => 'Edit item', + 'group' => 'Item group', + 'name' => 'Name', + 'unit' => 'Unit', + 'code' => 'Product code or barcode', + 'code_hint' => 'Optional. A barcode scanner types the code into the search field.', + 'supplier' => 'Supplier', + 'reorder_level' => 'Reorder level', + 'reorder_level_hint' => 'Optional. When the balance is at or below this, the item is shown as to order. At most three decimals.', + 'image' => 'Image', + 'image_hint' => 'An optional image that helps recognise the item on a touch screen. JPEG, PNG, WebP or GIF, at most :size MB.', + 'remove_image' => 'Remove image', + 'current_image' => 'Current image', + 'save' => 'Save', + 'cancel' => 'Cancel', + 'no_groups' => 'Add an item group first.', + 'created' => 'Item :name added.', + 'updated' => 'Item :name saved.', + ], + + 'item' => [ + 'details' => 'Details', + 'balance' => 'Balance', + 'edit' => 'Edit', + 'deactivate' => 'Take out of use', + 'activate' => 'Take into use', + 'deactivated' => 'The item was taken out of use. It can no longer be used, but its movements are kept.', + 'activated' => 'The item was taken into use.', + 'inactive_note' => 'The item is out of use.', + 'image_alt' => 'Image: :name', + 'history' => 'Movement history', + 'history_none' => 'No movements yet.', + 'history_limit' => 'At most the :count newest movements are shown.', + 'reverse' => 'Reverse', + 'reverse_named' => 'Reverse movement :kind :quantity (:time)', + 'reverse_title' => 'Reverse the movement?', + 'reverse_text' => 'A reversal that cancels :kind :quantity is recorded for today. The original movement stays in the history.', + 'reverse_confirm' => 'Record reversal', + 'reversed' => 'Reversal recorded. Balance now :balance.', + 'reversed_by' => 'Reversed (#:number)', + 'reverses' => 'Reverses movement #:number', + 'target_task' => 'Task #:id', + 'target_machine' => 'Machine #:id', + 'target_order' => 'Quick sale order', + 'target_maintenance' => 'Maintenance', + 'target_count' => 'Stock count #:id', + 'document' => 'Document :number', + ], + + 'purchase' => [ + 'title' => 'Record purchase', + 'intro' => 'Goods received. Give the price without VAT either in total or per unit; the average cost is updated.', + 'day' => 'Day', + 'quantity' => 'Quantity (:unit)', + 'total_price' => 'Total price (€, VAT 0)', + 'unit_price' => 'Or unit price (€/:unit, VAT 0)', + 'unit_price_hint' => 'At most four decimals, e.g. 0.0123.', + 'supplier' => 'Supplier', + 'document_number' => 'Purchase invoice or receipt number', + 'save' => 'Record purchase', + 'saved' => 'Purchase recorded: :quantity. Balance now :balance, average cost :cost.', + ], + + 'write_off' => [ + 'title' => 'Record write-off', + 'quantity' => 'Quantity (:unit)', + 'reason' => 'Reason', + 'reason_hint' => 'E.g. damaged, expired.', + 'save' => 'Record write-off', + 'saved' => 'Write-off recorded: :quantity. Balance now :balance.', + ], + + 'use' => [ + 'title' => 'Record use without a target', + 'intro' => 'Use with no task or machine (e.g. a test run). A task\'s material is recorded on the task.', + 'quantity' => 'Quantity (:unit)', + 'reason' => 'Reason', + 'save' => 'Record use', + 'saved' => 'Use recorded: :quantity. Balance now :balance.', + 'negative_warning' => 'The balance is negative. Correct it with a purchase or a stock count.', + ], + + 'errors' => [ + 'name' => 'Enter a name (1–150 characters).', + 'name_taken' => 'The name is already in use.', + 'group' => 'Choose an item group in use.', + 'quantity' => 'Enter a quantity greater than zero, at most three decimals (e.g. 2.5).', + 'reorder_level' => 'Enter the reorder level as a number, at most three decimals.', + 'cost' => 'Enter a price in euros (e.g. 12.50) or a unit price with at most four decimals.', + 'price_required' => 'Enter a total price or a unit price.', + 'day' => 'Enter the day as dd.mm.yyyy.', + 'reason' => 'Enter a reason.', + 'inactive' => 'The item is out of use and cannot be used.', + 'image' => 'The file is not a usable image (JPEG, PNG, WebP or GIF).', + 'image_too_large' => 'The image is too large (at most :size MB).', + 'not_found' => 'The row was not found. Refresh the page.', + 'already_reversed' => 'The movement has already been reversed.', + 'not_reversible' => 'A reversal or a stock count correction cannot be reversed.', + 'reversal_not_allowed' => 'You can only undo your own use recorded today. Management makes other corrections.', + ], +]; diff --git a/lang/en/layout.php b/lang/en/layout.php index 09e3182..3995e79 100644 --- a/lang/en/layout.php +++ b/lang/en/layout.php @@ -17,6 +17,9 @@ return [ 'users' => 'Users', 'company' => 'Company details', 'holidays' => 'Public holidays', + 'inventory' => 'Stock', + 'inventory_counts' => 'Stock counts', + 'machines' => 'Machines', 'catalog' => 'Basic data', 'prices' => 'Price list', 'logout' => 'Sign out', diff --git a/lang/fi/inventory.php b/lang/fi/inventory.php new file mode 100644 index 0000000..c56c755 --- /dev/null +++ b/lang/fi/inventory.php @@ -0,0 +1,189 @@ + [ + 'piece' => 'kpl', + 'sheet' => 'arkki', + 'roll' => 'rulla', + 'metre' => 'm', + 'square_metre' => 'm²', + 'litre' => 'l', + 'package' => 'pakkaus', + ], + 'kinds' => [ + 'purchase' => 'Hankinta', + 'consumption' => 'Käyttö', + 'write_off' => 'Hävikki', + 'adjustment' => 'Inventaariokorjaus', + 'reversal' => 'Vastakirjaus', + ], + + 'index' => [ + 'title' => 'Varasto', + 'intro' => 'Nimikkeiden saldot. Tilattavat nimikkeet (saldo hälytysrajalla tai alle) ja negatiiviset saldot näytetään merkinnällä.', + 'search' => 'Hae nimellä tai koodilla', + 'group' => 'Nimikeryhmä', + 'all_groups' => 'Kaikki ryhmät', + 'only_reorder' => 'Vain tilattavat', + 'include_inactive' => 'Näytä myös käytöstä poistetut', + 'new_item' => 'Uusi nimike', + 'groups' => 'Nimikeryhmät', + 'none' => 'Ei nimikkeitä näillä ehdoilla.', + 'count' => '{0} Ei nimikkeitä|{1} 1 nimike|[2,*] :count nimikettä', + 'total_value' => 'Varaston arvo yhteensä: :value', + ], + 'columns' => [ + 'name' => 'Nimike', + 'group' => 'Ryhmä', + 'balance' => 'Saldo', + 'reorder_level' => 'Hälytysraja', + 'status' => 'Tila', + 'average_cost' => 'Keskihinta', + 'value' => 'Arvo', + 'time' => 'Aika', + 'kind' => 'Laji', + 'quantity' => 'Määrä', + 'balance_after' => 'Saldo jälkeen', + 'user' => 'Kirjaaja', + 'target' => 'Kohde', + 'actions' => 'Toiminnot', + ], + 'status' => [ + 'ok' => 'Riittää', + 'reorder' => 'Tilattava', + 'negative' => 'Saldo negatiivinen', + 'inactive' => 'Poistettu käytöstä', + ], + + 'groups' => [ + 'title' => 'Nimikeryhmät', + 'intro' => 'Ryhmät järjestävät varastolistan ja konekäyttöliittymän materiaalihaun. Käytössä olleita ryhmiä ei poisteta, vaan ne poistetaan käytöstä.', + 'new' => 'Uusi ryhmä', + 'name' => 'Ryhmän nimi', + 'add' => 'Lisää ryhmä', + 'items' => '{0} ei nimikkeitä|{1} 1 nimike|[2,*] :count nimikettä', + 'rename' => 'Nimeä uudelleen', + 'rename_named' => 'Nimeä uudelleen: :name', + 'save' => 'Tallenna nimi', + 'cancel' => 'Peruuta', + 'up_named' => 'Siirrä ylös: :name', + 'down_named' => 'Siirrä alas: :name', + 'deactivate_named' => 'Poista käytöstä: :name', + 'activate_named' => 'Ota käyttöön: :name', + 'deactivate' => 'Poista käytöstä', + 'activate' => 'Ota käyttöön', + 'none' => 'Ei vielä ryhmiä. Lisää ensimmäinen ryhmä, esim. Paperit ja kartongit.', + 'added' => 'Ryhmä :name lisätty.', + 'renamed' => 'Ryhmä nimetty: :name.', + 'moved_up' => ':name siirretty ylöspäin.', + 'moved_down' => ':name siirretty alaspäin.', + 'first' => ':name on jo ensimmäisenä.', + 'last' => ':name on jo viimeisenä.', + 'activated' => ':name otettu käyttöön.', + 'deactivated' => ':name poistettu käytöstä.', + 'back' => 'Takaisin varastoon', + ], + + 'form' => [ + 'create_title' => 'Uusi nimike', + 'edit_title' => 'Muokkaa nimikettä', + 'group' => 'Nimikeryhmä', + 'name' => 'Nimi', + 'unit' => 'Yksikkö', + 'code' => 'Tuotekoodi tai viivakoodi', + 'code_hint' => 'Vapaaehtoinen. Viivakoodinlukija kirjoittaa koodin hakukenttään.', + 'supplier' => 'Toimittaja', + 'reorder_level' => 'Hälytysraja', + 'reorder_level_hint' => 'Vapaaehtoinen. Kun saldo on tällä tai alle, nimike näytetään tilattavana. Enintään kolme desimaalia.', + 'image' => 'Kuva', + 'image_hint' => 'Vapaaehtoinen kuva, joka helpottaa nimikkeen tunnistamista kosketusnäytöllä. JPEG, PNG, WebP tai GIF, enintään :size Mt.', + 'remove_image' => 'Poista kuva', + 'current_image' => 'Nykyinen kuva', + 'save' => 'Tallenna', + 'cancel' => 'Peruuta', + 'no_groups' => 'Lisää ensin nimikeryhmä.', + 'created' => 'Nimike :name lisätty.', + 'updated' => 'Nimike :name tallennettu.', + ], + + 'item' => [ + 'details' => 'Tiedot', + 'balance' => 'Saldo', + 'edit' => 'Muokkaa', + 'deactivate' => 'Poista käytöstä', + 'activate' => 'Ota käyttöön', + 'deactivated' => 'Nimike poistettu käytöstä. Sitä ei voi enää kirjata käytetyksi, mutta tapahtumat säilyvät.', + 'activated' => 'Nimike otettu käyttöön.', + 'inactive_note' => 'Nimike on poistettu käytöstä.', + 'image_alt' => 'Kuva: :name', + 'history' => 'Tapahtumahistoria', + 'history_none' => 'Ei vielä tapahtumia.', + 'history_limit' => 'Näytetään enintään :count uusinta tapahtumaa.', + 'reverse' => 'Vastakirjaa', + 'reverse_named' => 'Vastakirjaa tapahtuma :kind :quantity (:time)', + 'reverse_title' => 'Vastakirjataanko tapahtuma?', + 'reverse_text' => 'Tapahtumalle :kind :quantity kirjataan tälle päivälle vastakirjaus, joka kumoaa sen. Alkuperäinen tapahtuma säilyy historiassa.', + 'reverse_confirm' => 'Kirjaa vastakirjaus', + 'reversed' => 'Vastakirjaus kirjattu. Saldo nyt :balance.', + 'reversed_by' => 'Vastakirjattu (#:number)', + 'reverses' => 'Kumoaa tapahtuman #:number', + 'target_task' => 'Tehtävä #:id', + 'target_machine' => 'Kone #:id', + 'target_order' => 'Pikamyyntitilaus', + 'target_maintenance' => 'Huolto', + 'target_count' => 'Inventaario #:id', + 'document' => 'Tosite :number', + ], + + 'purchase' => [ + 'title' => 'Kirjaa hankinta', + 'intro' => 'Saapunut tavara. Anna hinta ilman ALV:tä joko yhteensä tai yksikköhintana; keskihinta päivitetään.', + 'day' => 'Päivä', + 'quantity' => 'Määrä (:unit)', + 'total_price' => 'Hinta yhteensä (€, ALV 0)', + 'unit_price' => 'Tai yksikköhinta (€/:unit, ALV 0)', + 'unit_price_hint' => 'Enintään neljä desimaalia, esim. 0,0123.', + 'supplier' => 'Toimittaja', + 'document_number' => 'Ostolaskun tai kuitin numero', + 'save' => 'Kirjaa hankinta', + 'saved' => 'Hankinta kirjattu: :quantity. Saldo nyt :balance, keskihinta :cost.', + ], + + 'write_off' => [ + 'title' => 'Kirjaa hävikki tai poisto', + 'quantity' => 'Määrä (:unit)', + 'reason' => 'Syy', + 'reason_hint' => 'Esim. vaurioitunut, vanhentunut.', + 'save' => 'Kirjaa hävikki', + 'saved' => 'Hävikki kirjattu: :quantity. Saldo nyt :balance.', + ], + + 'use' => [ + 'title' => 'Kirjaa käyttö ilman kohdetta', + 'intro' => 'Käyttö, jolla ei ole tehtävää tai konetta (esim. koeajo). Tehtävän materiaalit kirjataan tehtävältä.', + 'quantity' => 'Määrä (:unit)', + 'reason' => 'Syy', + 'save' => 'Kirjaa käyttö', + 'saved' => 'Käyttö kirjattu: :quantity. Saldo nyt :balance.', + 'negative_warning' => 'Saldo on negatiivinen. Korjaa se hankinnalla tai inventaariolla.', + ], + + 'errors' => [ + 'name' => 'Anna nimi (1–150 merkkiä).', + 'name_taken' => 'Nimi on jo käytössä.', + 'group' => 'Valitse käytössä oleva nimikeryhmä.', + 'quantity' => 'Anna määrä nollaa suurempana lukuna, enintään kolme desimaalia (esim. 2,5).', + 'reorder_level' => 'Anna hälytysraja lukuna, enintään kolme desimaalia.', + 'cost' => 'Anna hinta euroina (esim. 12,50) tai yksikköhinta enintään neljällä desimaalilla.', + 'price_required' => 'Anna hinta yhteensä tai yksikköhinta.', + 'day' => 'Anna päivä muodossa pp.kk.vvvv.', + 'reason' => 'Anna syy.', + 'inactive' => 'Nimike on poistettu käytöstä, eikä sitä voi kirjata käytetyksi.', + 'image' => 'Tiedosto ei ole kuva, jota voi käyttää (JPEG, PNG, WebP tai GIF).', + 'image_too_large' => 'Kuva on liian suuri (enintään :size Mt).', + 'not_found' => 'Riviä ei löytynyt. Päivitä sivu.', + 'already_reversed' => 'Tapahtuma on jo vastakirjattu.', + 'not_reversible' => 'Vastakirjausta tai inventaariokorjausta ei voi vastakirjata.', + 'reversal_not_allowed' => 'Voit perua vain oman tänään kirjatun käyttösi. Muut korjaukset tekee johto.', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index e0fe33c..b5f5606 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -17,6 +17,9 @@ return [ 'users' => 'Käyttäjät', 'company' => 'Yritystiedot', 'holidays' => 'Arkipyhät', + 'inventory' => 'Varasto', + 'inventory_counts' => 'Inventaario', + 'machines' => 'Koneet', 'catalog' => 'Pohjatiedot', 'prices' => 'Hinnasto', 'logout' => 'Kirjaudu ulos', diff --git a/resources/views/components/inventory/stock-status.blade.php b/resources/views/components/inventory/stock-status.blade.php new file mode 100644 index 0000000..4c438fa --- /dev/null +++ b/resources/views/components/inventory/stock-status.blade.php @@ -0,0 +1,31 @@ +{{-- + A stock item's state as text with an icon, not colour alone: negative + balance, to order (at or below the reorder level), out of use or enough. +--}} +@props(['item']) + +class('inline-flex flex-wrap items-center gap-x-2 gap-y-1') }}> + @if ($item->isNegative()) + + + @elseif ($item->needsReorder()) + + + @else + + + @endif + + @unless ($item->isActive) + + + @endunless + diff --git a/tests/Browser/InventoryAccessibilityTest.php b/tests/Browser/InventoryAccessibilityTest.php new file mode 100644 index 0000000..b8fd908 --- /dev/null +++ b/tests/Browser/InventoryAccessibilityTest.php @@ -0,0 +1,63 @@ +user = User::factory()->management()->create(['name' => 'Johtaja']); + $this->actingAs($this->user); + ServiceUnitModel::factory()->usingStock()->create(['name' => 'Painotuotanto']); + $group = StockItemGroupModel::factory()->create(['name' => 'Paperit']); + $this->item = StockItemModel::factory()->create([ + 'stock_item_group_id' => $group->id, + 'name' => 'Valokuvapaperi', + 'unit' => 'sheet', + 'reorder_level_milli' => 50_000, + 'average_cost_hundredths' => 5_000, + ]); + StockMovementModel::query()->create([ + 'stock_item_id' => $this->item->id, 'kind' => 'purchase', 'quantity_milli' => 40_000, 'unit_cost_hundredths' => 5_000, + 'value_cents' => 2_000, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->user->id, + ]); +}); + +it('has no accessibility issues on the stock pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) { + $url = match ($page) { + 'index' => route('inventory.index'), + 'item' => route('inventory.items.show', $this->item->id), + 'form' => route('inventory.items.edit', $this->item->id), + 'groups' => route('inventory.groups'), + }; + + $visit = visit($url); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee(match ($page) { + 'groups' => 'Paperit', 'form' => __('inventory.form.edit_title'), default => 'Valokuvapaperi' + }) + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with(['index', 'item', 'form', 'groups'])->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + +it('reverses a movement in a dialog that returns focus', function () { + visit(route('inventory.items.show', $this->item->id)) + ->assertSee(__('inventory.status.reorder')) + ->click(__('inventory.item.reverse')) + ->assertSee(__('inventory.item.reverse_title')) + ->assertNoAccessibilityIssues(level: 2) + ->click(__('inventory.item.reverse_confirm')) + ->assertSee('Vastakirjaus kirjattu') + ->assertScript('document.activeElement.id', 'item-status'); +}); diff --git a/tests/Feature/Modules/Inventory/StockTest.php b/tests/Feature/Modules/Inventory/StockTest.php new file mode 100644 index 0000000..ef81298 --- /dev/null +++ b/tests/Feature/Modules/Inventory/StockTest.php @@ -0,0 +1,216 @@ +manager = User::factory()->management()->create(['name' => 'Maija Johto']); + $this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']); + $this->papers = StockItemGroupModel::factory()->create(['name' => 'Paperit', 'sort_order' => 1]); + $this->paper = StockItemModel::factory()->create([ + 'stock_item_group_id' => $this->papers->id, + 'name' => 'Valokuvapaperi 10×15', + 'unit' => 'sheet', + 'code' => '6417000123', + 'reorder_level_milli' => 20_000, + ]); +}); + +function purchaseStock(int $itemId, string $quantity, string $total = '', string $unitPrice = ''): mixed +{ + return Livewire::test('inventory::item', ['item' => $itemId]) + ->set('purchaseQuantity', $quantity) + ->set('purchaseTotal', $total) + ->set('purchaseUnitPrice', $unitPrice) + ->call('recordPurchase'); +} + +it('shows the stock menu link only when a service unit uses stock', function () { + $this->actingAs($this->employee); + + $this->get(route('home'))->assertDontSee(__('layout.inventory')); + + ServiceUnitModel::factory()->usingStock()->create(); + + $this->get(route('home'))->assertSee(__('layout.inventory')); + $this->get(route('inventory.index'))->assertOk()->assertSee('Valokuvapaperi 10×15'); + + $this->actingAs(User::factory()->subcontractor()->create()); + $this->get(route('inventory.index'))->assertForbidden(); +}); + +it('records purchases at a moving average cost and shows costs only to management', function () { + $this->actingAs($this->manager); + + purchaseStock($this->paper->id, '100', total: '50,00')->assertHasNoErrors(); + purchaseStock($this->paper->id, '100', unitPrice: '0,70') + ->assertHasNoErrors() + ->assertSet('message', fn (string $message) => str_contains($message, "Saldo nyt 200\u{00A0}arkki, keskihinta 0,60\u{00A0}€")); + + expect($this->paper->fresh()->average_cost_hundredths)->toBe(6_000) + ->and(StockMovementModel::query()->where('kind', 'purchase')->sum('value_cents'))->toBe(12_000); + + Livewire::test('inventory::index')->assertSee(__('inventory.columns.average_cost'))->assertSee("120,00\u{00A0}€", false); + + $this->actingAs($this->employee); + Livewire::test('inventory::index') + ->assertSee("200\u{00A0}arkki", false) + ->assertDontSee(__('inventory.columns.average_cost')) + ->assertDontSee("120,00\u{00A0}€", false); + Livewire::test('inventory::item', ['item' => $this->paper->id]) + ->assertDontSee(__('inventory.purchase.title')) + ->call('recordPurchase') + ->assertForbidden(); +}); + +it('requires a price and a positive quantity for a purchase', function () { + $this->actingAs($this->manager); + + purchaseStock($this->paper->id, '10')->assertHasErrors('purchaseTotal'); + purchaseStock($this->paper->id, '0', total: '5')->assertHasErrors('purchaseQuantity'); + purchaseStock($this->paper->id, '10', unitPrice: '0,12345')->assertHasErrors('purchaseUnitPrice'); + + expect(StockMovementModel::query()->count())->toBe(0); +}); + +it('lets anyone using stock record use with a reason, going negative with a warning, and undo it the same day', function () { + $this->actingAs($this->employee); + + Livewire::test('inventory::item', ['item' => $this->paper->id]) + ->set('useQuantity', '3') + ->call('recordUse') + ->assertHasErrors('useReason') + ->set('useReason', 'Koeajo') + ->call('recordUse') + ->assertHasNoErrors() + ->assertSee(__('inventory.status.negative')) + ->assertSee(__('inventory.use.negative_warning')); + + $use = StockMovementModel::query()->sole(); + expect($use->kind)->toBe(StockMovementKind::Consumption)->and($use->quantity_milli)->toBe(-3_000); + + Livewire::test('inventory::index', ['onlyReorder' => true])->assertSee('Valokuvapaperi 10×15'); + + Livewire::test('inventory::item', ['item' => $this->paper->id]) + ->call('confirmReverse', $use->id) + ->call('reverse') + ->assertSet('message', fn (string $message) => str_contains($message, 'Vastakirjaus kirjattu')); + + expect(StockMovementModel::query()->where('reverses_movement_id', $use->id)->sole()->quantity_milli)->toBe(3_000); + + $this->travel(1)->day(); + Livewire::test('inventory::item', ['item' => $this->paper->id])->call('confirmReverse', $use->id)->assertForbidden(); + + $other = StockMovementModel::query()->create([ + 'stock_item_id' => $this->paper->id, 'kind' => 'consumption', 'quantity_milli' => -1000, 'unit_cost_hundredths' => 0, + 'value_cents' => 0, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->manager->id, 'reason' => 'Testi', + ]); + Livewire::test('inventory::item', ['item' => $this->paper->id])->call('confirmReverse', $other->id)->assertForbidden(); +}); + +it('records write-offs with a reason for management only', function () { + $this->actingAs($this->manager); + + Livewire::test('inventory::item', ['item' => $this->paper->id]) + ->set('writeOffQuantity', '2,5') + ->call('recordWriteOff') + ->assertHasErrors('writeOffReason') + ->set('writeOffReason', 'Vaurioitunut') + ->call('recordWriteOff') + ->assertHasNoErrors(); + + expect(StockMovementModel::query()->sole()->only(['kind', 'quantity_milli', 'reason'])) + ->toBe(['kind' => StockMovementKind::WriteOff, 'quantity_milli' => -2_500, 'reason' => 'Vaurioitunut']); +}); + +it('does not let an item out of use be used', function () { + $this->actingAs($this->manager); + + Livewire::test('inventory::item', ['item' => $this->paper->id]) + ->call('toggleActive') + ->assertSee(__('inventory.item.inactive_note')) + ->assertDontSee(__('inventory.use.title')); + + Livewire::test('inventory::index')->assertDontSee('Valokuvapaperi 10×15'); + Livewire::test('inventory::index')->set('includeInactive', true)->assertSee('Valokuvapaperi 10×15'); +}); + +it('searches items by parts of the name or code', function () { + $this->actingAs($this->employee); + StockItemModel::factory()->create(['stock_item_group_id' => $this->papers->id, 'name' => 'Tarramateriaali kiiltävä']); + + Livewire::test('inventory::index') + ->set('search', 'KIILTAVA') + ->assertSee('Tarramateriaali kiiltävä') + ->assertDontSee('Valokuvapaperi') + ->set('search', '6417') + ->assertSee('Valokuvapaperi'); +}); + +it('adds and edits items and groups, with an image', function () { + Storage::fake('local'); + $this->actingAs($this->manager); + + Livewire::test('inventory::groups') + ->set('newName', 'Musteet') + ->call('add') + ->assertHasNoErrors() + ->set('newName', 'musteet') + ->call('add') + ->assertHasErrors('newName'); + + $inks = StockItemGroupModel::query()->where('name', 'Musteet')->sole(); + + Livewire::test('inventory::groups') + ->call('move', $inks->id, 'up') + ->assertSet('message', 'Musteet siirretty ylöspäin.') + ->call('startRename', $inks->id) + ->set('editingName', 'Musteet ja värit') + ->call('rename') + ->assertHasNoErrors(); + + expect($inks->fresh()->name)->toBe('Musteet ja värit') + ->and($inks->fresh()->sort_order)->toBeLessThan($this->papers->fresh()->sort_order); + + Livewire::test('inventory::item-form') + ->set('groupId', (string) $inks->id) + ->set('name', 'Muste syaani') + ->set('unit', 'litre') + ->set('reorderLevel', '0,5') + ->set('image', UploadedFile::fake()->image('muste.jpg', 300, 200)) + ->call('save') + ->assertHasNoErrors(); + + $ink = StockItemModel::query()->where('name', 'Muste syaani')->sole(); + + expect($ink->reorder_level_milli)->toBe(500) + ->and($ink->image_path)->not->toBeNull(); + Storage::disk('local')->assertExists($ink->thumbnail_path); + $this->get(route('inventory.items.image', [$ink->id, 'thumbnail']))->assertOk(); + + Livewire::test('inventory::item-form', ['item' => $ink->id]) + ->set('name', 'Valokuvapaperi 10×15') + ->call('save') + ->assertHasErrors('name') + ->set('name', 'Muste syaani 1 l') + ->set('removeImage', true) + ->call('save') + ->assertHasNoErrors(); + + expect($ink->fresh()->image_path)->toBeNull(); + Storage::disk('local')->assertMissing($ink->thumbnail_path); + + $this->actingAs($this->employee); + $this->get(route('inventory.items.create'))->assertForbidden(); + $this->get(route('inventory.groups'))->assertForbidden(); +}); diff --git a/tests/Feature/Modules/Jobs/TaskImagesTest.php b/tests/Feature/Modules/Jobs/TaskImagesTest.php index 5de1770..01876bf 100644 --- a/tests/Feature/Modules/Jobs/TaskImagesTest.php +++ b/tests/Feature/Modules/Jobs/TaskImagesTest.php @@ -77,7 +77,7 @@ it('stores a downscaled image and a thumbnail without metadata and shows them on }); it('turns a sideways phone photo upright and leaves out its EXIF data', function () { - $stored = (new GdTaskImageFiles)->store(sidewaysJpeg(40, 20), $this->task->id); + $stored = app(GdTaskImageFiles::class)->store(sidewaysJpeg(40, 20), $this->task->id); $bytes = Storage::disk('local')->get($stored->path); expect(getimagesizefromstring($bytes)[0])->toBe(20) diff --git a/tests/Unit/Modules/Inventory/StockValuationTest.php b/tests/Unit/Modules/Inventory/StockValuationTest.php new file mode 100644 index 0000000..2b2731c --- /dev/null +++ b/tests/Unit/Modules/Inventory/StockValuationTest.php @@ -0,0 +1,77 @@ +milli)->toBe(2500) + ->and(StockQuantity::parsePositive('1 200')->milli)->toBe(1_200_000) + ->and(StockQuantity::parsePositive('0.125')->milli)->toBe(125) + ->and(StockQuantity::parse(''))->toBeNull() + ->and(StockQuantity::format(2500))->toBe('2,5') + ->and(StockQuantity::format(-1000))->toBe('-1') + ->and(StockQuantity::format(1_234_500))->toBe("1\u{00A0}234,5") + ->and(StockQuantity::inputValue(1_234_500))->toBe('1234,5'); +}); + +it('rejects quantities that are zero, negative or too precise', function (string $value) { + StockQuantity::parsePositive($value); +})->with(['0', '-1', '1,2345', 'abc'])->throws(InvalidStockQuantity::class); + +it('values stock at the moving average cost', function () { + // 10 sheets for 5,00 € → 0,50 € each (5 000 hundredths of a cent). + $average = StockValuation::averageAfterPurchase(0, 0, 10_000, 500); + expect($average)->toBe(5_000); + + // 10 more for 7,00 € → (5,00 + 7,00) / 20 = 0,60 €. + $average = StockValuation::averageAfterPurchase(10_000, $average, 10_000, 700); + expect($average)->toBe(6_000) + ->and(StockValuation::valueCents(2_500, $average))->toBe(150) + ->and(StockValuation::valueCents(-2_500, $average))->toBe(-150); + + // After a negative balance the purchase's own price is the average. + expect(StockValuation::averageAfterPurchase(-3_000, 6_000, 10_000, 1_000))->toBe(10_000) + // Ink at 0,0123 €/ml keeps its precision. + ->and(StockValuation::unitCostOf(1_000_000, 1_230))->toBe(123); +}); + +it('records use and write-offs negated at the average cost, and reverses them once', function () { + $item = StockItem::reconstitute(1, 1, new StockName('Paperi'), StockUnit::Sheet, null, null, null, 5_000, null, null, true); + $day = new DateTimeImmutable('2026-11-26'); + + $use = StockMovement::consumption($item, StockQuantity::parsePositive('3'), new StockUseTarget(taskId: 4, jobId: 2), $day, $day, 7); + $reversal = StockMovement::reversalOf(StockMovement::reconstitute(9, 1, StockMovementKind::Consumption, $use->quantityMilli(), 5_000, $use->valueCents(), $day, $day, 7, $use->target(), null, null, null, null, null), $day, $day, 7); + + expect($use->quantityMilli())->toBe(-3_000) + ->and($use->valueCents())->toBe(-150) + ->and($use->isOwnUseOf(7, $day))->toBeTrue() + ->and($use->isOwnUseOf(8, $day))->toBeFalse() + ->and($use->isOwnUseOf(7, $day->modify('+1 day')))->toBeFalse() + ->and($reversal->quantityMilli())->toBe(3_000) + ->and($reversal->valueCents())->toBe(150) + ->and($reversal->reversesMovementId())->toBe(9) + ->and($reversal->target()?->taskId)->toBe(4); + + StockMovement::reversalOf($reversal, $day, $day, 7); +})->throws(StockMovementNotReversible::class); + +it('needs a reason for use without a target', function () { + new StockUseTarget; +})->throws(StockReasonRequired::class); + +it('matches searches by words of the name or code regardless of case and dots', function () { + expect(StockSearch::matches('valokuva 10', 'Valokuvapaperi 10×15', null))->toBeTrue() + ->and(StockSearch::matches('PAAPERI', 'Pääperi', null))->toBeTrue() + ->and(StockSearch::matches('6417', 'Muste', '6417000123'))->toBeTrue() + ->and(StockSearch::matches('muste syaani', 'Muste magenta', null))->toBeFalse(); +});